blob: 69a9092e1c4218c18830636b547ec11c6dce87a0 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000022#include "CodeGenPGO.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000023#include "CodeGenTBAA.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000024#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000025#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000026#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000027#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000029#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000030#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000031#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000032#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000033#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000034#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000035#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000036#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000037#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000038#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000039#include "clang/Basic/Version.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000041#include "clang/Sema/SemaDiagnostic.h"
Sebastian Redl4a7eab22012-02-25 20:51:20 +000042#include "llvm/ADT/APSInt.h"
John McCallbeec5a02010-03-06 00:35:14 +000043#include "llvm/ADT/Triple.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000044#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000045#include "llvm/IR/CallingConv.h"
46#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/Module.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000050#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000051#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000052#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000053
Chris Lattnerbed31442007-05-28 01:07:47 +000054using namespace clang;
55using namespace CodeGen;
56
Julien Lerouge5a6b6982011-09-09 22:41:49 +000057static const char AnnotationSection[] = "llvm.metadata";
58
Alp Toker82862252013-12-28 21:58:40 +000059static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000060 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000061 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000062 case TargetCXXABI::GenericARM:
63 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000064 case TargetCXXABI::iOS64:
John McCall57625922013-01-25 23:36:14 +000065 case TargetCXXABI::GenericItanium:
Alp Toker82862252013-12-28 21:58:40 +000066 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000067 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000068 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000069 }
70
71 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000072}
73
Chandler Carruthbc55fe22009-11-12 17:24:48 +000074CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall568d4102013-04-16 22:48:20 +000075 llvm::Module &M, const llvm::DataLayout &TD,
David Blaikie9c902b52011-09-25 23:23:43 +000076 DiagnosticsEngine &diags)
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000077 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
78 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
79 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
80 TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
81 OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0),
Justin Bogner837a6f62014-04-18 21:52:00 +000082 NoObjCARCExceptionsMetadata(0), RRData(0), PGOReader(nullptr),
Justin Bogneref512b92014-01-06 22:27:43 +000083 CFConstantStringClassRef(0),
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000084 ConstantStringClassRef(0), NSConstantStringType(0),
85 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
86 BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
87 LifetimeStartFn(0), LifetimeEndFn(0),
88 SanitizerBlacklist(
89 llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
90 SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
91 : LangOpts.Sanitize) {
Will Dietzf54319c2013-01-18 11:30:38 +000092
Chris Lattnerece04092012-02-07 00:39:47 +000093 // Initialize the type cache.
94 llvm::LLVMContext &LLVMContext = M.getContext();
95 VoidTy = llvm::Type::getVoidTy(LLVMContext);
96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100 FloatTy = llvm::Type::getFloatTy(LLVMContext);
101 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103 PointerAlignInBytes =
104 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
105 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
106 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
107 Int8PtrTy = Int8Ty->getPointerTo(0);
108 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
109
John McCall882987f2013-02-28 19:01:20 +0000110 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
111
David Blaikiebbafb8a2012-03-11 07:00:24 +0000112 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000113 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000114 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000115 createOpenCLRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000116 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000117 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000118
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000119 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Will Dietzf54319c2013-01-18 11:30:38 +0000120 if (SanOpts.Thread ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000121 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
122 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Alp Toker82862252013-12-28 21:58:40 +0000123 getCXXABI().getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +0000124
Nick Lewycky207bce32011-04-21 23:44:07 +0000125 // If debug info or coverage generation is enabled, create the CGDebugInfo
126 // object.
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000127 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000128 CodeGenOpts.EmitGcovArcs ||
Nick Lewycky207bce32011-04-21 23:44:07 +0000129 CodeGenOpts.EmitGcovNotes)
130 DebugInfo = new CGDebugInfo(*this);
John McCallad7c5c12011-02-08 08:22:06 +0000131
132 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000133
David Blaikiebbafb8a2012-03-11 07:00:24 +0000134 if (C.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000135 ARCData = new ARCEntrypoints();
136 RRData = new RREntrypoints();
Justin Bogneref512b92014-01-06 22:27:43 +0000137
Justin Bogner837a6f62014-04-18 21:52:00 +0000138 if (!CodeGenOpts.InstrProfileInput.empty()) {
139 if (llvm::error_code EC = llvm::IndexedInstrProfReader::create(
140 CodeGenOpts.InstrProfileInput, PGOReader)) {
141 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
142 "Could not read profile: %0");
143 getDiags().Report(DiagID) << EC.message();
144 }
145 }
Chris Lattnera087ff92008-03-01 08:45:05 +0000146}
147
148CodeGenModule::~CodeGenModule() {
Peter Collingbournee1d20992011-07-27 20:29:46 +0000149 delete ObjCRuntime;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000150 delete OpenCLRuntime;
Peter Collingbournefe883422011-10-06 18:29:37 +0000151 delete CUDARuntime;
Ted Kremenekc168e502011-10-08 05:28:26 +0000152 delete TheTargetCodeGenInfo;
Dan Gohmand19ee8a2010-10-15 18:04:46 +0000153 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000154 delete DebugInfo;
John McCall31168b02011-06-15 23:02:42 +0000155 delete ARCData;
156 delete RRData;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000157}
158
David Chisnall481e3a82010-01-23 02:40:42 +0000159void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000160 // This is just isGNUFamily(), but we want to force implementors of
161 // new ABIs to decide how best to do this.
162 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000163 case ObjCRuntime::GNUstep:
164 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000165 case ObjCRuntime::ObjFW:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000166 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000167 return;
168
169 case ObjCRuntime::FragileMacOSX:
170 case ObjCRuntime::MacOSX:
171 case ObjCRuntime::iOS:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000172 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000173 return;
174 }
175 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000176}
177
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000178void CodeGenModule::createOpenCLRuntime() {
179 OpenCLRuntime = new CGOpenCLRuntime(*this);
180}
181
Peter Collingbournefe883422011-10-06 18:29:37 +0000182void CodeGenModule::createCUDARuntime() {
183 CUDARuntime = CreateNVCUDARuntime(*this);
184}
185
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000186void CodeGenModule::applyReplacements() {
187 for (ReplacementsTy::iterator I = Replacements.begin(),
188 E = Replacements.end();
189 I != E; ++I) {
190 StringRef MangledName = I->first();
191 llvm::Constant *Replacement = I->second;
192 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
193 if (!Entry)
194 continue;
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000195 llvm::Function *OldF = cast<llvm::Function>(Entry);
196 llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement);
197 if (!NewF) {
Reid Klecknerb78257d2014-02-03 18:54:51 +0000198 if (llvm::GlobalAlias *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
199 NewF = dyn_cast<llvm::Function>(Alias->getAliasedGlobal());
200 } else {
201 llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement);
202 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
203 CE->getOpcode() == llvm::Instruction::GetElementPtr);
204 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
205 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000206 }
207
208 // Replace old with new, but keep the old order.
209 OldF->replaceAllUsesWith(Replacement);
210 if (NewF) {
211 NewF->removeFromParent();
212 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
213 }
214 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000215 }
216}
217
Rafael Espindola208b5c02013-10-22 19:26:13 +0000218void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000219 // Check if the constructed aliases are well formed. It is really unfortunate
220 // that we have to do this in CodeGen, but we only construct mangled names
221 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000222 bool Error = false;
223 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
224 E = Aliases.end(); I != E; ++I) {
225 const GlobalDecl &GD = *I;
226 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
227 const AliasAttr *AA = D->getAttr<AliasAttr>();
228 StringRef MangledName = getMangledName(GD);
229 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
230 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000231 llvm::GlobalValue *GV = Alias->getAliasedGlobal();
Rafael Espindola93c7a652014-03-13 15:47:50 +0000232 if (!GV) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000233 Error = true;
234 getDiags().Report(AA->getLocation(), diag::err_cyclic_alias);
Rafael Espindola93c7a652014-03-13 15:47:50 +0000235 } else if (GV->isDeclaration()) {
236 Error = true;
237 getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000238 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000239
240 // We have to handle alias to weak aliases in here. LLVM itself disallows
241 // this since the object semantics would not match the IL one. For
242 // compatibility with gcc we implement it by just pointing the alias
243 // to its aliasee's aliasee. We also warn, since the user is probably
244 // expecting the link to be weak.
245 llvm::Constant *Aliasee = Alias->getAliasee();
246 llvm::GlobalValue *AliaseeGV;
247 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) {
248 assert((CE->getOpcode() == llvm::Instruction::BitCast ||
249 CE->getOpcode() == llvm::Instruction::AddrSpaceCast) &&
250 "Unsupported aliasee");
251 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
252 } else {
253 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
254 }
255 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
256 if (GA->mayBeOverridden()) {
257 getDiags().Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
258 << GA->getAliasedGlobal()->getName() << GA->getName();
259 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
260 GA->getAliasee(), Alias->getType());
261 Alias->setAliasee(Aliasee);
262 }
263 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000264 }
265 if (!Error)
266 return;
267
268 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
269 E = Aliases.end(); I != E; ++I) {
270 const GlobalDecl &GD = *I;
271 StringRef MangledName = getMangledName(GD);
272 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
273 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
274 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
275 Alias->eraseFromParent();
276 }
277}
278
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000279void CodeGenModule::clear() {
280 DeferredDeclsToEmit.clear();
281}
282
Ted Kremenek2c674f62008-08-05 18:50:11 +0000283void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000284 EmitDeferred();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000285 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000286 checkAliases();
Eli Friedman5866fe32010-01-08 00:50:11 +0000287 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000288 EmitCXXGlobalDtorFunc();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000289 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000290 if (ObjCRuntime)
291 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000292 AddGlobalCtor(ObjCInitFunction);
Justin Bognerf2ea7752014-04-10 18:13:13 +0000293 if (getCodeGenOpts().ProfileInstrGenerate)
294 if (llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this))
295 AddGlobalCtor(PGOInit, 0);
Justin Bogner837a6f62014-04-18 21:52:00 +0000296 if (PGOReader && PGOStats.isOutOfDate())
Justin Bognere2ef2a02014-04-15 21:22:35 +0000297 getDiags().Report(diag::warn_profile_data_out_of_date)
298 << PGOStats.Visited << PGOStats.Missing << PGOStats.Mismatched;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000299 EmitCtorList(GlobalCtors, "llvm.global_ctors");
300 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000301 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000302 EmitStaticExternCAliases();
Rafael Espindola060062a2014-03-06 22:15:10 +0000303 emitLLVMUsed();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000304
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000305 if (CodeGenOpts.Autolink &&
306 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000307 EmitModuleLinkOptions();
308 }
Manman Ren9691f7f2013-06-19 01:46:49 +0000309 if (CodeGenOpts.DwarfVersion)
310 // We actually want the latest version when there are conflicts.
311 // We can change from Warning to Latest if such mode is supported.
312 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
313 CodeGenOpts.DwarfVersion);
Manman Ren4b7f23d2013-11-22 19:42:45 +0000314 if (DebugInfo)
315 // We support a single version in the linked module: error out when
Manman Renba2fa8b2013-12-02 19:37:35 +0000316 // modules do not have the same version. We are going to implement dropping
317 // debug info when the version number is not up-to-date. Once that is
318 // done, the bitcode linker is not going to see modules with different
319 // version numbers.
Manman Ren4b7f23d2013-11-22 19:42:45 +0000320 getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000321 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000322
John McCall0bdb1fd2010-09-16 06:16:50 +0000323 SimplifyPersonality();
324
John McCall09ae0322010-07-06 23:57:41 +0000325 if (getCodeGenOpts().EmitDeclMetadata)
326 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000327
328 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000329 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000330
331 if (DebugInfo)
332 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000333
334 EmitVersionIdentMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000335}
336
Devang Patel945b8ae2011-03-23 16:29:39 +0000337void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
338 // Make sure that this type is translated.
339 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000340}
341
Dan Gohman947c9af2010-10-14 23:06:10 +0000342llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
343 if (!TBAA)
344 return 0;
345 return TBAA->getTBAAInfo(QTy);
346}
347
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000348llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
349 if (!TBAA)
350 return 0;
351 return TBAA->getTBAAInfoForVTablePtr();
352}
353
Dan Gohman22695fc2012-09-28 21:58:29 +0000354llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
355 if (!TBAA)
356 return 0;
357 return TBAA->getTBAAStructInfo(QTy);
358}
359
Manman Renc451e572013-04-04 21:53:22 +0000360llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
361 if (!TBAA)
362 return 0;
363 return TBAA->getTBAAStructTypeInfo(QTy);
364}
365
366llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
367 llvm::MDNode *AccessN,
368 uint64_t O) {
369 if (!TBAA)
370 return 0;
371 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
372}
373
Manman Ren4f755de2013-10-08 00:08:49 +0000374/// Decorate the instruction with a TBAA tag. For both scalar TBAA
375/// and struct-path aware TBAA, the tag has the same format:
376/// base type, access type and offset.
Manman Rene1ad74e2013-04-11 23:02:56 +0000377/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Dan Gohman947c9af2010-10-14 23:06:10 +0000378void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
Manman Rene1ad74e2013-04-11 23:02:56 +0000379 llvm::MDNode *TBAAInfo,
380 bool ConvertTypeToTag) {
Manman Ren4f755de2013-10-08 00:08:49 +0000381 if (ConvertTypeToTag && TBAA)
Manman Rene1ad74e2013-04-11 23:02:56 +0000382 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
383 TBAA->getTBAAScalarTagInfo(TBAAInfo));
384 else
385 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman947c9af2010-10-14 23:06:10 +0000386}
387
Alp Toker29cb66b2014-01-26 06:17:37 +0000388void CodeGenModule::Error(SourceLocation loc, StringRef message) {
389 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
390 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000391}
392
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000393/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000394/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000395void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000396 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000397 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000398 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000399 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
400 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000401}
Chris Lattner41af8182007-12-02 06:27:33 +0000402
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000403/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000404/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000405void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000406 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000407 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000408 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000409 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000410}
411
John McCall23c29fe2011-06-24 21:55:10 +0000412llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
413 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
414}
415
Mike Stump11289f42009-09-09 15:08:12 +0000416void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000417 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000418 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000419 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000420 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000421 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000422 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000423
John McCallc273f242010-10-30 11:50:40 +0000424 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000425 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000426 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
427 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000428}
429
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000430static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
431 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
432 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
433 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
434 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
435 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
436}
437
438static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
439 CodeGenOptions::TLSModel M) {
440 switch (M) {
441 case CodeGenOptions::GeneralDynamicTLSModel:
442 return llvm::GlobalVariable::GeneralDynamicTLSModel;
443 case CodeGenOptions::LocalDynamicTLSModel:
444 return llvm::GlobalVariable::LocalDynamicTLSModel;
445 case CodeGenOptions::InitialExecTLSModel:
446 return llvm::GlobalVariable::InitialExecTLSModel;
447 case CodeGenOptions::LocalExecTLSModel:
448 return llvm::GlobalVariable::LocalExecTLSModel;
449 }
450 llvm_unreachable("Invalid TLS model!");
451}
452
453void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
454 const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000455 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000456
457 llvm::GlobalVariable::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000458 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000459
460 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000461 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000462 TLM = GetLLVMTLSModel(Attr->getModel());
463 }
464
465 GV->setThreadLocalMode(TLM);
466}
467
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000468StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000469 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
470
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000471 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000472 if (!Str.empty())
473 return Str;
474
John McCall5d865c322010-08-31 07:33:07 +0000475 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000476 IdentifierInfo *II = ND->getIdentifier();
477 assert(II && "Attempt to mangle unnamed decl.");
478
479 Str = II->getName();
480 return Str;
481 }
482
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000483 SmallString<256> Buffer;
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000484 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000485 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000486 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000487 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000488 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000489 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000490 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000491
492 // Allocate space for the mangled name.
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000493 Out.flush();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000494 size_t Length = Buffer.size();
495 char *Name = MangledNamesAllocator.Allocate<char>(Length);
496 std::copy(Buffer.begin(), Buffer.end(), Name);
497
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 Str = StringRef(Name, Length);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000499
500 return Str;
501}
502
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000503void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
504 const BlockDecl *BD) {
505 MangleContext &MangleCtx = getCXXABI().getMangleContext();
506 const Decl *D = GD.getDecl();
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000507 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000508 if (D == 0)
Fariborz Jahanian63628032012-06-26 16:06:38 +0000509 MangleCtx.mangleGlobalBlock(BD,
510 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000511 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000512 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000513 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000514 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000515 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000516 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson635186a2010-06-09 02:36:32 +0000517}
518
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000519llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000520 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000521}
522
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000523/// AddGlobalCtor - Add a function to the list that will be called before
524/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000525void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000526 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000527 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000528}
529
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000530/// AddGlobalDtor - Add a function to the list that will be called
531/// when the module is unloaded.
532void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000533 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000534 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
535}
536
537void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
538 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000539 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000540 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000541
542 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000543 llvm::StructType *CtorStructTy =
Chris Lattnerece04092012-02-07 00:39:47 +0000544 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000545
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000546 // Construct the constructor and destructor arrays.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000547 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000548 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner3def9ae2012-02-06 22:16:34 +0000549 llvm::Constant *S[] = {
550 llvm::ConstantInt::get(Int32Ty, I->second, false),
551 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
552 };
Owen Anderson0e0189d2009-07-27 22:29:56 +0000553 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000554 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000555
556 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000557 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000558 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000559 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000560 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000561 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000562 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000563}
564
John McCalld4324142010-02-19 01:32:20 +0000565llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000566CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Eli Friedmanc48d31c2013-07-01 20:53:07 +0000567 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +0000568
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000569 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000570
Chris Lattner749b8ed2010-06-30 16:58:07 +0000571 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000572 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000573
574 if (D->hasAttr<DLLExportAttr>())
Nico Rieckbb0554f2014-01-14 15:23:53 +0000575 return llvm::Function::ExternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000576
577 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000578 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000579
580 // In C99 mode, 'inline' functions are guaranteed to have a strong
581 // definition somewhere else, so we can use available_externally linkage.
582 if (Linkage == GVA_C99Inline)
Fariborz Jahanian7cadb2f2011-02-04 00:08:13 +0000583 return llvm::Function::AvailableExternallyLinkage;
John McCall28a5b322011-09-19 18:05:26 +0000584
585 // Note that Apple's kernel linker doesn't support symbol
586 // coalescing, so we need to avoid linkonce and weak linkages there.
587 // Normally, this means we just map to internal, but for explicit
588 // instantiations we'll map to external.
589
Chris Lattner749b8ed2010-06-30 16:58:07 +0000590 // In C++, the compiler has to emit a definition in every translation unit
591 // that references the function. We should use linkonce_odr because
592 // a) if all references in this translation unit are optimized away, we
593 // don't need to codegen it. b) if the function persists, it needs to be
594 // merged with other definitions. c) C++ has the ODR, so we know the
595 // definition is dependable.
596 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000597 return !Context.getLangOpts().AppleKext
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000598 ? llvm::Function::LinkOnceODRLinkage
599 : llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000600
601 // An explicit instantiation of a template has weak linkage, since
602 // explicit instantiations can occur in multiple translation units
603 // and must all be equivalent. However, we are not allowed to
604 // throw away these explicit instantiations.
David Majnemer54e3ba52014-04-02 23:17:29 +0000605 if (Linkage == GVA_StrongODR)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000606 return !Context.getLangOpts().AppleKext
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000607 ? llvm::Function::WeakODRLinkage
John McCall28a5b322011-09-19 18:05:26 +0000608 : llvm::Function::ExternalLinkage;
Reid Klecknera12cd282013-12-11 19:21:27 +0000609
610 // Destructor variants in the Microsoft C++ ABI are always linkonce_odr thunks
611 // emitted on an as-needed basis.
612 if (isa<CXXDestructorDecl>(D) &&
613 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
614 GD.getDtorType()))
615 return llvm::Function::LinkOnceODRLinkage;
616
Chris Lattner749b8ed2010-06-30 16:58:07 +0000617 // Otherwise, we have strong external linkage.
618 assert(Linkage == GVA_StrongExternal);
619 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000620}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000621
John McCalld4324142010-02-19 01:32:20 +0000622
623/// SetFunctionDefinitionAttributes - Set attributes for a global.
624///
625/// FIXME: This is currently only done for aliases and functions, but not for
626/// variables (these details are set in EmitGlobalVarDefinition for variables).
627void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
628 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000629 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000630}
631
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000632void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000633 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000634 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000635 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000636 AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000637 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling3087d022012-12-07 23:17:26 +0000638 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000639 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000640}
641
John McCall9b0a7ce2011-10-02 01:16:38 +0000642/// Determines whether the language options require us to model
643/// unwind exceptions. We treat -fexceptions as mandating this
644/// except under the fragile ObjC ABI with only ObjC exceptions
645/// enabled. This means, for example, that C with -fexceptions
646/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000647static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000648 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000649 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000650
651 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000652 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000653
654 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000655 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +0000656 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +0000657 }
658
659 return true;
660}
661
Daniel Dunbar38932572009-04-14 08:05:55 +0000662void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
663 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000664 llvm::AttrBuilder B;
665
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000666 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000667 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000668
David Blaikiebbafb8a2012-03-11 07:00:24 +0000669 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000670 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000671
Eli Friedmanc55efe42011-08-22 23:55:33 +0000672 if (D->hasAttr<NakedAttr>()) {
673 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000674 B.addAttribute(llvm::Attribute::Naked);
675 B.addAttribute(llvm::Attribute::NoInline);
Paul Robinsonf0674352014-03-31 22:29:15 +0000676 } else if (D->hasAttr<OptimizeNoneAttr>()) {
677 // OptimizeNone implies noinline; we should not be inlining such functions.
678 B.addAttribute(llvm::Attribute::OptimizeNone);
679 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +0000680 } else if (D->hasAttr<NoDuplicateAttr>()) {
681 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000682 } else if (D->hasAttr<NoInlineAttr>()) {
683 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +0000684 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000685 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
686 llvm::Attribute::NoInline)) {
687 // (noinline wins over always_inline, and we can't specify both in IR)
688 B.addAttribute(llvm::Attribute::AlwaysInline);
Eli Friedmanc55efe42011-08-22 23:55:33 +0000689 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000690
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000691 if (D->hasAttr<ColdAttr>()) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000692 B.addAttribute(llvm::Attribute::OptimizeForSize);
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000693 B.addAttribute(llvm::Attribute::Cold);
694 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000695
Quentin Colombet4e172062012-11-01 23:55:47 +0000696 if (D->hasAttr<MinSizeAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000697 B.addAttribute(llvm::Attribute::MinSize);
Richard Smithb555a762012-09-28 22:46:07 +0000698
Paul Robinsonf0674352014-03-31 22:29:15 +0000699 if (D->hasAttr<OptimizeNoneAttr>()) {
700 // OptimizeNone wins over OptimizeForSize and MinSize.
701 B.removeAttribute(llvm::Attribute::OptimizeForSize);
702 B.removeAttribute(llvm::Attribute::MinSize);
703 }
704
David Blaikiebbafb8a2012-03-11 07:00:24 +0000705 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000706 B.addAttribute(llvm::Attribute::StackProtect);
Josh Mageee0fc1a82014-02-11 01:35:14 +0000707 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
708 B.addAttribute(llvm::Attribute::StackProtectStrong);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000709 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000710 B.addAttribute(llvm::Attribute::StackProtectReq);
Will Dietzf54319c2013-01-18 11:30:38 +0000711
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000712 // Add sanitizer attributes if function is not blacklisted.
Alexey Samsonovd6e043b2013-08-12 11:48:05 +0000713 if (!SanitizerBlacklist->isIn(*F)) {
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000714 // When AddressSanitizer is enabled, set SanitizeAddress attribute
715 // unless __attribute__((no_sanitize_address)) is used.
716 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000717 B.addAttribute(llvm::Attribute::SanitizeAddress);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000718 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
719 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000720 B.addAttribute(llvm::Attribute::SanitizeThread);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000721 }
722 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
723 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000724 B.addAttribute(llvm::Attribute::SanitizeMemory);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000725 }
Alexander Potapenkoef41fd32012-02-02 11:49:28 +0000726
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000727 F->addAttributes(llvm::AttributeSet::FunctionIndex,
728 llvm::AttributeSet::get(
729 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
730
731 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
732 F->setUnnamedAddr(true);
733 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
734 if (MD->isVirtual())
735 F->setUnnamedAddr(true);
736
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000737 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
738 if (alignment)
739 F->setAlignment(alignment);
740
Mike Stump3472ae52009-10-05 22:49:20 +0000741 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000742 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
743 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000744}
745
Mike Stump11289f42009-09-09 15:08:12 +0000746void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000747 llvm::GlobalValue *GV) {
Anders Carlsson072ef742011-01-29 19:41:00 +0000748 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
749 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000750 else
751 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000752
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000753 if (D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000754 addUsedGlobal(GV);
Daniel Dunbar38932572009-04-14 08:05:55 +0000755
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000756 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000757 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000758
Rafael Espindola513499d2013-03-19 15:03:47 +0000759 // Alias cannot have attributes. Filter them here.
760 if (!isa<llvm::GlobalAlias>(GV))
761 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000762}
763
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000764void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
765 llvm::Function *F,
766 const CGFunctionInfo &FI) {
767 SetLLVMFunctionAttributes(D, FI, F);
768 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000769
770 F->setLinkage(llvm::Function::InternalLinkage);
771
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000772 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000773}
774
Anders Carlsson6710c532010-02-06 02:44:09 +0000775void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000776 llvm::Function *F,
777 bool IsIncompleteFunction) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000778 if (unsigned IID = F->getIntrinsicID()) {
779 // If this is an intrinsic function, set the function's attributes
780 // to the intrinsic's attributes.
Bill Wendling311c8322012-10-15 04:47:45 +0000781 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
782 (llvm::Intrinsic::ID)IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000783 return;
784 }
785
Anders Carlsson6710c532010-02-06 02:44:09 +0000786 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
787
Eli Friedman895771a2009-05-26 01:22:57 +0000788 if (!IsIncompleteFunction)
John McCalla729c622012-02-17 03:33:10 +0000789 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000790
Bob Wilsonfc6297f2014-04-01 01:38:16 +0000791 // Add the Returned attribute for "this", except for iOS 5 and earlier
792 // where substantial code, including the libstdc++ dylib, was compiled with
793 // GCC and does not actually return "this".
794 if (getCXXABI().HasThisReturn(GD) &&
795 !(getTarget().getTriple().isiOS() &&
796 getTarget().getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000797 assert(!F->arg_empty() &&
798 F->arg_begin()->getType()
799 ->canLosslesslyBitCastTo(F->getReturnType()) &&
800 "unexpected this return");
801 F->addAttribute(1, llvm::Attribute::Returned);
802 }
803
Daniel Dunbar38932572009-04-14 08:05:55 +0000804 // Only a few attributes are set on declarations; these may later be
805 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000806
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000807 if (FD->hasAttr<DLLImportAttr>()) {
Nico Rieckbb0554f2014-01-14 15:23:53 +0000808 F->setLinkage(llvm::Function::ExternalLinkage);
809 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Mike Stump11289f42009-09-09 15:08:12 +0000810 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000811 FD->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000812 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000813 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000814 F->setLinkage(llvm::Function::ExternalWeakLinkage);
815 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000816 F->setLinkage(llvm::Function::ExternalLinkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +0000817 if (FD->hasAttr<DLLExportAttr>())
818 F->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
John McCallc273f242010-10-30 11:50:40 +0000819
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000820 LinkageInfo LV = FD->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000821 if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
822 F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
John McCallc273f242010-10-30 11:50:40 +0000823 }
Daniel Dunbar38932572009-04-14 08:05:55 +0000824 }
825
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000826 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000827 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +0000828
829 // A replaceable global allocation function does not act like a builtin by
830 // default, only if it is invoked by a new-expression or delete-expression.
831 if (FD->isReplaceableGlobalAllocationFunction())
832 F->addAttribute(llvm::AttributeSet::FunctionIndex,
833 llvm::Attribute::NoBuiltin);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000834}
835
Rafael Espindola060062a2014-03-06 22:15:10 +0000836void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000837 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000838 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000839 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000840}
841
Rafael Espindola060062a2014-03-06 22:15:10 +0000842void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
843 assert(!GV->isDeclaration() &&
844 "Only globals with definition can force usage.");
845 LLVMCompilerUsed.push_back(GV);
846}
847
848static void emitUsed(CodeGenModule &CGM, StringRef Name,
849 std::vector<llvm::WeakVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000850 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +0000851 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000852 return;
853
Rafael Espindola060062a2014-03-06 22:15:10 +0000854 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000855 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +0000856 UsedArray.resize(List.size());
857 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000858 UsedArray[i] =
Rafael Espindola060062a2014-03-06 22:15:10 +0000859 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
860 CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000861 }
Mike Stump11289f42009-09-09 15:08:12 +0000862
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000863 if (UsedArray.empty())
864 return;
Rafael Espindola060062a2014-03-06 22:15:10 +0000865 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000866
867 llvm::GlobalVariable *GV =
Rafael Espindola060062a2014-03-06 22:15:10 +0000868 new llvm::GlobalVariable(CGM.getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000869 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000870 llvm::ConstantArray::get(ATy, UsedArray),
Rafael Espindola060062a2014-03-06 22:15:10 +0000871 Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000872
873 GV->setSection("llvm.metadata");
874}
875
Rafael Espindola060062a2014-03-06 22:15:10 +0000876void CodeGenModule::emitLLVMUsed() {
877 emitUsed(*this, "llvm.used", LLVMUsed);
878 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
879}
880
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000881void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
882 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
883 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
884}
885
Aaron Ballman5d041be2013-06-04 02:07:14 +0000886void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
887 llvm::SmallString<32> Opt;
888 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
889 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
890 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
891}
892
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000893void CodeGenModule::AddDependentLib(StringRef Lib) {
894 llvm::SmallString<24> Opt;
895 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
896 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
897 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
898}
899
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000900/// \brief Add link options implied by the given module, including modules
901/// it depends on, using a postorder walk.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000902static void addLinkOptionsPostorder(CodeGenModule &CGM,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000903 Module *Mod,
Daniel Dunbar69e47462013-01-17 01:35:06 +0000904 SmallVectorImpl<llvm::Value *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000905 llvm::SmallPtrSet<Module *, 16> &Visited) {
906 // Import this module's parent.
907 if (Mod->Parent && Visited.insert(Mod->Parent)) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000908 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000909 }
910
911 // Import this module's dependencies.
912 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
913 if (Visited.insert(Mod->Imports[I-1]))
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000914 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000915 }
916
917 // Add linker options to link against the libraries/frameworks
918 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000919 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000920 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000921 // Link against a framework. Frameworks are currently Darwin only, so we
922 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000923 if (Mod->LinkLibraries[I-1].IsFramework) {
924 llvm::Value *Args[2] = {
925 llvm::MDString::get(Context, "-framework"),
926 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
927 };
928
929 Metadata.push_back(llvm::MDNode::get(Context, Args));
930 continue;
931 }
932
933 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000934 llvm::SmallString<24> Opt;
935 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
936 Mod->LinkLibraries[I-1].Library, Opt);
937 llvm::Value *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000938 Metadata.push_back(llvm::MDNode::get(Context, OptString));
939 }
940}
941
942void CodeGenModule::EmitModuleLinkOptions() {
943 // Collect the set of all of the modules we want to visit to emit link
944 // options, which is essentially the imported modules and all of their
945 // non-explicit child modules.
946 llvm::SetVector<clang::Module *> LinkModules;
947 llvm::SmallPtrSet<clang::Module *, 16> Visited;
948 SmallVector<clang::Module *, 16> Stack;
949
950 // Seed the stack with imported modules.
951 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
952 MEnd = ImportedModules.end();
953 M != MEnd; ++M) {
954 if (Visited.insert(*M))
955 Stack.push_back(*M);
956 }
957
958 // Find all of the modules to import, making a little effort to prune
959 // non-leaf modules.
960 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000961 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000962
963 bool AnyChildren = false;
964
965 // Visit the submodules of this module.
966 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
967 SubEnd = Mod->submodule_end();
968 Sub != SubEnd; ++Sub) {
969 // Skip explicit children; they need to be explicitly imported to be
970 // linked against.
971 if ((*Sub)->IsExplicit)
972 continue;
973
974 if (Visited.insert(*Sub)) {
975 Stack.push_back(*Sub);
976 AnyChildren = true;
977 }
978 }
979
980 // We didn't find any children, so add this module to the list of
981 // modules to link against.
982 if (!AnyChildren) {
983 LinkModules.insert(Mod);
984 }
985 }
986
987 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000988 // order. We don't do anything to try to order import link flags with respect
989 // to linker options inserted by things like #pragma comment().
Daniel Dunbar69e47462013-01-17 01:35:06 +0000990 SmallVector<llvm::Value *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000991 Visited.clear();
992 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
993 MEnd = LinkModules.end();
994 M != MEnd; ++M) {
995 if (Visited.insert(*M))
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000996 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000997 }
Daniel Dunbar69e47462013-01-17 01:35:06 +0000998 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000999 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001000
Daniel Dunbar69e47462013-01-17 01:35:06 +00001001 // Add the linker options metadata flag.
1002 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001003 llvm::MDNode::get(getLLVMContext(),
1004 LinkerOptionsMetadata));
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001005}
1006
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001007void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +00001008 // Emit code for any potentially referenced deferred decls. Since a
1009 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001010 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001011
John McCall6bd2a892013-01-25 22:31:03 +00001012 while (true) {
Anders Carlsson11e51402010-04-17 20:15:18 +00001013 if (!DeferredVTables.empty()) {
John McCall6bd2a892013-01-25 22:31:03 +00001014 EmitDeferredVTables();
1015
1016 // Emitting a v-table doesn't directly cause more v-tables to
1017 // become deferred, although it can cause functions to be
1018 // emitted that then need those v-tables.
1019 assert(DeferredVTables.empty());
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001020 }
1021
John McCall6bd2a892013-01-25 22:31:03 +00001022 // Stop if we're out of both deferred v-tables and deferred declarations.
1023 if (DeferredDeclsToEmit.empty()) break;
1024
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001025 DeferredGlobal &G = DeferredDeclsToEmit.back();
1026 GlobalDecl D = G.GD;
1027 llvm::GlobalValue *GV = G.GV;
Chris Lattner45470942009-03-21 09:44:56 +00001028 DeferredDeclsToEmit.pop_back();
1029
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001030 assert(GV == GetGlobalValue(getMangledName(D)));
John McCallc2af9392010-05-27 01:45:30 +00001031 // Check to see if we've already emitted this. This is necessary
1032 // for a couple of reasons: first, decls can end up in the
1033 // deferred-decls queue multiple times, and second, decls can end
1034 // up with definitions in unusual ways (e.g. by an extern inline
1035 // function acquiring a strong function redefinition). Just
1036 // ignore these cases.
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001037 if(!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001038 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001039
Chris Lattner45470942009-03-21 09:44:56 +00001040 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001041 EmitGlobalDefinition(D, GV);
Chris Lattner45470942009-03-21 09:44:56 +00001042 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001043}
Chris Lattner09153c02007-06-22 18:48:09 +00001044
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001045void CodeGenModule::EmitGlobalAnnotations() {
1046 if (Annotations.empty())
1047 return;
1048
1049 // Create a new global variable for the ConstantStruct in the Module.
1050 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1051 Annotations[0]->getType(), Annotations.size()), Annotations);
1052 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
1053 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
1054 "llvm.global.annotations");
1055 gv->setSection(AnnotationSection);
1056}
1057
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001058llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001059 llvm::Constant *&AStr = AnnotationStrings[Str];
1060 if (AStr)
1061 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001062
1063 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001064 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001065 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
1066 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
1067 gv->setSection(AnnotationSection);
1068 gv->setUnnamedAddr(true);
Benjamin Kramereed80612013-11-10 16:55:11 +00001069 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001070 return gv;
1071}
1072
1073llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1074 SourceManager &SM = getContext().getSourceManager();
1075 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1076 if (PLoc.isValid())
1077 return EmitAnnotationString(PLoc.getFilename());
1078 return EmitAnnotationString(SM.getBufferName(Loc));
1079}
1080
1081llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1082 SourceManager &SM = getContext().getSourceManager();
1083 PresumedLoc PLoc = SM.getPresumedLoc(L);
1084 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1085 SM.getExpansionLineNumber(L);
1086 return llvm::ConstantInt::get(Int32Ty, LineNo);
1087}
1088
Mike Stump11289f42009-09-09 15:08:12 +00001089llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001090 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001091 SourceLocation L) {
1092 // Get the globals for file name, annotation, and the line number.
1093 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1094 *UnitGV = EmitAnnotationUnit(L),
1095 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001096
Daniel Dunbar346892a2009-04-14 22:41:13 +00001097 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001098 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001099 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1100 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1101 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1102 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001103 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001104 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001105}
1106
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001107void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1108 llvm::GlobalValue *GV) {
1109 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1110 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001111 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1112 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001113}
1114
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +00001115bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001116 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001117 if (LangOpts.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001118 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001119
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00001120 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001121}
1122
Nico Webercf4ff5862012-10-11 10:13:44 +00001123llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1124 const CXXUuidofExpr* E) {
1125 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1126 // well-formed.
David Majnemer8eaab6f2013-08-13 06:32:20 +00001127 StringRef Uuid = E->getUuidAsStringRef(Context);
David Majnemercf963ce2013-08-09 08:35:59 +00001128 std::string Name = "_GUID_" + Uuid.lower();
1129 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001130
1131 // Look for an existing global.
1132 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1133 return GV;
1134
1135 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1136 assert(Init && "failed to initialize as constant");
1137
David Majnemerbbecd092013-08-15 19:59:14 +00001138 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1139 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001140 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
Nico Webercf4ff5862012-10-11 10:13:44 +00001141 return GV;
1142}
1143
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001144llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1145 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1146 assert(AA && "No alias?");
1147
Chris Lattner2192fe52011-07-18 04:24:23 +00001148 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001149
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001150 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001151 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001152 if (Entry) {
1153 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1154 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1155 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001156
1157 llvm::Constant *Aliasee;
1158 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001159 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1160 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001161 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001162 else
John McCall7ec50432010-03-19 23:29:14 +00001163 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001164 llvm::PointerType::getUnqual(DeclTy), 0);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001165
1166 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1167 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1168 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001169
1170 return Aliasee;
1171}
1172
Chris Lattnere0be0df2009-05-12 21:21:08 +00001173void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +00001174 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001175
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001176 // Weak references don't produce any output by themselves.
1177 if (Global->hasAttr<WeakRefAttr>())
1178 return;
1179
Chris Lattner54041692009-03-22 21:47:11 +00001180 // If this is an alias definition (which otherwise looks like a declaration)
1181 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001182 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001183 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001184
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001185 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001186 if (LangOpts.CUDA) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001187 if (CodeGenOpts.CUDAIsDevice) {
1188 if (!Global->hasAttr<CUDADeviceAttr>() &&
1189 !Global->hasAttr<CUDAGlobalAttr>() &&
1190 !Global->hasAttr<CUDAConstantAttr>() &&
1191 !Global->hasAttr<CUDASharedAttr>())
1192 return;
1193 } else {
1194 if (!Global->hasAttr<CUDAHostAttr>() && (
1195 Global->hasAttr<CUDADeviceAttr>() ||
1196 Global->hasAttr<CUDAConstantAttr>() ||
1197 Global->hasAttr<CUDASharedAttr>()))
1198 return;
1199 }
1200 }
1201
Chris Lattner45470942009-03-21 09:44:56 +00001202 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +00001203 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001204 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001205 if (!FD->doesThisDeclarationHaveABody()) {
1206 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1207 return;
1208
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001209 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00001210
1211 // Compute the function info and LLVM type.
1212 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1213 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1214
1215 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1216 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001217 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001218 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001219 } else {
1220 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001221 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1222
Douglas Gregor61f6db52010-02-06 05:15:45 +00001223 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +00001224 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +00001225 }
1226
Chris Lattner45470942009-03-21 09:44:56 +00001227 // Defer code generation when possible if this is a static definition, inline
1228 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001229 if (!MayDeferGeneration(Global)) {
1230 // Emit the definition if it can't be deferred.
1231 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001232 return;
1233 }
John McCall70013b62010-07-15 23:40:35 +00001234
1235 // If we're deferring emission of a C++ variable with an
1236 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001237 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00001238 cast<VarDecl>(Global)->hasInit()) {
1239 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1240 CXXGlobalInits.push_back(0);
1241 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001242
1243 // If the value has already been used, add it directly to the
1244 // DeferredDeclsToEmit list.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001245 StringRef MangledName = getMangledName(GD);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001246 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
1247 addDeferredDeclToEmit(GV, GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001248 else {
1249 // Otherwise, remember that we saw a deferred decl with this name. The
1250 // first use of the mangled name will cause it to move into
1251 // DeferredDeclsToEmit.
1252 DeferredDecls[MangledName] = GD;
1253 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001254}
1255
Rafael Espindolac5941352011-10-26 20:41:06 +00001256namespace {
1257 struct FunctionIsDirectlyRecursive :
1258 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1259 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001260 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00001261 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001262 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1263 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001264 }
1265 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1266
1267 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001268 const FunctionDecl *FD = E->getDirectCallee();
1269 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00001270 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001271 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1272 if (Attr && Name == Attr->getLabel()) {
1273 Result = true;
1274 return false;
1275 }
1276 unsigned BuiltinID = FD->getBuiltinID();
1277 if (!BuiltinID)
Rafael Espindolac5941352011-10-26 20:41:06 +00001278 return true;
Nick Lewycky9ed5b152012-01-18 03:41:19 +00001279 StringRef BuiltinName = BI.GetName(BuiltinID);
1280 if (BuiltinName.startswith("__builtin_") &&
1281 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001282 Result = true;
1283 return false;
1284 }
1285 return true;
1286 }
1287 };
1288}
1289
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001290// isTriviallyRecursive - Check if this function calls another
1291// decl that, because of the asm attribute or the other decl being a builtin,
1292// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00001293bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001294CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1295 StringRef Name;
1296 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00001297 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001298 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1299 if (!Attr)
1300 return false;
1301 Name = Attr->getLabel();
1302 } else {
1303 Name = FD->getName();
1304 }
Rafael Espindolac5941352011-10-26 20:41:06 +00001305
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001306 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1307 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00001308 return Walker.Result;
1309}
1310
1311bool
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001312CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1313 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00001314 return true;
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001315 const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00001316 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00001317 return false;
1318 // PR9614. Avoid cases where the source code is lying to us. An available
1319 // externally function should have an equivalent function somewhere else,
1320 // but a function that calls itself is clearly not equivalent to the real
1321 // implementation.
1322 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001323 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00001324}
1325
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001326/// If the type for the method's class was generated by
1327/// CGDebugInfo::createContextChain(), the cache contains only a
1328/// limited DIType without any declarations. Since EmitFunctionStart()
1329/// needs to find the canonical declaration for each method, we need
1330/// to construct the complete type prior to emitting the method.
1331void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1332 if (!D->isInstance())
1333 return;
1334
1335 if (CGDebugInfo *DI = getModuleDebugInfo())
1336 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1337 const PointerType *ThisPtr =
1338 cast<PointerType>(D->getThisType(getContext()));
1339 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1340 }
1341}
1342
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001343void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Anders Carlsson38988d72009-09-10 23:38:47 +00001344 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001345
Dan Gohman145f3f12010-04-19 16:39:44 +00001346 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00001347 Context.getSourceManager(),
1348 "Generating code for declaration");
1349
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001350 if (isa<FunctionDecl>(D)) {
Douglas Gregora700f682010-07-13 06:02:28 +00001351 // At -O0, don't generate IR for functions with available_externally
1352 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001353 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00001354 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00001355
Douglas Gregora700f682010-07-13 06:02:28 +00001356 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001357 CompleteDIClassType(Method);
Eli Friedman49a94b12011-05-06 17:27:27 +00001358 // Make sure to emit the definition(s) before we emit the thunks.
1359 // This is necessary for the generation of certain thunks.
1360 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1361 EmitCXXConstructor(CD, GD.getCtorType());
1362 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1363 EmitCXXDestructor(DD, GD.getDtorType());
1364 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001365 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00001366
Douglas Gregora700f682010-07-13 06:02:28 +00001367 if (Method->isVirtual())
1368 getVTables().EmitThunks(GD);
1369
Eli Friedman49a94b12011-05-06 17:27:27 +00001370 return;
Douglas Gregora700f682010-07-13 06:02:28 +00001371 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001372
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001373 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00001374 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001375
1376 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1377 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001378
David Blaikie83d382b2011-09-23 05:06:16 +00001379 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00001380}
1381
Chris Lattnerd4808922009-03-22 21:03:39 +00001382/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1383/// module, create and return an llvm Function with the specified type. If there
1384/// is something in the module with the specified name, return it potentially
1385/// bitcasted to the right type.
1386///
1387/// If D is non-null, it specifies a decl that correspond to this. This is used
1388/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001389llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001390CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001391 llvm::Type *Ty,
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001392 GlobalDecl GD, bool ForVTable,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001393 bool DontDefer,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001394 llvm::AttributeSet ExtraAttrs) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001395 const Decl *D = GD.getDecl();
1396
Chris Lattnera85d68e2009-03-21 09:25:43 +00001397 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001398 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001399 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001400 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001401 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001402 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001403 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001404 }
1405
Chris Lattnera85d68e2009-03-21 09:25:43 +00001406 if (Entry->getType()->getElementType() == Ty)
1407 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001408
Chris Lattnera85d68e2009-03-21 09:25:43 +00001409 // Make sure the result is of the correct type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001410 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00001411 }
Mike Stump11289f42009-09-09 15:08:12 +00001412
Eli Friedmancc522d92009-11-09 05:07:37 +00001413 // This function doesn't have a complete type (for example, the return
1414 // type is an incomplete struct). Use a fake type instead, and make
1415 // sure not to try to set attributes.
1416 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00001417
Chris Lattner2192fe52011-07-18 04:24:23 +00001418 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00001419 if (isa<llvm::FunctionType>(Ty)) {
1420 FTy = cast<llvm::FunctionType>(Ty);
1421 } else {
John McCall9dc0db22011-05-15 01:53:33 +00001422 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00001423 IsIncompleteFunction = true;
1424 }
Chris Lattner5c740f12010-06-30 19:14:05 +00001425
John McCalld06fb862010-04-28 00:00:30 +00001426 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +00001427 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001428 MangledName, &getModule());
1429 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001430 if (D)
1431 SetFunctionAttributes(GD, F, IsIncompleteFunction);
Bill Wendling8594fcb2013-01-31 00:30:05 +00001432 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1433 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling9a677922013-01-23 00:21:06 +00001434 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1435 llvm::AttributeSet::get(VMContext,
1436 llvm::AttributeSet::FunctionIndex,
1437 B));
1438 }
Eli Friedmancc522d92009-11-09 05:07:37 +00001439
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001440 if (!DontDefer) {
1441 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1442 // each other bottoming out with the base dtor. Therefore we emit non-base
1443 // dtors on usage, even if there is no dtor definition in the TU.
1444 if (D && isa<CXXDestructorDecl>(D) &&
1445 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1446 GD.getDtorType()))
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001447 addDeferredDeclToEmit(F, GD);
John McCall357d0f32010-12-15 04:00:32 +00001448
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001449 // This is the first use or definition of a mangled name. If there is a
1450 // deferred decl with this name, remember that we need to emit it at the end
1451 // of the file.
1452 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1453 if (DDI != DeferredDecls.end()) {
1454 // Move the potentially referenced deferred decl to the
1455 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1456 // don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001457 addDeferredDeclToEmit(F, DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001458 DeferredDecls.erase(DDI);
Richard Smithb47c36f2013-11-05 09:12:18 +00001459
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001460 // Otherwise, if this is a sized deallocation function, emit a weak
1461 // definition
1462 // for it at the end of the translation unit.
1463 } else if (D && cast<FunctionDecl>(D)
1464 ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001465 addDeferredDeclToEmit(F, GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001466
1467 // Otherwise, there are cases we have to worry about where we're
1468 // using a declaration for which we must emit a definition but where
1469 // we might not find a top-level definition:
1470 // - member functions defined inline in their classes
1471 // - friend functions defined inline in some class
1472 // - special member functions with implicit definitions
1473 // If we ever change our AST traversal to walk into class methods,
1474 // this will be unnecessary.
1475 //
1476 // We also don't emit a definition for a function if it's going to be an
1477 // entry
1478 // in a vtable, unless it's already marked as used.
1479 } else if (getLangOpts().CPlusPlus && D) {
1480 // Look for a declaration that's lexically in a record.
1481 const FunctionDecl *FD = cast<FunctionDecl>(D);
1482 FD = FD->getMostRecentDecl();
1483 do {
1484 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1485 if (FD->isImplicit() && !ForVTable) {
1486 assert(FD->isUsed() &&
1487 "Sema didn't mark implicit function as used!");
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001488 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001489 break;
1490 } else if (FD->doesThisDeclarationHaveABody()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001491 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001492 break;
1493 }
John McCall357d0f32010-12-15 04:00:32 +00001494 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001495 FD = FD->getPreviousDecl();
1496 } while (FD);
1497 }
Chris Lattner45470942009-03-21 09:44:56 +00001498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
John McCalld06fb862010-04-28 00:00:30 +00001500 // Make sure the result is of the requested type.
1501 if (!IsIncompleteFunction) {
1502 assert(F->getType()->getElementType() == Ty);
1503 return F;
1504 }
1505
Chris Lattnera5f58b02011-07-09 17:41:47 +00001506 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00001507 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001508}
1509
Chris Lattnerd4808922009-03-22 21:03:39 +00001510/// GetAddrOfFunction - Return the address of the given function. If Ty is
1511/// non-null, then this function will use the specified type if it has to
1512/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00001513llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00001514 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001515 bool ForVTable,
1516 bool DontDefer) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001517 // If there was no specific requested type, just convert it now.
1518 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +00001519 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +00001520
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001521 StringRef MangledName = getMangledName(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001522 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
Chris Lattnerd4808922009-03-22 21:03:39 +00001523}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001524
Chris Lattnerd4808922009-03-22 21:03:39 +00001525/// CreateRuntimeFunction - Create a new runtime function with the specified
1526/// type and name.
1527llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001528CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001529 StringRef Name,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001530 llvm::AttributeSet ExtraAttrs) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001531 llvm::Constant *C =
1532 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1533 /*DontDefer=*/false, ExtraAttrs);
John McCall882987f2013-02-28 19:01:20 +00001534 if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1535 if (F->empty())
1536 F->setCallingConv(getRuntimeCC());
1537 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00001538}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001539
Richard Smithe070fd22012-02-17 06:48:11 +00001540/// isTypeConstant - Determine whether an object of this type can be emitted
1541/// as a constant.
1542///
1543/// If ExcludeCtor is true, the duration when the object's constructor runs
1544/// will not be considered. The caller will need to verify that the object is
1545/// not written to during its construction.
1546bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1547 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00001548 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00001549
David Blaikiebbafb8a2012-03-11 07:00:24 +00001550 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00001551 if (const CXXRecordDecl *Record
1552 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1553 return ExcludeCtor && !Record->hasMutableFields() &&
1554 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00001555 }
Richard Smithe070fd22012-02-17 06:48:11 +00001556
Eli Friedmanb095e152009-12-11 21:23:03 +00001557 return true;
1558}
1559
Chris Lattnerd4808922009-03-22 21:03:39 +00001560/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1561/// create and return an llvm GlobalVariable with the specified type. If there
1562/// is something in the module with the specified name, return it potentially
1563/// bitcasted to the right type.
1564///
1565/// If D is non-null, it specifies a decl that correspond to this. This is used
1566/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001567llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001568CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001569 llvm::PointerType *Ty,
Rafael Espindolad661a852011-01-18 21:07:57 +00001570 const VarDecl *D,
1571 bool UnnamedAddr) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00001572 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001573 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00001574 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001575 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001576 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001577 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001578 }
1579
Rafael Espindolad661a852011-01-18 21:07:57 +00001580 if (UnnamedAddr)
1581 Entry->setUnnamedAddr(true);
1582
Chris Lattnerd4808922009-03-22 21:03:39 +00001583 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001584 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001585
Chris Lattner3bfce182009-03-21 08:03:33 +00001586 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00001587 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1588 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1589
Owen Andersonade90fd2009-07-29 18:54:39 +00001590 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001591 }
Mike Stump11289f42009-09-09 15:08:12 +00001592
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001593 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1594 llvm::GlobalVariable *GV =
1595 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1596 llvm::GlobalValue::ExternalLinkage,
1597 0, MangledName, 0,
1598 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1599
Chris Lattner45470942009-03-21 09:44:56 +00001600 // This is the first use or definition of a mangled name. If there is a
1601 // deferred decl with this name, remember that we need to emit it at the end
1602 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001603 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001604 if (DDI != DeferredDecls.end()) {
1605 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1606 // list, and remove it from DeferredDecls (since we don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001607 addDeferredDeclToEmit(GV, DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00001608 DeferredDecls.erase(DDI);
1609 }
Mike Stump11289f42009-09-09 15:08:12 +00001610
Chris Lattner3bfce182009-03-21 08:03:33 +00001611 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001612 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001613 // FIXME: This code is overly simple and should be merged with other global
1614 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00001615 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00001616
John McCall37bb6c92010-10-29 22:22:43 +00001617 // Set linkage and visibility in case we never see a definition.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +00001618 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +00001619 if (LV.getLinkage() != ExternalLinkage) {
John McCall83779672011-02-19 02:53:41 +00001620 // Don't set internal linkage on declarations.
John McCall37bb6c92010-10-29 22:22:43 +00001621 } else {
Nico Rieckbb0554f2014-01-14 15:23:53 +00001622 if (D->hasAttr<DLLImportAttr>()) {
1623 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1624 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1625 } else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall37bb6c92010-10-29 22:22:43 +00001626 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner3bfce182009-03-21 08:03:33 +00001627
John McCallc273f242010-10-30 11:50:40 +00001628 // Set visibility on a declaration only if it's explicit.
Rafael Espindola4a5da442013-02-27 02:56:45 +00001629 if (LV.isVisibilityExplicit())
1630 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
John McCall37bb6c92010-10-29 22:22:43 +00001631 }
Eli Friedman4f856742009-04-19 21:05:03 +00001632
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001633 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00001634 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1635 CXXThreadLocals.push_back(std::make_pair(D, GV));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001636 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001637 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00001638
1639 // If required by the ABI, treat declarations of static data members with
1640 // inline initializers as definitions.
1641 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1642 D->isStaticDataMember() && D->hasInit() &&
1643 !D->isThisDeclarationADefinition())
1644 EmitGlobalVarDefinition(D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001645 }
Mike Stump11289f42009-09-09 15:08:12 +00001646
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001647 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault00e65b22013-11-15 02:19:52 +00001648 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1649
Robert Lytton15abd182014-02-11 10:34:51 +00001650 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1651 D->getLanguageLinkage() == CLanguageLinkage &&
1652 D->getType().isConstant(Context) &&
1653 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1654 GV->setSection(".cp.rodata");
1655
Matt Arsenault00e65b22013-11-15 02:19:52 +00001656 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001657}
1658
Chris Lattnerd4808922009-03-22 21:03:39 +00001659
Anders Carlssonda80af32011-01-29 18:20:20 +00001660llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001661CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00001662 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00001663 llvm::GlobalValue::LinkageTypes Linkage) {
1664 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1665 llvm::GlobalVariable *OldGV = 0;
1666
1667
1668 if (GV) {
1669 // Check if the variable has the right type.
1670 if (GV->getType()->getElementType() == Ty)
1671 return GV;
1672
1673 // Because C++ name mangling, the only way we can end up with an already
1674 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00001675 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001676 OldGV = GV;
1677 }
1678
1679 // Create a new variable.
1680 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1681 Linkage, 0, Name);
1682
1683 if (OldGV) {
1684 // Replace occurrences of the old variable if needed.
1685 GV->takeName(OldGV);
1686
1687 if (!OldGV->use_empty()) {
1688 llvm::Constant *NewPtrForOldDecl =
1689 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1690 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1691 }
1692
1693 OldGV->eraseFromParent();
1694 }
1695
1696 return GV;
1697}
1698
Chris Lattnerd4808922009-03-22 21:03:39 +00001699/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1700/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00001701/// then it will be created with the specified type instead of whatever the
Chris Lattnerd4808922009-03-22 21:03:39 +00001702/// normal requested type would be.
1703llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2192fe52011-07-18 04:24:23 +00001704 llvm::Type *Ty) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001705 assert(D->hasGlobalStorage() && "Not a global variable");
1706 QualType ASTTy = D->getType();
1707 if (Ty == 0)
1708 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Chris Lattner2192fe52011-07-18 04:24:23 +00001710 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001711 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00001712
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001713 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001714 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001715}
1716
1717/// CreateRuntimeVariable - Create a new runtime global variable with the
1718/// specified type and name.
1719llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001720CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001721 StringRef Name) {
John McCall31996342011-04-07 08:22:57 +00001722 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolad661a852011-01-18 21:07:57 +00001723 true);
Chris Lattnerd4808922009-03-22 21:03:39 +00001724}
1725
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001726void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1727 assert(!D->getInit() && "Cannot emit definite definitions here!");
1728
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001729 if (MayDeferGeneration(D)) {
1730 // If we have not seen a reference to this variable yet, place it
1731 // into the deferred declarations table to be emitted if needed
1732 // later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001733 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001734 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001735 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001736 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001737 }
1738 }
1739
1740 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001741 EmitGlobalVarDefinition(D);
1742}
1743
Chris Lattner2192fe52011-07-18 04:24:23 +00001744CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001745 return Context.toCharUnitsFromBits(
Micah Villmowdd31ca12012-10-08 16:25:52 +00001746 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001747}
1748
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001749unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1750 unsigned AddrSpace) {
1751 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1752 if (D->hasAttr<CUDAConstantAttr>())
1753 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1754 else if (D->hasAttr<CUDASharedAttr>())
1755 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1756 else
1757 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1758 }
1759
1760 return AddrSpace;
1761}
1762
Richard Smithdf931ce2013-04-06 05:00:46 +00001763template<typename SomeDecl>
1764void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1765 llvm::GlobalValue *GV) {
1766 if (!getLangOpts().CPlusPlus)
1767 return;
1768
1769 // Must have 'used' attribute, or else inline assembly can't rely on
1770 // the name existing.
1771 if (!D->template hasAttr<UsedAttr>())
1772 return;
1773
1774 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001775 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00001776 return;
1777
1778 // Must be in an extern "C" context. Entities declared directly within
1779 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001780 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00001781 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00001782 return;
1783
1784 // OK, this is an internal linkage entity inside an extern "C" linkage
1785 // specification. Make a note of that so we can give it the "expected"
1786 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00001787 std::pair<StaticExternCMap::iterator, bool> R =
1788 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00001789
1790 // If we have multiple internal linkage entities with the same name
1791 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00001792 if (!R.second)
1793 R.first->second = 0;
Richard Smithdf931ce2013-04-06 05:00:46 +00001794}
1795
Daniel Dunbar9c426522008-07-29 23:18:29 +00001796void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001797 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001798 QualType ASTTy = D->getType();
Richard Smith6331c402012-02-13 22:16:19 +00001799 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1800 bool NeedsGlobalCtor = false;
1801 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00001802
Richard Smithdafff942012-01-14 04:30:29 +00001803 const VarDecl *InitDecl;
1804 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001805
Anders Carlssonca4a5452010-01-26 17:43:42 +00001806 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001807 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001808 // implicitly initialized with { 0 }.
1809 //
1810 // Note that tentative definitions are only emitted at the end of
1811 // a translation unit, so they should never have incomplete
1812 // type. In addition, EmitTentativeDefinition makes sure that we
1813 // never attempt to emit a tentative definition if a real one
1814 // exists. A use may still exists, however, so we still may need
1815 // to do a RAUW.
1816 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001817 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001818 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00001819 initializedGlobalDecl = GlobalDecl(D);
1820 Init = EmitConstantInit(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001821
Fariborz Jahanian63628032012-06-26 16:06:38 +00001822 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001823 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001824 if (D->getType()->isReferenceType())
1825 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00001826
David Blaikiebbafb8a2012-03-11 07:00:24 +00001827 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001828 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00001829 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001830 } else {
1831 ErrorUnsupported(D, "static initializer");
1832 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1833 }
John McCall70013b62010-07-15 23:40:35 +00001834 } else {
1835 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00001836 // initializer position (just in case this entry was delayed) if we
1837 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001838 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00001839 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001840 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001841 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001842
Chris Lattner2192fe52011-07-18 04:24:23 +00001843 llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001844 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattner149927c2009-03-21 09:16:30 +00001846 // Strip off a bitcast if we got one back.
1847 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001848 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00001849 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1850 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00001851 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001852 Entry = CE->getOperand(0);
1853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
Chris Lattner149927c2009-03-21 09:16:30 +00001855 // Entry is now either a Function or GlobalVariable.
1856 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001857
Chris Lattner149927c2009-03-21 09:16:30 +00001858 // We have a definition after a declaration with the wrong type.
1859 // We must make a new GlobalVariable* and update everything that used OldGV
1860 // (a declaration or tentative definition) with the new GlobalVariable*
1861 // (which will be a definition).
1862 //
1863 // This happens if there is a prototype for a global (e.g.
1864 // "extern int x[];") and then a definition of a different type (e.g.
1865 // "int x[10];"). This also happens when an initializer has a different type
1866 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001867 if (GV == 0 ||
1868 GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001869 GV->getType()->getAddressSpace() !=
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001870 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump11289f42009-09-09 15:08:12 +00001871
John McCall7ec50432010-03-19 23:29:14 +00001872 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001873 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001874
Chris Lattner149927c2009-03-21 09:16:30 +00001875 // Make a new global with the correct type, this is now guaranteed to work.
1876 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001877
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001878 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001879 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001880 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001881 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001882
1883 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001884 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001885 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001886
Richard Smithdf931ce2013-04-06 05:00:46 +00001887 MaybeHandleStaticInExternC(D, GV);
1888
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001889 if (D->hasAttr<AnnotateAttr>())
1890 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00001891
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001892 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001893
1894 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00001895 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1896 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00001897
Ken Dyck160146e2010-01-27 17:10:57 +00001898 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00001899
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001900 // Set the llvm linkage type as appropriate.
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001901 llvm::GlobalValue::LinkageTypes Linkage =
Eli Friedman7e346a82013-07-01 20:22:57 +00001902 GetLLVMLinkageVarDefinition(D, GV->isConstant());
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001903 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00001904 if (D->hasAttr<DLLImportAttr>())
1905 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1906 else if (D->hasAttr<DLLExportAttr>())
1907 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00001908
1909 // If required by the ABI, give definitions of static data members with inline
1910 // initializers linkonce_odr linkage.
1911 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1912 D->isStaticDataMember() && InitExpr &&
1913 !InitDecl->isThisDeclarationADefinition())
1914 GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage);
1915
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001916 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001917 // common vars aren't constant even if declared const.
1918 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001919
Daniel Dunbar38932572009-04-14 08:05:55 +00001920 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001921
John McCallcdf7ef52010-11-06 09:44:32 +00001922 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00001923 if (NeedsGlobalCtor || NeedsGlobalDtor)
1924 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00001925
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001926 // If we are compiling with ASan, add metadata indicating dynamically
1927 // initialized globals.
Will Dietzf54319c2013-01-18 11:30:38 +00001928 if (SanOpts.Address && NeedsGlobalCtor) {
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001929 llvm::Module &M = getModule();
1930
1931 llvm::NamedMDNode *DynamicInitializers =
1932 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1933 llvm::Value *GlobalToAdd[] = { GV };
1934 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1935 DynamicInitializers->addOperand(ThisGlobal);
1936 }
1937
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001938 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00001939 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001940 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00001941 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001942}
Chris Lattner09153c02007-06-22 18:48:09 +00001943
David Majnemer9832a3d2014-04-10 16:53:16 +00001944static bool isVarDeclStrongDefinition(const VarDecl *D, bool NoCommon) {
1945 // Don't give variables common linkage if -fno-common was specified unless it
1946 // was overridden by a NoCommon attribute.
1947 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
1948 return true;
1949
1950 // C11 6.9.2/2:
1951 // A declaration of an identifier for an object that has file scope without
1952 // an initializer, and without a storage-class specifier or with the
1953 // storage-class specifier static, constitutes a tentative definition.
1954 if (D->getInit() || D->hasExternalStorage())
1955 return true;
1956
1957 // A variable cannot be both common and exist in a section.
1958 if (D->hasAttr<SectionAttr>())
1959 return true;
1960
1961 // Thread local vars aren't considered common linkage.
1962 if (D->getTLSKind())
1963 return true;
1964
1965 // Tentative definitions marked with WeakImportAttr are true definitions.
1966 if (D->hasAttr<WeakImportAttr>())
1967 return true;
1968
1969 return false;
1970}
1971
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001972llvm::GlobalValue::LinkageTypes
Eli Friedman7e346a82013-07-01 20:22:57 +00001973CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001974 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1975 if (Linkage == GVA_Internal)
1976 return llvm::Function::InternalLinkage;
1977 else if (D->hasAttr<DLLImportAttr>())
Nico Rieckbb0554f2014-01-14 15:23:53 +00001978 return llvm::Function::ExternalLinkage;
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001979 else if (D->hasAttr<DLLExportAttr>())
Nico Rieckbb0554f2014-01-14 15:23:53 +00001980 return llvm::Function::ExternalLinkage;
Reid Klecknerb144d362013-05-20 14:02:37 +00001981 else if (D->hasAttr<SelectAnyAttr>()) {
1982 // selectany symbols are externally visible, so use weak instead of
1983 // linkonce. MSVC optimizes away references to const selectany globals, so
1984 // all definitions should be the same and ODR linkage should be used.
1985 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1986 return llvm::GlobalVariable::WeakODRLinkage;
1987 } else if (D->hasAttr<WeakAttr>()) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001988 if (isConstant)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001989 return llvm::GlobalVariable::WeakODRLinkage;
1990 else
1991 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer54e3ba52014-04-02 23:17:29 +00001992 } else if (Linkage == GVA_TemplateInstantiation || Linkage == GVA_StrongODR)
John McCalla97f3292011-04-12 01:46:54 +00001993 return llvm::GlobalVariable::WeakODRLinkage;
David Majnemer9832a3d2014-04-10 16:53:16 +00001994 else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1995 getTarget().getTriple().isMacOSX())
Bill Wendling95cae882013-05-02 19:18:03 +00001996 // On Darwin, the backing variable for a C++11 thread_local variable always
1997 // has internal linkage; all accesses should just be calls to the
1998 // Itanium-specified entry point, which has the normal linkage of the
1999 // variable.
2000 return llvm::GlobalValue::InternalLinkage;
David Majnemer9832a3d2014-04-10 16:53:16 +00002001 // C++ doesn't have tentative definitions and thus cannot have common linkage.
2002 else if (!getLangOpts().CPlusPlus &&
2003 !isVarDeclStrongDefinition(D, CodeGenOpts.NoCommon))
2004 return llvm::GlobalVariable::CommonLinkage;
2005
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002006 return llvm::GlobalVariable::ExternalLinkage;
2007}
2008
John McCall49954ca2012-12-12 22:21:47 +00002009/// Replace the uses of a function that was declared with a non-proto type.
2010/// We want to silently drop extra arguments from call sites
2011static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2012 llvm::Function *newFn) {
2013 // Fast path.
2014 if (old->use_empty()) return;
2015
2016 llvm::Type *newRetTy = newFn->getReturnType();
2017 SmallVector<llvm::Value*, 4> newArgs;
2018
2019 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2020 ui != ue; ) {
2021 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002022 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00002023
2024 // Recognize and replace uses of bitcasts. Most calls to
2025 // unprototyped functions will use bitcasts.
2026 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2027 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2028 replaceUsesOfNonProtoConstant(bitcast, newFn);
2029 continue;
2030 }
2031
2032 // Recognize calls to the function.
2033 llvm::CallSite callSite(user);
2034 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002035 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00002036
2037 // If the return types don't match exactly, then we can't
2038 // transform this call unless it's dead.
2039 if (callSite->getType() != newRetTy && !callSite->use_empty())
2040 continue;
2041
2042 // Get the call site's attribute list.
Bill Wendling290d9522013-01-27 02:46:53 +00002043 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCall49954ca2012-12-12 22:21:47 +00002044 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2045
2046 // Collect any return attributes from the call.
Bill Wendling304f6f02013-01-21 21:57:40 +00002047 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlingb7abb302013-01-21 22:45:00 +00002048 newAttrs.push_back(
Bill Wendling290d9522013-01-27 02:46:53 +00002049 llvm::AttributeSet::get(newFn->getContext(),
2050 oldAttrs.getRetAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002051
2052 // If the function was passed too few arguments, don't transform.
2053 unsigned newNumArgs = newFn->arg_size();
2054 if (callSite.arg_size() < newNumArgs) continue;
2055
2056 // If extra arguments were passed, we silently drop them.
2057 // If any of the types mismatch, we don't transform.
2058 unsigned argNo = 0;
2059 bool dontTransform = false;
2060 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2061 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2062 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2063 dontTransform = true;
2064 break;
2065 }
2066
2067 // Add any parameter attributes.
Bill Wendlingce2f9c52013-01-23 06:15:10 +00002068 if (oldAttrs.hasAttributes(argNo + 1))
2069 newAttrs.
Bill Wendling290d9522013-01-27 02:46:53 +00002070 push_back(llvm::
2071 AttributeSet::get(newFn->getContext(),
2072 oldAttrs.getParamAttributes(argNo + 1)));
John McCall49954ca2012-12-12 22:21:47 +00002073 }
2074 if (dontTransform)
2075 continue;
2076
Bill Wendling63ffde52013-01-18 21:26:07 +00002077 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendling290d9522013-01-27 02:46:53 +00002078 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2079 oldAttrs.getFnAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00002080
2081 // Okay, we can transform this. Create the new call instruction and copy
2082 // over the required information.
2083 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2084
2085 llvm::CallSite newCall;
2086 if (callSite.isCall()) {
2087 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2088 callSite.getInstruction());
2089 } else {
2090 llvm::InvokeInst *oldInvoke =
2091 cast<llvm::InvokeInst>(callSite.getInstruction());
2092 newCall = llvm::InvokeInst::Create(newFn,
2093 oldInvoke->getNormalDest(),
2094 oldInvoke->getUnwindDest(),
2095 newArgs, "",
2096 callSite.getInstruction());
2097 }
2098 newArgs.clear(); // for the next iteration
2099
2100 if (!newCall->getType()->isVoidTy())
2101 newCall->takeName(callSite.getInstruction());
2102 newCall.setAttributes(
2103 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2104 newCall.setCallingConv(callSite.getCallingConv());
2105
2106 // Finally, remove the old call, replacing any uses with the new one.
2107 if (!callSite->use_empty())
2108 callSite->replaceAllUsesWith(newCall.getInstruction());
2109
2110 // Copy debug location attached to CI.
2111 if (!callSite->getDebugLoc().isUnknown())
2112 newCall->setDebugLoc(callSite->getDebugLoc());
2113 callSite->eraseFromParent();
2114 }
2115}
2116
Chris Lattner36797ab2009-05-05 06:16:31 +00002117/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2118/// implement a function with no prototype, e.g. "int foo() {}". If there are
2119/// existing call uses of the old function in the module, this adjusts them to
2120/// call the new function directly.
2121///
2122/// This is not just a cleanup: the always_inline pass requires direct calls to
2123/// functions to be able to inline them. If there is a bitcast in the way, it
2124/// won't inline them. Instcombine normally deletes these calls, but it isn't
2125/// run at -O0.
2126static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2127 llvm::Function *NewFn) {
2128 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00002129 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00002130
John McCall49954ca2012-12-12 22:21:47 +00002131 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00002132}
2133
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00002134void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2135 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2136 // If we have a definition, this might be a deferred decl. If the
2137 // instantiation is explicit, make sure we emit it at the end.
2138 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2139 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00002140
2141 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00002142}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002143
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002144void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2145 llvm::GlobalValue *GV) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00002146 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00002147
John McCall46288ef2011-03-09 08:12:35 +00002148 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00002149 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2150 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00002151
Chris Lattnereb7466d2009-05-12 20:58:15 +00002152 // Get or create the prototype for the function.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002153 llvm::Constant *Entry =
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002154 GV ? GV
2155 : GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002156
Chris Lattnera85d68e2009-03-21 09:25:43 +00002157 // Strip off a bitcast if we got one back.
2158 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2159 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2160 Entry = CE->getOperand(0);
2161 }
Mike Stump11289f42009-09-09 15:08:12 +00002162
Argyrios Kyrtzidisf405dd62013-11-23 18:41:35 +00002163 if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) {
2164 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2165 return;
2166 }
Mike Stump11289f42009-09-09 15:08:12 +00002167
Chris Lattnera85d68e2009-03-21 09:25:43 +00002168 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00002169 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002170
Daniel Dunbar99d28352009-03-09 23:53:08 +00002171 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00002172 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00002173 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00002174
Chris Lattner5eaee562009-03-21 08:38:50 +00002175 // F is the Function* for the one with the wrong type, we must make a new
2176 // Function* and update everything that used F (a declaration) with the new
2177 // Function* (which will be a definition).
2178 //
2179 // This happens if there is a prototype for a function
2180 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00002181 // (e.g. "int f(int x)"). Move the old function aside so that it
2182 // doesn't interfere with GetAddrOfFunction.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002183 OldFn->setName(StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00002184 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00002185
John McCall49954ca2012-12-12 22:21:47 +00002186 // This might be an implementation of a function without a
2187 // prototype, in which case, try to do special replacement of
2188 // calls which match the new prototype. The really key thing here
2189 // is that we also potentially drop arguments from the call site
2190 // so as to make a direct call, which makes the inliner happier
2191 // and suppresses a number of optimizer warnings (!) about
2192 // dropping arguments.
2193 if (!OldFn->use_empty()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00002194 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00002195 OldFn->removeDeadConstantUsers();
2196 }
Mike Stump11289f42009-09-09 15:08:12 +00002197
Chris Lattner5eaee562009-03-21 08:38:50 +00002198 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00002199 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00002200 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00002201 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00002202 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2203 }
Mike Stump11289f42009-09-09 15:08:12 +00002204
Chris Lattner5eaee562009-03-21 08:38:50 +00002205 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00002206 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00002207
Chris Lattnera85d68e2009-03-21 09:25:43 +00002208 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002209 }
Mike Stump11289f42009-09-09 15:08:12 +00002210
John McCall8e7cb6d2010-11-02 21:04:24 +00002211 // We need to set linkage and visibility on the function before
2212 // generating code for it because various parts of IR generation
2213 // want to propagate this information down (e.g. to local static
2214 // declarations).
Chris Lattnera85d68e2009-03-21 09:25:43 +00002215 llvm::Function *Fn = cast<llvm::Function>(Entry);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002216 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002217
John McCall8e7cb6d2010-11-02 21:04:24 +00002218 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00002219 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00002220
Richard Smithdf931ce2013-04-06 05:00:46 +00002221 MaybeHandleStaticInExternC(D, Fn);
2222
John McCalla738c252011-03-09 04:27:21 +00002223 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00002224
Daniel Dunbar38932572009-04-14 08:05:55 +00002225 SetFunctionDefinitionAttributes(D, Fn);
2226 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00002227
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002228 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002229 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002230 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002231 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002232 if (D->hasAttr<AnnotateAttr>())
2233 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002234}
2235
John McCall7ec50432010-03-19 23:29:14 +00002236void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2237 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002238 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00002239 assert(AA && "Not an alias?");
2240
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002241 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00002242
John McCall7ec50432010-03-19 23:29:14 +00002243 // If there is a definition in the module, then it wins over the alias.
2244 // This is dubious, but allow it to be safe. Just ignore the alias.
2245 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2246 if (Entry && !Entry->isDeclaration())
2247 return;
2248
Rafael Espindola208b5c02013-10-22 19:26:13 +00002249 Aliases.push_back(GD);
2250
Chris Lattner2192fe52011-07-18 04:24:23 +00002251 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00002252
2253 // Create a reference to the named value. This ensures that it is emitted
2254 // if a deferred decl.
2255 llvm::Constant *Aliasee;
2256 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002257 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00002258 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00002259 else
John McCall7ec50432010-03-19 23:29:14 +00002260 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00002261 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00002262
2263 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00002264 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00002265 new llvm::GlobalAlias(Aliasee->getType(),
2266 llvm::Function::ExternalLinkage,
2267 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattner54041692009-03-22 21:47:11 +00002269 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00002270 assert(Entry->isDeclaration());
2271
Chris Lattner54041692009-03-22 21:47:11 +00002272 // If there is a declaration in the module, then we had an extern followed
2273 // by the alias, as in:
2274 // extern int test6();
2275 // ...
2276 // int test6() __attribute__((alias("test7")));
2277 //
2278 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00002279 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002280
Owen Andersonade90fd2009-07-29 18:54:39 +00002281 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00002282 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00002283 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00002284 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00002285 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00002286 }
Mike Stump11289f42009-09-09 15:08:12 +00002287
Daniel Dunbar38932572009-04-14 08:05:55 +00002288 // Set attributes which are particular to an alias; this is a
2289 // specialization of the attributes which may be set on a global
2290 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002291 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002292 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2293 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002294 if (FD->hasBody())
Nico Rieckbb0554f2014-01-14 15:23:53 +00002295 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar38932572009-04-14 08:05:55 +00002296 } else {
Nico Rieckbb0554f2014-01-14 15:23:53 +00002297 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar38932572009-04-14 08:05:55 +00002298 }
Mike Stump11289f42009-09-09 15:08:12 +00002299 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00002300 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002301 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002302 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2303 }
2304
2305 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00002306}
2307
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002308llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00002309 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00002310 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002311 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00002312}
Chris Lattner1eec6602007-08-31 04:31:45 +00002313
Daniel Dunbar64509b22009-07-23 22:52:48 +00002314static llvm::StringMapEntry<llvm::Constant*> &
2315GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2316 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00002317 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00002318 bool &IsUTF16,
2319 unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002320 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002321 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002322
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002323 // Check for simple case.
2324 if (!Literal->containsNonAsciiOrNull()) {
2325 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002326 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002327 }
2328
Bill Wendling82b87f12012-03-30 00:26:17 +00002329 // Otherwise, convert the UTF8 literals into a string of shorts.
2330 IsUTF16 = true;
2331
2332 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divackye6377112012-09-06 15:59:27 +00002333 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002334 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00002335
Fariborz Jahanian535618b2010-09-07 19:57:04 +00002336 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2337 &ToPtr, ToPtr + NumBytes,
2338 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00002339
Daniel Dunbar91ade142009-07-23 23:41:22 +00002340 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00002341 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00002342
Bill Wendling82b87f12012-03-30 00:26:17 +00002343 // Add an explicit null.
2344 *ToPtr = 0;
2345 return Map.
2346 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2347 (StringLength + 1) * 2));
Daniel Dunbar64509b22009-07-23 22:52:48 +00002348}
2349
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002350static llvm::StringMapEntry<llvm::Constant*> &
2351GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling07635cc2012-03-29 22:12:09 +00002352 const StringLiteral *Literal,
2353 unsigned &StringLength) {
2354 StringRef String = Literal->getString();
2355 StringLength = String.size();
2356 return Map.GetOrCreateValue(String);
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002357}
2358
Daniel Dunbar64509b22009-07-23 22:52:48 +00002359llvm::Constant *
2360CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2361 unsigned StringLength = 0;
2362 bool isUTF16 = false;
2363 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00002364 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002365 getDataLayout().isLittleEndian(),
Daniel Dunbar91ade142009-07-23 23:41:22 +00002366 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002367
Daniel Dunbar64509b22009-07-23 22:52:48 +00002368 if (llvm::Constant *C = Entry.getValue())
2369 return C;
Mike Stump11289f42009-09-09 15:08:12 +00002370
Chris Lattnerece04092012-02-07 00:39:47 +00002371 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00002372 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002373 llvm::Value *V;
2374
Chris Lattneraa64ca22009-07-16 16:48:25 +00002375 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00002376 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002377 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002378 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002379 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00002380 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00002381 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002382 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2383 CFConstantStringClassRef = V;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002384 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002385 else
2386 V = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00002387
Anders Carlssonc2480a52008-11-15 18:54:24 +00002388 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00002389
Chris Lattner2192fe52011-07-18 04:24:23 +00002390 llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00002391 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2392
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002393 llvm::Constant *Fields[4];
Douglas Gregor91f84212008-12-11 16:49:14 +00002394
Anders Carlssonb04ea612007-08-21 00:21:21 +00002395 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002396 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump11289f42009-09-09 15:08:12 +00002397
Anders Carlssonb04ea612007-08-21 00:21:21 +00002398 // Flags.
Chris Lattner2192fe52011-07-18 04:24:23 +00002399 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00002400 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00002401 llvm::ConstantInt::get(Ty, 0x07C8);
2402
Anders Carlssonb04ea612007-08-21 00:21:21 +00002403 // String pointer.
Bill Wendling82b87f12012-03-30 00:26:17 +00002404 llvm::Constant *C = 0;
2405 if (isUTF16) {
2406 ArrayRef<uint16_t> Arr =
David Greene0a528db2013-01-15 22:09:41 +00002407 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2408 const_cast<char *>(Entry.getKey().data())),
Bill Wendling82b87f12012-03-30 00:26:17 +00002409 Entry.getKey().size() / 2);
2410 C = llvm::ConstantDataArray::get(VMContext, Arr);
2411 } else {
2412 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2413 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002414
Bill Wendling86131f22012-01-10 08:46:39 +00002415 // Note: -fwritable-strings doesn't make the backing store strings of
2416 // CFStrings writable. (See <rdar://problem/10657500>)
Mike Stump11289f42009-09-09 15:08:12 +00002417 llvm::GlobalVariable *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00002418 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2419 llvm::GlobalValue::PrivateLinkage, C, ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00002420 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002421 // Don't enforce the target's minimum global alignment, since the only use
2422 // of the string is via this class initializer.
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002423 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2424 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2425 // that changes the section it ends in, which surprises ld64.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002426 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00002427 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2428 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002429 GV->setSection("__TEXT,__ustring");
Daniel Dunbar9c8cd4c2011-04-12 23:30:52 +00002430 } else {
2431 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2432 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002433 GV->setSection("__TEXT,__cstring,cstring_literals");
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002434 }
Bill Wendling82b87f12012-03-30 00:26:17 +00002435
2436 // String.
Jay Foaded8db7d2011-07-21 14:31:17 +00002437 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00002438
Bill Wendling82b87f12012-03-30 00:26:17 +00002439 if (isUTF16)
2440 // Cast the UTF16 string to the correct type.
2441 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2442
Anders Carlssonb04ea612007-08-21 00:21:21 +00002443 // String length.
2444 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00002445 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002446
Anders Carlssonb04ea612007-08-21 00:21:21 +00002447 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00002448 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00002449 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2450 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00002451 "_unnamed_cfstring_");
Rafael Espindola8ff16102014-01-20 20:13:11 +00002452 GV->setSection("__DATA,__cfstring");
Daniel Dunbar64509b22009-07-23 22:52:48 +00002453 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00002454
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00002455 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002456}
Chris Lattnerfb300092007-11-28 05:34:05 +00002457
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002458llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002459CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002460 unsigned StringLength = 0;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002461 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002462 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002463
2464 if (llvm::Constant *C = Entry.getValue())
2465 return C;
2466
Chris Lattner00a10ca2012-02-06 22:47:00 +00002467 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002468 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002469 llvm::Value *V;
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002470 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002471 if (!ConstantStringClassRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002472 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2192fe52011-07-18 04:24:23 +00002473 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002474 llvm::Constant *GV;
John McCall5fb5df92012-06-20 06:18:46 +00002475 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002476 std::string str =
2477 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2478 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002479 GV = getObjCRuntime().GetClassGlobal(str);
2480 // Make sure the result is of the correct type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002481 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002482 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2483 ConstantStringClassRef = V;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002484 } else {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002485 std::string str =
2486 StringClass.empty() ? "_NSConstantStringClassReference"
2487 : "_" + StringClass + "ClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00002488 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002489 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002490 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002491 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2492 ConstantStringClassRef = V;
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002493 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002494 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002495 else
2496 V = ConstantStringClassRef;
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002497
2498 if (!NSConstantStringType) {
2499 // Construct the type for a constant NSString.
Alp Toker2dea15b2013-12-17 01:22:38 +00002500 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002501 D->startDefinition();
2502
2503 QualType FieldTypes[3];
2504
2505 // const int *isa;
2506 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2507 // const char *str;
2508 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2509 // unsigned int length;
2510 FieldTypes[2] = Context.UnsignedIntTy;
2511
2512 // Create fields
2513 for (unsigned i = 0; i < 3; ++i) {
2514 FieldDecl *Field = FieldDecl::Create(Context, D,
2515 SourceLocation(),
2516 SourceLocation(), 0,
2517 FieldTypes[i], /*TInfo=*/0,
2518 /*BitWidth=*/0,
2519 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002520 ICIS_NoInit);
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002521 Field->setAccess(AS_public);
2522 D->addDecl(Field);
2523 }
2524
2525 D->completeDefinition();
2526 QualType NSTy = Context.getTagDeclType(D);
2527 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2528 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002529
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002530 llvm::Constant *Fields[3];
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002531
2532 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002533 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002534
2535 // String pointer.
Chris Lattner9c818332012-02-05 02:30:40 +00002536 llvm::Constant *C =
2537 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002538
2539 llvm::GlobalValue::LinkageTypes Linkage;
2540 bool isConstant;
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002541 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002542 isConstant = !LangOpts.WritableStrings;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002543
2544 llvm::GlobalVariable *GV =
2545 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2546 ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00002547 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002548 // Don't enforce the target's minimum global alignment, since the only use
2549 // of the string is via this class initializer.
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002550 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2551 GV->setAlignment(Align.getQuantity());
Jay Foaded8db7d2011-07-21 14:31:17 +00002552 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002553
2554 // String length.
Chris Lattner2192fe52011-07-18 04:24:23 +00002555 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002556 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2557
2558 // The struct.
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002559 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002560 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2561 llvm::GlobalVariable::PrivateLinkage, C,
2562 "_unnamed_nsstring_");
Rafael Espindola63582d62014-01-20 15:19:43 +00002563 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2564 const char *NSStringNonFragileABISection =
Rafael Espindola8ff16102014-01-20 20:13:11 +00002565 "__DATA,__objc_stringobj,regular,no_dead_strip";
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002566 // FIXME. Fix section.
Rafael Espindola8ff16102014-01-20 20:13:11 +00002567 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2568 ? NSStringNonFragileABISection
2569 : NSStringSection);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002570 Entry.setValue(GV);
2571
2572 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002573}
2574
Douglas Gregor636e2002011-08-09 17:23:49 +00002575QualType CodeGenModule::getObjCFastEnumerationStateType() {
2576 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00002577 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00002578 D->startDefinition();
2579
2580 QualType FieldTypes[] = {
2581 Context.UnsignedLongTy,
2582 Context.getPointerType(Context.getObjCIdType()),
2583 Context.getPointerType(Context.UnsignedLongTy),
2584 Context.getConstantArrayType(Context.UnsignedLongTy,
2585 llvm::APInt(32, 5), ArrayType::Normal, 0)
2586 };
2587
2588 for (size_t i = 0; i < 4; ++i) {
2589 FieldDecl *Field = FieldDecl::Create(Context,
2590 D,
2591 SourceLocation(),
2592 SourceLocation(), 0,
2593 FieldTypes[i], /*TInfo=*/0,
2594 /*BitWidth=*/0,
2595 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002596 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00002597 Field->setAccess(AS_public);
2598 D->addDecl(Field);
2599 }
2600
2601 D->completeDefinition();
2602 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2603 }
2604
2605 return ObjCFastEnumerationStateType;
2606}
2607
Eli Friedmanfcec6302011-11-01 02:23:42 +00002608llvm::Constant *
2609CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2610 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2611
2612 // Don't emit it as the address of the string, emit the string data itself
2613 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002614 if (E->getCharByteWidth() == 1) {
2615 SmallString<64> Str(E->getString());
2616
2617 // Resize the string to the right size, which is indicated by its type.
2618 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2619 Str.resize(CAT->getSize().getZExtValue());
2620 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2621 }
Chris Lattner9c818332012-02-05 02:30:40 +00002622
2623 llvm::ArrayType *AType =
2624 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2625 llvm::Type *ElemTy = AType->getElementType();
2626 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00002627
2628 // Wide strings have either 2-byte or 4-byte elements.
2629 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2630 SmallVector<uint16_t, 32> Elements;
2631 Elements.reserve(NumElements);
2632
2633 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2634 Elements.push_back(E->getCodeUnit(i));
2635 Elements.resize(NumElements);
2636 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00002637 }
2638
Chris Lattner02cb1712012-02-06 22:52:04 +00002639 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2640 SmallVector<uint32_t, 32> Elements;
2641 Elements.reserve(NumElements);
2642
2643 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2644 Elements.push_back(E->getCodeUnit(i));
2645 Elements.resize(NumElements);
2646 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002647}
2648
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002649/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2650/// constant array for the given string literal.
2651llvm::Constant *
2652CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
Ulrich Weigandfa806422013-05-06 16:23:57 +00002653 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
David Majnemer58e5bee2014-03-24 21:43:36 +00002654
2655 llvm::StringMapEntry<llvm::GlobalVariable *> *Entry = nullptr;
2656 llvm::GlobalVariable *GV = nullptr;
2657 if (!LangOpts.WritableStrings) {
2658 llvm::StringMap<llvm::GlobalVariable *> *ConstantStringMap = nullptr;
2659 switch (S->getCharByteWidth()) {
2660 case 1:
2661 ConstantStringMap = &Constant1ByteStringMap;
2662 break;
2663 case 2:
2664 ConstantStringMap = &Constant2ByteStringMap;
2665 break;
2666 case 4:
2667 ConstantStringMap = &Constant4ByteStringMap;
2668 break;
2669 default:
2670 llvm_unreachable("unhandled byte width!");
2671 }
2672 Entry = &ConstantStringMap->GetOrCreateValue(S->getBytes());
2673 GV = Entry->getValue();
Eli Friedman49ddc5f2009-11-16 05:55:46 +00002674 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00002675
David Majnemer58e5bee2014-03-24 21:43:36 +00002676 if (!GV) {
2677 SmallString<256> MangledNameBuffer;
2678 StringRef GlobalVariableName;
2679 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00002680
David Majnemer58e5bee2014-03-24 21:43:36 +00002681 // Mangle the string literal if the ABI allows for it. However, we cannot
2682 // do this if we are compiling with ASan or -fwritable-strings because they
2683 // rely on strings having normal linkage.
2684 if (!LangOpts.WritableStrings && !SanOpts.Address &&
2685 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2686 llvm::raw_svector_ostream Out(MangledNameBuffer);
2687 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2688 Out.flush();
2689
2690 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2691 GlobalVariableName = MangledNameBuffer;
2692 } else {
2693 LT = llvm::GlobalValue::PrivateLinkage;;
2694 GlobalVariableName = ".str";
2695 }
2696
2697 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2698 unsigned AddrSpace = 0;
2699 if (getLangOpts().OpenCL)
2700 AddrSpace = getContext().getTargetAddressSpace(LangAS::opencl_constant);
2701
2702 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2703 GV = new llvm::GlobalVariable(
2704 getModule(), C->getType(), !LangOpts.WritableStrings, LT, C,
2705 GlobalVariableName, /*InsertBefore=*/nullptr,
2706 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2707 GV->setUnnamedAddr(true);
2708 if (Entry)
2709 Entry->setValue(GV);
2710 }
2711
2712 if (Align.getQuantity() > GV->getAlignment())
2713 GV->setAlignment(Align.getQuantity());
2714
Eli Friedmanfcec6302011-11-01 02:23:42 +00002715 return GV;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002716}
2717
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002718/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2719/// array for the given ObjCEncodeExpr node.
2720llvm::Constant *
2721CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2722 std::string Str;
2723 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00002724
2725 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002726}
2727
2728
Chris Lattner36fc8792008-02-11 00:02:17 +00002729/// GenerateWritableString -- Creates storage for a string literal.
John McCall9b24df42011-08-04 01:03:22 +00002730static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattnerfb300092007-11-28 05:34:05 +00002731 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00002732 CodeGenModule &CGM,
John McCall9b24df42011-08-04 01:03:22 +00002733 const char *GlobalName,
2734 unsigned Alignment) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002735 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00002736 llvm::Constant *C =
Chris Lattner9c818332012-02-05 02:30:40 +00002737 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00002738
David Majnemer58e5bee2014-03-24 21:43:36 +00002739 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
Joey Gouly561bba22013-11-14 18:26:10 +00002740 unsigned AddrSpace = 0;
2741 if (CGM.getLangOpts().OpenCL)
2742 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2743
Chris Lattnerfb300092007-11-28 05:34:05 +00002744 // Create a global variable for this string
Joey Gouly561bba22013-11-14 18:26:10 +00002745 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2746 CGM.getModule(), C->getType(), constant,
2747 llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0,
2748 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall9b24df42011-08-04 01:03:22 +00002749 GV->setAlignment(Alignment);
Rafael Espindolab7f60e32011-01-10 22:34:03 +00002750 GV->setUnnamedAddr(true);
2751 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002752}
2753
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002754/// GetAddrOfConstantString - Returns a pointer to a character array
2755/// containing the literal. This contents are exactly that of the
2756/// given string, i.e. it will not be null terminated automatically;
2757/// see GetAddrOfConstantCString. Note that whether the result is
2758/// actually a pointer to an LLVM constant depends on
2759/// Feature.WriteableStrings.
2760///
2761/// The result has pointer to array type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002762llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCall9b24df42011-08-04 01:03:22 +00002763 const char *GlobalName,
2764 unsigned Alignment) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002765 // Get the default prefix if a name wasn't specified.
2766 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00002767 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002768
Ulrich Weigandfa806422013-05-06 16:23:57 +00002769 if (Alignment == 0)
2770 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2771 .getQuantity();
2772
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002773 // Don't share any string literals if strings aren't constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002774 if (LangOpts.WritableStrings)
John McCall9b24df42011-08-04 01:03:22 +00002775 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump11289f42009-09-09 15:08:12 +00002776
John McCall9b24df42011-08-04 01:03:22 +00002777 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
David Majnemer58e5bee2014-03-24 21:43:36 +00002778 Constant1ByteStringMap.GetOrCreateValue(Str);
Chris Lattnerfb300092007-11-28 05:34:05 +00002779
John McCall9b24df42011-08-04 01:03:22 +00002780 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2781 if (Alignment > GV->getAlignment()) {
2782 GV->setAlignment(Alignment);
2783 }
2784 return GV;
2785 }
Chris Lattnerfb300092007-11-28 05:34:05 +00002786
2787 // Create a global variable for this.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002788 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2789 Alignment);
John McCall9b24df42011-08-04 01:03:22 +00002790 Entry.setValue(GV);
2791 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002792}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002793
2794/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002795/// array containing the literal and a terminating '\0'
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002796/// character. The result has pointer to array type.
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002797llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCall9b24df42011-08-04 01:03:22 +00002798 const char *GlobalName,
2799 unsigned Alignment) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002800 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall9b24df42011-08-04 01:03:22 +00002801 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002802}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002803
Richard Smithe6c01442013-06-05 00:46:14 +00002804llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00002805 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00002806 assert((E->getStorageDuration() == SD_Static ||
2807 E->getStorageDuration() == SD_Thread) && "not a global temporary");
2808 const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2809
2810 // If we're not materializing a subobject of the temporary, keep the
2811 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00002812 QualType MaterializedType = Init->getType();
2813 if (Init == E->GetTemporaryExpr())
2814 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00002815
2816 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2817 if (Slot)
2818 return Slot;
2819
2820 // FIXME: If an externally-visible declaration extends multiple temporaries,
2821 // we need to give each temporary the same name in every translation unit (and
2822 // we also need to make the temporaries externally-visible).
2823 SmallString<256> Name;
2824 llvm::raw_svector_ostream Out(Name);
2825 getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
2826 Out.flush();
2827
Richard Smithe6c01442013-06-05 00:46:14 +00002828 APValue *Value = 0;
2829 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00002830 // We might have a cached constant initializer for this temporary. Note
2831 // that this might have a different value from the value computed by
2832 // evaluating the initializer if the surrounding constant expression
2833 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00002834 Value = getContext().getMaterializedTemporaryValue(E, false);
2835 if (Value && Value->isUninit())
2836 Value = 0;
2837 }
2838
Richard Smitha509f2f2013-06-14 03:07:01 +00002839 // Try evaluating it now, it might have a constant initializer.
2840 Expr::EvalResult EvalResult;
2841 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2842 !EvalResult.hasSideEffects())
2843 Value = &EvalResult.Val;
2844
2845 llvm::Constant *InitialValue = 0;
2846 bool Constant = false;
2847 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00002848 if (Value) {
2849 // The temporary has a constant initializer, use it.
Richard Smitha509f2f2013-06-14 03:07:01 +00002850 InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2851 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2852 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00002853 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00002854 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00002855 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00002856 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00002857 }
2858
2859 // Create a global variable for this lifetime-extended temporary.
2860 llvm::GlobalVariable *GV =
Richard Smitha509f2f2013-06-14 03:07:01 +00002861 new llvm::GlobalVariable(getModule(), Type, Constant,
2862 llvm::GlobalValue::PrivateLinkage,
2863 InitialValue, Name.c_str());
Richard Smithe6c01442013-06-05 00:46:14 +00002864 GV->setAlignment(
Richard Smitha509f2f2013-06-14 03:07:01 +00002865 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
Richard Smithe6c01442013-06-05 00:46:14 +00002866 if (VD->getTLSKind())
2867 setTLSMode(GV, *VD);
2868 Slot = GV;
2869 return GV;
2870}
2871
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002872/// EmitObjCPropertyImplementations - Emit information for synthesized
2873/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00002874void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002875 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00002876 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002877 // Dynamic is just for type-checking.
2878 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2879 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2880
2881 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00002882 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002883 // we want, that just indicates if the decl came from a
2884 // property. What we want to know is if the method is defined in
2885 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002886 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002887 CodeGenFunction(*this).GenerateObjCGetter(
2888 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002889 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002890 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002891 CodeGenFunction(*this).GenerateObjCSetter(
2892 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002893 }
2894 }
2895}
2896
John McCall6a4fa522011-03-22 07:05:39 +00002897static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002898 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2899 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00002900 ivar; ivar = ivar->getNextIvar())
2901 if (ivar->getType().isDestructedType())
2902 return true;
2903
2904 return false;
2905}
2906
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002907/// EmitObjCIvarInitializations - Emit information for ivar initialization
2908/// for an implementation.
2909void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00002910 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2911 if (needsDestructMethod(D)) {
2912 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2913 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2914 ObjCMethodDecl *DTORMethod =
2915 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002916 cxxSelector, getContext().VoidTy, 0, D,
2917 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002918 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002919 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00002920 D->addInstanceMethod(DTORMethod);
2921 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00002922 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00002923 }
2924
2925 // If the implementation doesn't have any ivar initializers, we don't need
2926 // a .cxx_construct.
David Chisnalla9e54602011-03-17 14:19:08 +00002927 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002928 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002929
John McCall6a4fa522011-03-22 07:05:39 +00002930 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2931 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002932 // The constructor returns 'self'.
2933 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2934 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002935 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002936 cxxSelector,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002937 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002938 D, /*isInstance=*/true,
2939 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002940 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002941 /*isImplicitlyDeclared=*/true,
2942 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002943 ObjCMethodDecl::Required);
2944 D->addInstanceMethod(CTORMethod);
2945 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00002946 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002947}
2948
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002949/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00002950void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Aaron Ballman629afae2014-03-07 19:56:05 +00002951 for (auto *I : ND->decls()) {
2952 if (const auto *VD = dyn_cast<VarDecl>(I))
David Blaikieb00f3602013-09-04 21:07:37 +00002953 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2954 VD->getTemplateSpecializationKind() != TSK_Undeclared)
2955 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00002956 EmitTopLevelDecl(I);
David Blaikieb00f3602013-09-04 21:07:37 +00002957 }
Anders Carlsson237f3492009-04-01 00:58:25 +00002958}
2959
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002960// EmitLinkageSpec - Emit all declarations in a linkage spec.
2961void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00002962 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2963 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002964 ErrorUnsupported(LSD, "linkage spec");
2965 return;
2966 }
2967
Aaron Ballman629afae2014-03-07 19:56:05 +00002968 for (auto *I : LSD->decls()) {
Fariborz Jahanian9dd2e082012-10-26 22:20:25 +00002969 // Meta-data for ObjC class includes references to implemented methods.
2970 // Generate class's method definitions first.
Aaron Ballman629afae2014-03-07 19:56:05 +00002971 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00002972 for (auto *M : OID->methods())
2973 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00002974 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002975 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00002976 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002977}
2978
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002979/// EmitTopLevelDecl - Emit code for a single top level declaration.
2980void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002981 // Ignore dependent declarations.
2982 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2983 return;
Mike Stump11289f42009-09-09 15:08:12 +00002984
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002985 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00002986 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00002987 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002988 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00002989 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00002990 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2991 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00002992 return;
Mike Stump11289f42009-09-09 15:08:12 +00002993
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002994 EmitGlobal(cast<FunctionDecl>(D));
2995 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002996
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002997 case Decl::Var:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002998 // Skip variable templates
2999 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3000 return;
3001 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003002 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003003 break;
3004
John McCall32f44bd2011-04-12 01:01:22 +00003005 // Indirect fields from global anonymous structs and unions can be
3006 // ignored; only the actual variable requires IR gen support.
3007 case Decl::IndirectField:
3008 break;
3009
Anders Carlssonf7475242009-04-15 15:55:24 +00003010 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003011 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00003012 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003013 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00003014 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00003015 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003016 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003017 case Decl::VarTemplate:
3018 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003019 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00003020 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003021 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00003022 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00003023 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00003024 case Decl::Using: // using X; [C++]
3025 if (CGDebugInfo *DI = getModuleDebugInfo())
3026 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3027 return;
David Blaikief121b932013-05-20 22:50:41 +00003028 case Decl::NamespaceAlias:
3029 if (CGDebugInfo *DI = getModuleDebugInfo())
3030 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3031 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00003032 case Decl::UsingDirective: // using namespace X; [C++]
3033 if (CGDebugInfo *DI = getModuleDebugInfo())
3034 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3035 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00003036 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00003037 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003038 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3039 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00003040 return;
3041
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00003042 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00003043 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003044 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00003045 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3046 return;
Reid Klecknere7de47e2013-07-22 13:51:44 +00003047 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003048 break;
Anders Carlsson87835432009-06-11 21:22:55 +00003049
3050 case Decl::StaticAssert:
3051 // Nothing to do.
3052 break;
3053
Anders Carlssonf7475242009-04-15 15:55:24 +00003054 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00003055
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003056 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00003057 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00003058 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00003059 break;
3060
Douglas Gregorf6102672012-01-01 21:23:57 +00003061 case Decl::ObjCProtocol: {
3062 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
3063 if (Proto->isThisDeclarationADefinition())
3064 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003065 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00003066 }
3067
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003068 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003069 // Categories have properties but don't support synthesize so we
3070 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00003071 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003072 break;
3073
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003074 case Decl::ObjCImplementation: {
3075 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
3076 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003077 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00003078 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00003079 // Emit global variable debug information.
3080 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00003081 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3082 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3083 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003084 break;
Mike Stump11289f42009-09-09 15:08:12 +00003085 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003086 case Decl::ObjCMethod: {
3087 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
3088 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003089 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003090 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3091 break;
3092 }
Mike Stump11289f42009-09-09 15:08:12 +00003093 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00003094 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003095 break;
3096
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003097 case Decl::LinkageSpec:
3098 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003099 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003100
3101 case Decl::FileScopeAsm: {
3102 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003103 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00003104
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003105 const std::string &S = getModule().getModuleInlineAsm();
3106 if (S.empty())
3107 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8c02a242012-08-10 10:57:52 +00003108 else if (S.end()[-1] == '\n')
Chris Lattner84037d32011-07-23 20:04:25 +00003109 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003110 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00003111 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003112 break;
3113 }
Mike Stump11289f42009-09-09 15:08:12 +00003114
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003115 case Decl::Import: {
3116 ImportDecl *Import = cast<ImportDecl>(D);
3117
3118 // Ignore import declarations that come from imported modules.
3119 if (clang::Module *Owner = Import->getOwningModule()) {
3120 if (getLangOpts().CurrentModule.empty() ||
3121 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3122 break;
3123 }
3124
Douglas Gregorbc25ff42013-01-14 20:53:57 +00003125 ImportedModules.insert(Import->getImportedModule());
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003126 break;
David Blaikie0e716b42014-03-03 23:48:23 +00003127 }
3128
3129 case Decl::ClassTemplateSpecialization: {
3130 const ClassTemplateSpecializationDecl *Spec =
3131 cast<ClassTemplateSpecializationDecl>(D);
3132 if (DebugInfo &&
3133 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
3134 DebugInfo->completeTemplateDefinition(*Spec);
3135 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003136
Mike Stump11289f42009-09-09 15:08:12 +00003137 default:
Mike Stump18bb9282009-05-16 07:57:57 +00003138 // Make sure we handled everything we should, every other kind is a
3139 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3140 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003141 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3142 }
3143}
John McCall09ae0322010-07-06 23:57:41 +00003144
3145/// Turns the given pointer into a constant.
3146static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3147 const void *Ptr) {
3148 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00003149 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00003150 return llvm::ConstantInt::get(i64, PtrInt);
3151}
3152
3153static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3154 llvm::NamedMDNode *&GlobalMetadata,
3155 GlobalDecl D,
3156 llvm::GlobalValue *Addr) {
3157 if (!GlobalMetadata)
3158 GlobalMetadata =
3159 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3160
3161 // TODO: should we report variant information for ctors/dtors?
3162 llvm::Value *Ops[] = {
3163 Addr,
3164 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3165 };
Jay Foadea324f12011-04-21 19:59:12 +00003166 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00003167}
3168
Richard Smithdf931ce2013-04-06 05:00:46 +00003169/// For each function which is declared within an extern "C" region and marked
3170/// as 'used', but has internal linkage, create an alias from the unmangled
3171/// name to the mangled name if possible. People expect to be able to refer
3172/// to such functions with an unmangled name from inline assembly within the
3173/// same translation unit.
3174void CodeGenModule::EmitStaticExternCAliases() {
Richard Smithf21c9612013-04-13 01:28:18 +00003175 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3176 E = StaticExternCValues.end();
3177 I != E; ++I) {
3178 IdentifierInfo *Name = I->first;
3179 llvm::GlobalValue *Val = I->second;
Richard Smith85465e62013-04-06 07:07:44 +00003180 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola060062a2014-03-06 22:15:10 +00003181 addUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
Richard Smith85465e62013-04-06 07:07:44 +00003182 Name->getName(), Val, &getModule()));
3183 }
Richard Smithdf931ce2013-04-06 05:00:46 +00003184}
3185
John McCall09ae0322010-07-06 23:57:41 +00003186/// Emits metadata nodes associating all the global values in the
3187/// current module with the Decls they came from. This is useful for
3188/// projects using IR gen as a subroutine.
3189///
3190/// Since there's currently no way to associate an MDNode directly
3191/// with an llvm::GlobalValue, we create a global named metadata
3192/// with the name 'clang.global.decl.ptrs'.
3193void CodeGenModule::EmitDeclMetadata() {
3194 llvm::NamedMDNode *GlobalMetadata = 0;
3195
3196 // StaticLocalDeclMap
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003197 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall09ae0322010-07-06 23:57:41 +00003198 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3199 I != E; ++I) {
3200 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3201 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3202 }
3203}
3204
3205/// Emits metadata nodes for all the local variables in the current
3206/// function.
3207void CodeGenFunction::EmitDeclMetadata() {
3208 if (LocalDeclMap.empty()) return;
3209
3210 llvm::LLVMContext &Context = getLLVMContext();
3211
3212 // Find the unique metadata ID for this name.
3213 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3214
3215 llvm::NamedMDNode *GlobalMetadata = 0;
3216
3217 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3218 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3219 const Decl *D = I->first;
3220 llvm::Value *Addr = I->second;
3221
3222 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3223 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foadea324f12011-04-21 19:59:12 +00003224 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall09ae0322010-07-06 23:57:41 +00003225 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3226 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3227 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3228 }
3229 }
3230}
Daniel Dunbar900546d2010-07-16 00:00:15 +00003231
Rafael Espindola3bfa4682013-10-16 19:28:50 +00003232void CodeGenModule::EmitVersionIdentMetadata() {
3233 llvm::NamedMDNode *IdentMetadata =
3234 TheModule.getOrInsertNamedMetadata("llvm.ident");
3235 std::string Version = getClangFullVersion();
3236 llvm::LLVMContext &Ctx = TheModule.getContext();
3237
3238 llvm::Value *IdentNode[] = {
3239 llvm::MDString::get(Ctx, Version)
3240 };
3241 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3242}
3243
Nick Lewycky85c011d2011-05-05 00:08:20 +00003244void CodeGenModule::EmitCoverageFile() {
3245 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky480cb992011-05-04 20:46:58 +00003246 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3247 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3248 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky85c011d2011-05-05 00:08:20 +00003249 llvm::MDString *CoverageFile =
3250 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky480cb992011-05-04 20:46:58 +00003251 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3252 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky85c011d2011-05-05 00:08:20 +00003253 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky480cb992011-05-04 20:46:58 +00003254 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3255 GCov->addOperand(N);
3256 }
3257 }
3258 }
3259}
Nico Webercf4ff5862012-10-11 10:13:44 +00003260
3261llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3262 QualType GuidType) {
3263 // Sema has checked that all uuid strings are of the form
3264 // "12345678-1234-1234-1234-1234567890ab".
3265 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00003266 for (unsigned i = 0; i < 36; ++i) {
3267 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3268 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00003269 }
Nico Webercf4ff5862012-10-11 10:13:44 +00003270
David Majnemerbbecd092013-08-15 19:59:14 +00003271 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00003272
David Majnemerbbecd092013-08-15 19:59:14 +00003273 llvm::Constant *Field3[8];
3274 for (unsigned Idx = 0; Idx < 8; ++Idx)
3275 Field3[Idx] = llvm::ConstantInt::get(
3276 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3277
3278 llvm::Constant *Fields[4] = {
3279 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3280 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3281 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3282 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3283 };
3284
3285 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00003286}