xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 629afaefe0cd1a583ccee54918b7b13f48bfe273)
1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-module state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenModule.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCall.h"
18 #include "CGDebugInfo.h"
19 #include "CGObjCRuntime.h"
20 #include "CGOpenCLRuntime.h"
21 #include "CodeGenFunction.h"
22 #include "CodeGenPGO.h"
23 #include "CodeGenTBAA.h"
24 #include "TargetInfo.h"
25 #include "clang/AST/ASTContext.h"
26 #include "clang/AST/CharUnits.h"
27 #include "clang/AST/DeclCXX.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/DeclTemplate.h"
30 #include "clang/AST/Mangle.h"
31 #include "clang/AST/RecordLayout.h"
32 #include "clang/AST/RecursiveASTVisitor.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/CharInfo.h"
35 #include "clang/Basic/Diagnostic.h"
36 #include "clang/Basic/Module.h"
37 #include "clang/Basic/SourceManager.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Basic/Version.h"
40 #include "clang/Frontend/CodeGenOptions.h"
41 #include "clang/Sema/SemaDiagnostic.h"
42 #include "llvm/ADT/APSInt.h"
43 #include "llvm/ADT/Triple.h"
44 #include "llvm/IR/CallSite.h"
45 #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"
50 #include "llvm/Support/ConvertUTF.h"
51 #include "llvm/Support/ErrorHandling.h"
52 
53 using namespace clang;
54 using namespace CodeGen;
55 
56 static const char AnnotationSection[] = "llvm.metadata";
57 
58 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
59   switch (CGM.getTarget().getCXXABI().getKind()) {
60   case TargetCXXABI::GenericAArch64:
61   case TargetCXXABI::GenericARM:
62   case TargetCXXABI::iOS:
63   case TargetCXXABI::GenericItanium:
64     return CreateItaniumCXXABI(CGM);
65   case TargetCXXABI::Microsoft:
66     return CreateMicrosoftCXXABI(CGM);
67   }
68 
69   llvm_unreachable("invalid C++ ABI kind");
70 }
71 
72 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
73                              llvm::Module &M, const llvm::DataLayout &TD,
74                              DiagnosticsEngine &diags)
75     : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
76       Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
77       ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
78       TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
79       OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0),
80       NoObjCARCExceptionsMetadata(0), RRData(0), PGOData(0),
81       CFConstantStringClassRef(0),
82       ConstantStringClassRef(0), NSConstantStringType(0),
83       NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
84       BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
85       LifetimeStartFn(0), LifetimeEndFn(0),
86       SanitizerBlacklist(
87           llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
88       SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
89                                           : LangOpts.Sanitize) {
90 
91   // Initialize the type cache.
92   llvm::LLVMContext &LLVMContext = M.getContext();
93   VoidTy = llvm::Type::getVoidTy(LLVMContext);
94   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
95   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
96   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
97   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
98   FloatTy = llvm::Type::getFloatTy(LLVMContext);
99   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
100   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
101   PointerAlignInBytes =
102   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
103   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
104   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
105   Int8PtrTy = Int8Ty->getPointerTo(0);
106   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
107 
108   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
109 
110   if (LangOpts.ObjC1)
111     createObjCRuntime();
112   if (LangOpts.OpenCL)
113     createOpenCLRuntime();
114   if (LangOpts.CUDA)
115     createCUDARuntime();
116 
117   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
118   if (SanOpts.Thread ||
119       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
120     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
121                            getCXXABI().getMangleContext());
122 
123   // If debug info or coverage generation is enabled, create the CGDebugInfo
124   // object.
125   if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
126       CodeGenOpts.EmitGcovArcs ||
127       CodeGenOpts.EmitGcovNotes)
128     DebugInfo = new CGDebugInfo(*this);
129 
130   Block.GlobalUniqueCount = 0;
131 
132   if (C.getLangOpts().ObjCAutoRefCount)
133     ARCData = new ARCEntrypoints();
134   RRData = new RREntrypoints();
135 
136   if (!CodeGenOpts.InstrProfileInput.empty())
137     PGOData = new PGOProfileData(*this, CodeGenOpts.InstrProfileInput);
138 }
139 
140 CodeGenModule::~CodeGenModule() {
141   delete ObjCRuntime;
142   delete OpenCLRuntime;
143   delete CUDARuntime;
144   delete TheTargetCodeGenInfo;
145   delete TBAA;
146   delete DebugInfo;
147   delete ARCData;
148   delete RRData;
149 }
150 
151 void CodeGenModule::createObjCRuntime() {
152   // This is just isGNUFamily(), but we want to force implementors of
153   // new ABIs to decide how best to do this.
154   switch (LangOpts.ObjCRuntime.getKind()) {
155   case ObjCRuntime::GNUstep:
156   case ObjCRuntime::GCC:
157   case ObjCRuntime::ObjFW:
158     ObjCRuntime = CreateGNUObjCRuntime(*this);
159     return;
160 
161   case ObjCRuntime::FragileMacOSX:
162   case ObjCRuntime::MacOSX:
163   case ObjCRuntime::iOS:
164     ObjCRuntime = CreateMacObjCRuntime(*this);
165     return;
166   }
167   llvm_unreachable("bad runtime kind");
168 }
169 
170 void CodeGenModule::createOpenCLRuntime() {
171   OpenCLRuntime = new CGOpenCLRuntime(*this);
172 }
173 
174 void CodeGenModule::createCUDARuntime() {
175   CUDARuntime = CreateNVCUDARuntime(*this);
176 }
177 
178 void CodeGenModule::applyReplacements() {
179   for (ReplacementsTy::iterator I = Replacements.begin(),
180                                 E = Replacements.end();
181        I != E; ++I) {
182     StringRef MangledName = I->first();
183     llvm::Constant *Replacement = I->second;
184     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
185     if (!Entry)
186       continue;
187     llvm::Function *OldF = cast<llvm::Function>(Entry);
188     llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement);
189     if (!NewF) {
190       if (llvm::GlobalAlias *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
191         NewF = dyn_cast<llvm::Function>(Alias->getAliasedGlobal());
192       } else {
193         llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement);
194         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
195                CE->getOpcode() == llvm::Instruction::GetElementPtr);
196         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
197       }
198     }
199 
200     // Replace old with new, but keep the old order.
201     OldF->replaceAllUsesWith(Replacement);
202     if (NewF) {
203       NewF->removeFromParent();
204       OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
205     }
206     OldF->eraseFromParent();
207   }
208 }
209 
210 void CodeGenModule::checkAliases() {
211   bool Error = false;
212   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
213          E = Aliases.end(); I != E; ++I) {
214     const GlobalDecl &GD = *I;
215     const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
216     const AliasAttr *AA = D->getAttr<AliasAttr>();
217     StringRef MangledName = getMangledName(GD);
218     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
219     llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
220     llvm::GlobalValue *GV = Alias->getAliasedGlobal();
221     if (GV->isDeclaration()) {
222       Error = true;
223       getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined);
224     } else if (!Alias->resolveAliasedGlobal(/*stopOnWeak*/ false)) {
225       Error = true;
226       getDiags().Report(AA->getLocation(), diag::err_cyclic_alias);
227     }
228   }
229   if (!Error)
230     return;
231 
232   for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
233          E = Aliases.end(); I != E; ++I) {
234     const GlobalDecl &GD = *I;
235     StringRef MangledName = getMangledName(GD);
236     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
237     llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
238     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
239     Alias->eraseFromParent();
240   }
241 }
242 
243 void CodeGenModule::clear() {
244   DeferredDeclsToEmit.clear();
245 }
246 
247 void CodeGenModule::Release() {
248   EmitDeferred();
249   applyReplacements();
250   checkAliases();
251   EmitCXXGlobalInitFunc();
252   EmitCXXGlobalDtorFunc();
253   EmitCXXThreadLocalInitFunc();
254   if (ObjCRuntime)
255     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
256       AddGlobalCtor(ObjCInitFunction);
257   EmitCtorList(GlobalCtors, "llvm.global_ctors");
258   EmitCtorList(GlobalDtors, "llvm.global_dtors");
259   EmitGlobalAnnotations();
260   EmitStaticExternCAliases();
261   emitLLVMUsed();
262 
263   if (CodeGenOpts.Autolink &&
264       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
265     EmitModuleLinkOptions();
266   }
267   if (CodeGenOpts.DwarfVersion)
268     // We actually want the latest version when there are conflicts.
269     // We can change from Warning to Latest if such mode is supported.
270     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
271                               CodeGenOpts.DwarfVersion);
272   if (DebugInfo)
273     // We support a single version in the linked module: error out when
274     // modules do not have the same version. We are going to implement dropping
275     // debug info when the version number is not up-to-date. Once that is
276     // done, the bitcode linker is not going to see modules with different
277     // version numbers.
278     getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version",
279                               llvm::DEBUG_METADATA_VERSION);
280 
281   SimplifyPersonality();
282 
283   if (getCodeGenOpts().EmitDeclMetadata)
284     EmitDeclMetadata();
285 
286   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
287     EmitCoverageFile();
288 
289   if (DebugInfo)
290     DebugInfo->finalize();
291 
292   EmitVersionIdentMetadata();
293 }
294 
295 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
296   // Make sure that this type is translated.
297   Types.UpdateCompletedType(TD);
298 }
299 
300 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
301   if (!TBAA)
302     return 0;
303   return TBAA->getTBAAInfo(QTy);
304 }
305 
306 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
307   if (!TBAA)
308     return 0;
309   return TBAA->getTBAAInfoForVTablePtr();
310 }
311 
312 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
313   if (!TBAA)
314     return 0;
315   return TBAA->getTBAAStructInfo(QTy);
316 }
317 
318 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
319   if (!TBAA)
320     return 0;
321   return TBAA->getTBAAStructTypeInfo(QTy);
322 }
323 
324 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
325                                                   llvm::MDNode *AccessN,
326                                                   uint64_t O) {
327   if (!TBAA)
328     return 0;
329   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
330 }
331 
332 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
333 /// and struct-path aware TBAA, the tag has the same format:
334 /// base type, access type and offset.
335 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
336 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
337                                         llvm::MDNode *TBAAInfo,
338                                         bool ConvertTypeToTag) {
339   if (ConvertTypeToTag && TBAA)
340     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
341                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
342   else
343     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
344 }
345 
346 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
347   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
348   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
349 }
350 
351 /// ErrorUnsupported - Print out an error that codegen doesn't support the
352 /// specified stmt yet.
353 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
354   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
355                                                "cannot compile this %0 yet");
356   std::string Msg = Type;
357   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
358     << Msg << S->getSourceRange();
359 }
360 
361 /// ErrorUnsupported - Print out an error that codegen doesn't support the
362 /// specified decl yet.
363 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
364   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
365                                                "cannot compile this %0 yet");
366   std::string Msg = Type;
367   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
368 }
369 
370 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
371   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
372 }
373 
374 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
375                                         const NamedDecl *D) const {
376   // Internal definitions always have default visibility.
377   if (GV->hasLocalLinkage()) {
378     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
379     return;
380   }
381 
382   // Set visibility for definitions.
383   LinkageInfo LV = D->getLinkageAndVisibility();
384   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
385     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
386 }
387 
388 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
389   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
390       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
391       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
392       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
393       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
394 }
395 
396 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
397     CodeGenOptions::TLSModel M) {
398   switch (M) {
399   case CodeGenOptions::GeneralDynamicTLSModel:
400     return llvm::GlobalVariable::GeneralDynamicTLSModel;
401   case CodeGenOptions::LocalDynamicTLSModel:
402     return llvm::GlobalVariable::LocalDynamicTLSModel;
403   case CodeGenOptions::InitialExecTLSModel:
404     return llvm::GlobalVariable::InitialExecTLSModel;
405   case CodeGenOptions::LocalExecTLSModel:
406     return llvm::GlobalVariable::LocalExecTLSModel;
407   }
408   llvm_unreachable("Invalid TLS model!");
409 }
410 
411 void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
412                                const VarDecl &D) const {
413   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
414 
415   llvm::GlobalVariable::ThreadLocalMode TLM;
416   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
417 
418   // Override the TLS model if it is explicitly specified.
419   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
420     TLM = GetLLVMTLSModel(Attr->getModel());
421   }
422 
423   GV->setThreadLocalMode(TLM);
424 }
425 
426 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
427   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
428 
429   StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
430   if (!Str.empty())
431     return Str;
432 
433   if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
434     IdentifierInfo *II = ND->getIdentifier();
435     assert(II && "Attempt to mangle unnamed decl.");
436 
437     Str = II->getName();
438     return Str;
439   }
440 
441   SmallString<256> Buffer;
442   llvm::raw_svector_ostream Out(Buffer);
443   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
444     getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
445   else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
446     getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
447   else
448     getCXXABI().getMangleContext().mangleName(ND, Out);
449 
450   // Allocate space for the mangled name.
451   Out.flush();
452   size_t Length = Buffer.size();
453   char *Name = MangledNamesAllocator.Allocate<char>(Length);
454   std::copy(Buffer.begin(), Buffer.end(), Name);
455 
456   Str = StringRef(Name, Length);
457 
458   return Str;
459 }
460 
461 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
462                                         const BlockDecl *BD) {
463   MangleContext &MangleCtx = getCXXABI().getMangleContext();
464   const Decl *D = GD.getDecl();
465   llvm::raw_svector_ostream Out(Buffer.getBuffer());
466   if (D == 0)
467     MangleCtx.mangleGlobalBlock(BD,
468       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
469   else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
470     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
471   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
472     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
473   else
474     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
475 }
476 
477 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
478   return getModule().getNamedValue(Name);
479 }
480 
481 /// AddGlobalCtor - Add a function to the list that will be called before
482 /// main() runs.
483 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
484   // FIXME: Type coercion of void()* types.
485   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
486 }
487 
488 /// AddGlobalDtor - Add a function to the list that will be called
489 /// when the module is unloaded.
490 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
491   // FIXME: Type coercion of void()* types.
492   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
493 }
494 
495 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
496   // Ctor function type is void()*.
497   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
498   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
499 
500   // Get the type of a ctor entry, { i32, void ()* }.
501   llvm::StructType *CtorStructTy =
502     llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
503 
504   // Construct the constructor and destructor arrays.
505   SmallVector<llvm::Constant*, 8> Ctors;
506   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
507     llvm::Constant *S[] = {
508       llvm::ConstantInt::get(Int32Ty, I->second, false),
509       llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
510     };
511     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
512   }
513 
514   if (!Ctors.empty()) {
515     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
516     new llvm::GlobalVariable(TheModule, AT, false,
517                              llvm::GlobalValue::AppendingLinkage,
518                              llvm::ConstantArray::get(AT, Ctors),
519                              GlobalName);
520   }
521 }
522 
523 llvm::GlobalValue::LinkageTypes
524 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
525   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
526 
527   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
528 
529   if (Linkage == GVA_Internal)
530     return llvm::Function::InternalLinkage;
531 
532   if (D->hasAttr<DLLExportAttr>())
533     return llvm::Function::ExternalLinkage;
534 
535   if (D->hasAttr<WeakAttr>())
536     return llvm::Function::WeakAnyLinkage;
537 
538   // In C99 mode, 'inline' functions are guaranteed to have a strong
539   // definition somewhere else, so we can use available_externally linkage.
540   if (Linkage == GVA_C99Inline)
541     return llvm::Function::AvailableExternallyLinkage;
542 
543   // Note that Apple's kernel linker doesn't support symbol
544   // coalescing, so we need to avoid linkonce and weak linkages there.
545   // Normally, this means we just map to internal, but for explicit
546   // instantiations we'll map to external.
547 
548   // In C++, the compiler has to emit a definition in every translation unit
549   // that references the function.  We should use linkonce_odr because
550   // a) if all references in this translation unit are optimized away, we
551   // don't need to codegen it.  b) if the function persists, it needs to be
552   // merged with other definitions. c) C++ has the ODR, so we know the
553   // definition is dependable.
554   if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
555     return !Context.getLangOpts().AppleKext
556              ? llvm::Function::LinkOnceODRLinkage
557              : llvm::Function::InternalLinkage;
558 
559   // An explicit instantiation of a template has weak linkage, since
560   // explicit instantiations can occur in multiple translation units
561   // and must all be equivalent. However, we are not allowed to
562   // throw away these explicit instantiations.
563   if (Linkage == GVA_ExplicitTemplateInstantiation)
564     return !Context.getLangOpts().AppleKext
565              ? llvm::Function::WeakODRLinkage
566              : llvm::Function::ExternalLinkage;
567 
568   // Destructor variants in the Microsoft C++ ABI are always linkonce_odr thunks
569   // emitted on an as-needed basis.
570   if (isa<CXXDestructorDecl>(D) &&
571       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
572                                          GD.getDtorType()))
573     return llvm::Function::LinkOnceODRLinkage;
574 
575   // Otherwise, we have strong external linkage.
576   assert(Linkage == GVA_StrongExternal);
577   return llvm::Function::ExternalLinkage;
578 }
579 
580 
581 /// SetFunctionDefinitionAttributes - Set attributes for a global.
582 ///
583 /// FIXME: This is currently only done for aliases and functions, but not for
584 /// variables (these details are set in EmitGlobalVarDefinition for variables).
585 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
586                                                     llvm::GlobalValue *GV) {
587   SetCommonAttributes(D, GV);
588 }
589 
590 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
591                                               const CGFunctionInfo &Info,
592                                               llvm::Function *F) {
593   unsigned CallingConv;
594   AttributeListType AttributeList;
595   ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
596   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
597   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
598 }
599 
600 /// Determines whether the language options require us to model
601 /// unwind exceptions.  We treat -fexceptions as mandating this
602 /// except under the fragile ObjC ABI with only ObjC exceptions
603 /// enabled.  This means, for example, that C with -fexceptions
604 /// enables this.
605 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
606   // If exceptions are completely disabled, obviously this is false.
607   if (!LangOpts.Exceptions) return false;
608 
609   // If C++ exceptions are enabled, this is true.
610   if (LangOpts.CXXExceptions) return true;
611 
612   // If ObjC exceptions are enabled, this depends on the ABI.
613   if (LangOpts.ObjCExceptions) {
614     return LangOpts.ObjCRuntime.hasUnwindExceptions();
615   }
616 
617   return true;
618 }
619 
620 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
621                                                            llvm::Function *F) {
622   llvm::AttrBuilder B;
623 
624   if (CodeGenOpts.UnwindTables)
625     B.addAttribute(llvm::Attribute::UWTable);
626 
627   if (!hasUnwindExceptions(LangOpts))
628     B.addAttribute(llvm::Attribute::NoUnwind);
629 
630   if (D->hasAttr<NakedAttr>()) {
631     // Naked implies noinline: we should not be inlining such functions.
632     B.addAttribute(llvm::Attribute::Naked);
633     B.addAttribute(llvm::Attribute::NoInline);
634   } else if (D->hasAttr<NoDuplicateAttr>()) {
635     B.addAttribute(llvm::Attribute::NoDuplicate);
636   } else if (D->hasAttr<NoInlineAttr>()) {
637     B.addAttribute(llvm::Attribute::NoInline);
638   } else if (D->hasAttr<AlwaysInlineAttr>() &&
639              !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
640                                               llvm::Attribute::NoInline)) {
641     // (noinline wins over always_inline, and we can't specify both in IR)
642     B.addAttribute(llvm::Attribute::AlwaysInline);
643   }
644 
645   if (D->hasAttr<ColdAttr>()) {
646     B.addAttribute(llvm::Attribute::OptimizeForSize);
647     B.addAttribute(llvm::Attribute::Cold);
648   }
649 
650   if (D->hasAttr<MinSizeAttr>())
651     B.addAttribute(llvm::Attribute::MinSize);
652 
653   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
654     B.addAttribute(llvm::Attribute::StackProtect);
655   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
656     B.addAttribute(llvm::Attribute::StackProtectStrong);
657   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
658     B.addAttribute(llvm::Attribute::StackProtectReq);
659 
660   // Add sanitizer attributes if function is not blacklisted.
661   if (!SanitizerBlacklist->isIn(*F)) {
662     // When AddressSanitizer is enabled, set SanitizeAddress attribute
663     // unless __attribute__((no_sanitize_address)) is used.
664     if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
665       B.addAttribute(llvm::Attribute::SanitizeAddress);
666     // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
667     if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
668       B.addAttribute(llvm::Attribute::SanitizeThread);
669     }
670     // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
671     if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
672       B.addAttribute(llvm::Attribute::SanitizeMemory);
673   }
674 
675   F->addAttributes(llvm::AttributeSet::FunctionIndex,
676                    llvm::AttributeSet::get(
677                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
678 
679   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
680     F->setUnnamedAddr(true);
681   else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
682     if (MD->isVirtual())
683       F->setUnnamedAddr(true);
684 
685   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
686   if (alignment)
687     F->setAlignment(alignment);
688 
689   // C++ ABI requires 2-byte alignment for member functions.
690   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
691     F->setAlignment(2);
692 }
693 
694 void CodeGenModule::SetCommonAttributes(const Decl *D,
695                                         llvm::GlobalValue *GV) {
696   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
697     setGlobalVisibility(GV, ND);
698   else
699     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
700 
701   if (D->hasAttr<UsedAttr>())
702     addUsedGlobal(GV);
703 
704   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
705     GV->setSection(SA->getName());
706 
707   // Alias cannot have attributes. Filter them here.
708   if (!isa<llvm::GlobalAlias>(GV))
709     getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
710 }
711 
712 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
713                                                   llvm::Function *F,
714                                                   const CGFunctionInfo &FI) {
715   SetLLVMFunctionAttributes(D, FI, F);
716   SetLLVMFunctionAttributesForDefinition(D, F);
717 
718   F->setLinkage(llvm::Function::InternalLinkage);
719 
720   SetCommonAttributes(D, F);
721 }
722 
723 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
724                                           llvm::Function *F,
725                                           bool IsIncompleteFunction) {
726   if (unsigned IID = F->getIntrinsicID()) {
727     // If this is an intrinsic function, set the function's attributes
728     // to the intrinsic's attributes.
729     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
730                                                     (llvm::Intrinsic::ID)IID));
731     return;
732   }
733 
734   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
735 
736   if (!IsIncompleteFunction)
737     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
738 
739   if (getCXXABI().HasThisReturn(GD)) {
740     assert(!F->arg_empty() &&
741            F->arg_begin()->getType()
742              ->canLosslesslyBitCastTo(F->getReturnType()) &&
743            "unexpected this return");
744     F->addAttribute(1, llvm::Attribute::Returned);
745   }
746 
747   // Only a few attributes are set on declarations; these may later be
748   // overridden by a definition.
749 
750   if (FD->hasAttr<DLLImportAttr>()) {
751     F->setLinkage(llvm::Function::ExternalLinkage);
752     F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
753   } else if (FD->hasAttr<WeakAttr>() ||
754              FD->isWeakImported()) {
755     // "extern_weak" is overloaded in LLVM; we probably should have
756     // separate linkage types for this.
757     F->setLinkage(llvm::Function::ExternalWeakLinkage);
758   } else {
759     F->setLinkage(llvm::Function::ExternalLinkage);
760     if (FD->hasAttr<DLLExportAttr>())
761       F->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
762 
763     LinkageInfo LV = FD->getLinkageAndVisibility();
764     if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
765       F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
766     }
767   }
768 
769   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
770     F->setSection(SA->getName());
771 
772   // A replaceable global allocation function does not act like a builtin by
773   // default, only if it is invoked by a new-expression or delete-expression.
774   if (FD->isReplaceableGlobalAllocationFunction())
775     F->addAttribute(llvm::AttributeSet::FunctionIndex,
776                     llvm::Attribute::NoBuiltin);
777 }
778 
779 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
780   assert(!GV->isDeclaration() &&
781          "Only globals with definition can force usage.");
782   LLVMUsed.push_back(GV);
783 }
784 
785 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
786   assert(!GV->isDeclaration() &&
787          "Only globals with definition can force usage.");
788   LLVMCompilerUsed.push_back(GV);
789 }
790 
791 static void emitUsed(CodeGenModule &CGM, StringRef Name,
792                      std::vector<llvm::WeakVH> &List) {
793   // Don't create llvm.used if there is no need.
794   if (List.empty())
795     return;
796 
797   // Convert List to what ConstantArray needs.
798   SmallVector<llvm::Constant*, 8> UsedArray;
799   UsedArray.resize(List.size());
800   for (unsigned i = 0, e = List.size(); i != e; ++i) {
801     UsedArray[i] =
802      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
803                                     CGM.Int8PtrTy);
804   }
805 
806   if (UsedArray.empty())
807     return;
808   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
809 
810   llvm::GlobalVariable *GV =
811     new llvm::GlobalVariable(CGM.getModule(), ATy, false,
812                              llvm::GlobalValue::AppendingLinkage,
813                              llvm::ConstantArray::get(ATy, UsedArray),
814                              Name);
815 
816   GV->setSection("llvm.metadata");
817 }
818 
819 void CodeGenModule::emitLLVMUsed() {
820   emitUsed(*this, "llvm.used", LLVMUsed);
821   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
822 }
823 
824 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
825   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
826   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
827 }
828 
829 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
830   llvm::SmallString<32> Opt;
831   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
832   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
833   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
834 }
835 
836 void CodeGenModule::AddDependentLib(StringRef Lib) {
837   llvm::SmallString<24> Opt;
838   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
839   llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
840   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
841 }
842 
843 /// \brief Add link options implied by the given module, including modules
844 /// it depends on, using a postorder walk.
845 static void addLinkOptionsPostorder(CodeGenModule &CGM,
846                                     Module *Mod,
847                                     SmallVectorImpl<llvm::Value *> &Metadata,
848                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
849   // Import this module's parent.
850   if (Mod->Parent && Visited.insert(Mod->Parent)) {
851     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
852   }
853 
854   // Import this module's dependencies.
855   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
856     if (Visited.insert(Mod->Imports[I-1]))
857       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
858   }
859 
860   // Add linker options to link against the libraries/frameworks
861   // described by this module.
862   llvm::LLVMContext &Context = CGM.getLLVMContext();
863   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
864     // Link against a framework.  Frameworks are currently Darwin only, so we
865     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
866     if (Mod->LinkLibraries[I-1].IsFramework) {
867       llvm::Value *Args[2] = {
868         llvm::MDString::get(Context, "-framework"),
869         llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
870       };
871 
872       Metadata.push_back(llvm::MDNode::get(Context, Args));
873       continue;
874     }
875 
876     // Link against a library.
877     llvm::SmallString<24> Opt;
878     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
879       Mod->LinkLibraries[I-1].Library, Opt);
880     llvm::Value *OptString = llvm::MDString::get(Context, Opt);
881     Metadata.push_back(llvm::MDNode::get(Context, OptString));
882   }
883 }
884 
885 void CodeGenModule::EmitModuleLinkOptions() {
886   // Collect the set of all of the modules we want to visit to emit link
887   // options, which is essentially the imported modules and all of their
888   // non-explicit child modules.
889   llvm::SetVector<clang::Module *> LinkModules;
890   llvm::SmallPtrSet<clang::Module *, 16> Visited;
891   SmallVector<clang::Module *, 16> Stack;
892 
893   // Seed the stack with imported modules.
894   for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
895                                                MEnd = ImportedModules.end();
896        M != MEnd; ++M) {
897     if (Visited.insert(*M))
898       Stack.push_back(*M);
899   }
900 
901   // Find all of the modules to import, making a little effort to prune
902   // non-leaf modules.
903   while (!Stack.empty()) {
904     clang::Module *Mod = Stack.pop_back_val();
905 
906     bool AnyChildren = false;
907 
908     // Visit the submodules of this module.
909     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
910                                         SubEnd = Mod->submodule_end();
911          Sub != SubEnd; ++Sub) {
912       // Skip explicit children; they need to be explicitly imported to be
913       // linked against.
914       if ((*Sub)->IsExplicit)
915         continue;
916 
917       if (Visited.insert(*Sub)) {
918         Stack.push_back(*Sub);
919         AnyChildren = true;
920       }
921     }
922 
923     // We didn't find any children, so add this module to the list of
924     // modules to link against.
925     if (!AnyChildren) {
926       LinkModules.insert(Mod);
927     }
928   }
929 
930   // Add link options for all of the imported modules in reverse topological
931   // order.  We don't do anything to try to order import link flags with respect
932   // to linker options inserted by things like #pragma comment().
933   SmallVector<llvm::Value *, 16> MetadataArgs;
934   Visited.clear();
935   for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
936                                                MEnd = LinkModules.end();
937        M != MEnd; ++M) {
938     if (Visited.insert(*M))
939       addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
940   }
941   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
942   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
943 
944   // Add the linker options metadata flag.
945   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
946                             llvm::MDNode::get(getLLVMContext(),
947                                               LinkerOptionsMetadata));
948 }
949 
950 void CodeGenModule::EmitDeferred() {
951   // Emit code for any potentially referenced deferred decls.  Since a
952   // previously unused static decl may become used during the generation of code
953   // for a static function, iterate until no changes are made.
954 
955   while (true) {
956     if (!DeferredVTables.empty()) {
957       EmitDeferredVTables();
958 
959       // Emitting a v-table doesn't directly cause more v-tables to
960       // become deferred, although it can cause functions to be
961       // emitted that then need those v-tables.
962       assert(DeferredVTables.empty());
963     }
964 
965     // Stop if we're out of both deferred v-tables and deferred declarations.
966     if (DeferredDeclsToEmit.empty()) break;
967 
968     DeferredGlobal &G = DeferredDeclsToEmit.back();
969     GlobalDecl D = G.GD;
970     llvm::GlobalValue *GV = G.GV;
971     DeferredDeclsToEmit.pop_back();
972 
973     assert(GV == GetGlobalValue(getMangledName(D)));
974     // Check to see if we've already emitted this.  This is necessary
975     // for a couple of reasons: first, decls can end up in the
976     // deferred-decls queue multiple times, and second, decls can end
977     // up with definitions in unusual ways (e.g. by an extern inline
978     // function acquiring a strong function redefinition).  Just
979     // ignore these cases.
980     if(!GV->isDeclaration())
981       continue;
982 
983     // Otherwise, emit the definition and move on to the next one.
984     EmitGlobalDefinition(D, GV);
985   }
986 }
987 
988 void CodeGenModule::EmitGlobalAnnotations() {
989   if (Annotations.empty())
990     return;
991 
992   // Create a new global variable for the ConstantStruct in the Module.
993   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
994     Annotations[0]->getType(), Annotations.size()), Annotations);
995   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
996     Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
997     "llvm.global.annotations");
998   gv->setSection(AnnotationSection);
999 }
1000 
1001 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1002   llvm::Constant *&AStr = AnnotationStrings[Str];
1003   if (AStr)
1004     return AStr;
1005 
1006   // Not found yet, create a new global.
1007   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1008   llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
1009     true, llvm::GlobalValue::PrivateLinkage, s, ".str");
1010   gv->setSection(AnnotationSection);
1011   gv->setUnnamedAddr(true);
1012   AStr = gv;
1013   return gv;
1014 }
1015 
1016 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1017   SourceManager &SM = getContext().getSourceManager();
1018   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1019   if (PLoc.isValid())
1020     return EmitAnnotationString(PLoc.getFilename());
1021   return EmitAnnotationString(SM.getBufferName(Loc));
1022 }
1023 
1024 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1025   SourceManager &SM = getContext().getSourceManager();
1026   PresumedLoc PLoc = SM.getPresumedLoc(L);
1027   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1028     SM.getExpansionLineNumber(L);
1029   return llvm::ConstantInt::get(Int32Ty, LineNo);
1030 }
1031 
1032 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1033                                                 const AnnotateAttr *AA,
1034                                                 SourceLocation L) {
1035   // Get the globals for file name, annotation, and the line number.
1036   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1037                  *UnitGV = EmitAnnotationUnit(L),
1038                  *LineNoCst = EmitAnnotationLineNo(L);
1039 
1040   // Create the ConstantStruct for the global annotation.
1041   llvm::Constant *Fields[4] = {
1042     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1043     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1044     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1045     LineNoCst
1046   };
1047   return llvm::ConstantStruct::getAnon(Fields);
1048 }
1049 
1050 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1051                                          llvm::GlobalValue *GV) {
1052   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1053   // Get the struct elements for these annotations.
1054   for (specific_attr_iterator<AnnotateAttr>
1055        ai = D->specific_attr_begin<AnnotateAttr>(),
1056        ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
1057     Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
1058 }
1059 
1060 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
1061   // Never defer when EmitAllDecls is specified.
1062   if (LangOpts.EmitAllDecls)
1063     return false;
1064 
1065   return !getContext().DeclMustBeEmitted(Global);
1066 }
1067 
1068 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1069     const CXXUuidofExpr* E) {
1070   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1071   // well-formed.
1072   StringRef Uuid = E->getUuidAsStringRef(Context);
1073   std::string Name = "_GUID_" + Uuid.lower();
1074   std::replace(Name.begin(), Name.end(), '-', '_');
1075 
1076   // Look for an existing global.
1077   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1078     return GV;
1079 
1080   llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1081   assert(Init && "failed to initialize as constant");
1082 
1083   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1084       getModule(), Init->getType(),
1085       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1086   return GV;
1087 }
1088 
1089 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1090   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1091   assert(AA && "No alias?");
1092 
1093   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1094 
1095   // See if there is already something with the target's name in the module.
1096   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1097   if (Entry) {
1098     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1099     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1100   }
1101 
1102   llvm::Constant *Aliasee;
1103   if (isa<llvm::FunctionType>(DeclTy))
1104     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1105                                       GlobalDecl(cast<FunctionDecl>(VD)),
1106                                       /*ForVTable=*/false);
1107   else
1108     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1109                                     llvm::PointerType::getUnqual(DeclTy), 0);
1110 
1111   llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1112   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1113   WeakRefReferences.insert(F);
1114 
1115   return Aliasee;
1116 }
1117 
1118 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1119   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
1120 
1121   // Weak references don't produce any output by themselves.
1122   if (Global->hasAttr<WeakRefAttr>())
1123     return;
1124 
1125   // If this is an alias definition (which otherwise looks like a declaration)
1126   // emit it now.
1127   if (Global->hasAttr<AliasAttr>())
1128     return EmitAliasDefinition(GD);
1129 
1130   // If this is CUDA, be selective about which declarations we emit.
1131   if (LangOpts.CUDA) {
1132     if (CodeGenOpts.CUDAIsDevice) {
1133       if (!Global->hasAttr<CUDADeviceAttr>() &&
1134           !Global->hasAttr<CUDAGlobalAttr>() &&
1135           !Global->hasAttr<CUDAConstantAttr>() &&
1136           !Global->hasAttr<CUDASharedAttr>())
1137         return;
1138     } else {
1139       if (!Global->hasAttr<CUDAHostAttr>() && (
1140             Global->hasAttr<CUDADeviceAttr>() ||
1141             Global->hasAttr<CUDAConstantAttr>() ||
1142             Global->hasAttr<CUDASharedAttr>()))
1143         return;
1144     }
1145   }
1146 
1147   // Ignore declarations, they will be emitted on their first use.
1148   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
1149     // Forward declarations are emitted lazily on first use.
1150     if (!FD->doesThisDeclarationHaveABody()) {
1151       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1152         return;
1153 
1154       const FunctionDecl *InlineDefinition = 0;
1155       FD->getBody(InlineDefinition);
1156 
1157       StringRef MangledName = getMangledName(GD);
1158       DeferredDecls.erase(MangledName);
1159       EmitGlobalDefinition(InlineDefinition);
1160       return;
1161     }
1162   } else {
1163     const VarDecl *VD = cast<VarDecl>(Global);
1164     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1165 
1166     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
1167       return;
1168   }
1169 
1170   // Defer code generation when possible if this is a static definition, inline
1171   // function etc.  These we only want to emit if they are used.
1172   if (!MayDeferGeneration(Global)) {
1173     // Emit the definition if it can't be deferred.
1174     EmitGlobalDefinition(GD);
1175     return;
1176   }
1177 
1178   // If we're deferring emission of a C++ variable with an
1179   // initializer, remember the order in which it appeared in the file.
1180   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1181       cast<VarDecl>(Global)->hasInit()) {
1182     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1183     CXXGlobalInits.push_back(0);
1184   }
1185 
1186   // If the value has already been used, add it directly to the
1187   // DeferredDeclsToEmit list.
1188   StringRef MangledName = getMangledName(GD);
1189   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
1190     addDeferredDeclToEmit(GV, GD);
1191   else {
1192     // Otherwise, remember that we saw a deferred decl with this name.  The
1193     // first use of the mangled name will cause it to move into
1194     // DeferredDeclsToEmit.
1195     DeferredDecls[MangledName] = GD;
1196   }
1197 }
1198 
1199 namespace {
1200   struct FunctionIsDirectlyRecursive :
1201     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1202     const StringRef Name;
1203     const Builtin::Context &BI;
1204     bool Result;
1205     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1206       Name(N), BI(C), Result(false) {
1207     }
1208     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1209 
1210     bool TraverseCallExpr(CallExpr *E) {
1211       const FunctionDecl *FD = E->getDirectCallee();
1212       if (!FD)
1213         return true;
1214       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1215       if (Attr && Name == Attr->getLabel()) {
1216         Result = true;
1217         return false;
1218       }
1219       unsigned BuiltinID = FD->getBuiltinID();
1220       if (!BuiltinID)
1221         return true;
1222       StringRef BuiltinName = BI.GetName(BuiltinID);
1223       if (BuiltinName.startswith("__builtin_") &&
1224           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1225         Result = true;
1226         return false;
1227       }
1228       return true;
1229     }
1230   };
1231 }
1232 
1233 // isTriviallyRecursive - Check if this function calls another
1234 // decl that, because of the asm attribute or the other decl being a builtin,
1235 // ends up pointing to itself.
1236 bool
1237 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1238   StringRef Name;
1239   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1240     // asm labels are a special kind of mangling we have to support.
1241     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1242     if (!Attr)
1243       return false;
1244     Name = Attr->getLabel();
1245   } else {
1246     Name = FD->getName();
1247   }
1248 
1249   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1250   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1251   return Walker.Result;
1252 }
1253 
1254 bool
1255 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1256   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1257     return true;
1258   const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
1259   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1260     return false;
1261   // PR9614. Avoid cases where the source code is lying to us. An available
1262   // externally function should have an equivalent function somewhere else,
1263   // but a function that calls itself is clearly not equivalent to the real
1264   // implementation.
1265   // This happens in glibc's btowc and in some configure checks.
1266   return !isTriviallyRecursive(F);
1267 }
1268 
1269 /// If the type for the method's class was generated by
1270 /// CGDebugInfo::createContextChain(), the cache contains only a
1271 /// limited DIType without any declarations. Since EmitFunctionStart()
1272 /// needs to find the canonical declaration for each method, we need
1273 /// to construct the complete type prior to emitting the method.
1274 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1275   if (!D->isInstance())
1276     return;
1277 
1278   if (CGDebugInfo *DI = getModuleDebugInfo())
1279     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1280       const PointerType *ThisPtr =
1281         cast<PointerType>(D->getThisType(getContext()));
1282       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1283     }
1284 }
1285 
1286 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1287   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1288 
1289   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1290                                  Context.getSourceManager(),
1291                                  "Generating code for declaration");
1292 
1293   if (isa<FunctionDecl>(D)) {
1294     // At -O0, don't generate IR for functions with available_externally
1295     // linkage.
1296     if (!shouldEmitFunction(GD))
1297       return;
1298 
1299     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1300       CompleteDIClassType(Method);
1301       // Make sure to emit the definition(s) before we emit the thunks.
1302       // This is necessary for the generation of certain thunks.
1303       if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1304         EmitCXXConstructor(CD, GD.getCtorType());
1305       else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1306         EmitCXXDestructor(DD, GD.getDtorType());
1307       else
1308         EmitGlobalFunctionDefinition(GD, GV);
1309 
1310       if (Method->isVirtual())
1311         getVTables().EmitThunks(GD);
1312 
1313       return;
1314     }
1315 
1316     return EmitGlobalFunctionDefinition(GD, GV);
1317   }
1318 
1319   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1320     return EmitGlobalVarDefinition(VD);
1321 
1322   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1323 }
1324 
1325 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1326 /// module, create and return an llvm Function with the specified type. If there
1327 /// is something in the module with the specified name, return it potentially
1328 /// bitcasted to the right type.
1329 ///
1330 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1331 /// to set the attributes on the function when it is first created.
1332 llvm::Constant *
1333 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1334                                        llvm::Type *Ty,
1335                                        GlobalDecl GD, bool ForVTable,
1336                                        bool DontDefer,
1337                                        llvm::AttributeSet ExtraAttrs) {
1338   const Decl *D = GD.getDecl();
1339 
1340   // Lookup the entry, lazily creating it if necessary.
1341   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1342   if (Entry) {
1343     if (WeakRefReferences.erase(Entry)) {
1344       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1345       if (FD && !FD->hasAttr<WeakAttr>())
1346         Entry->setLinkage(llvm::Function::ExternalLinkage);
1347     }
1348 
1349     if (Entry->getType()->getElementType() == Ty)
1350       return Entry;
1351 
1352     // Make sure the result is of the correct type.
1353     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1354   }
1355 
1356   // This function doesn't have a complete type (for example, the return
1357   // type is an incomplete struct). Use a fake type instead, and make
1358   // sure not to try to set attributes.
1359   bool IsIncompleteFunction = false;
1360 
1361   llvm::FunctionType *FTy;
1362   if (isa<llvm::FunctionType>(Ty)) {
1363     FTy = cast<llvm::FunctionType>(Ty);
1364   } else {
1365     FTy = llvm::FunctionType::get(VoidTy, false);
1366     IsIncompleteFunction = true;
1367   }
1368 
1369   llvm::Function *F = llvm::Function::Create(FTy,
1370                                              llvm::Function::ExternalLinkage,
1371                                              MangledName, &getModule());
1372   assert(F->getName() == MangledName && "name was uniqued!");
1373   if (D)
1374     SetFunctionAttributes(GD, F, IsIncompleteFunction);
1375   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1376     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1377     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1378                      llvm::AttributeSet::get(VMContext,
1379                                              llvm::AttributeSet::FunctionIndex,
1380                                              B));
1381   }
1382 
1383   if (!DontDefer) {
1384     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1385     // each other bottoming out with the base dtor.  Therefore we emit non-base
1386     // dtors on usage, even if there is no dtor definition in the TU.
1387     if (D && isa<CXXDestructorDecl>(D) &&
1388         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1389                                            GD.getDtorType()))
1390       addDeferredDeclToEmit(F, GD);
1391 
1392     // This is the first use or definition of a mangled name.  If there is a
1393     // deferred decl with this name, remember that we need to emit it at the end
1394     // of the file.
1395     llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1396     if (DDI != DeferredDecls.end()) {
1397       // Move the potentially referenced deferred decl to the
1398       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1399       // don't need it anymore).
1400       addDeferredDeclToEmit(F, DDI->second);
1401       DeferredDecls.erase(DDI);
1402 
1403       // Otherwise, if this is a sized deallocation function, emit a weak
1404       // definition
1405       // for it at the end of the translation unit.
1406     } else if (D && cast<FunctionDecl>(D)
1407                         ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
1408       addDeferredDeclToEmit(F, GD);
1409 
1410       // Otherwise, there are cases we have to worry about where we're
1411       // using a declaration for which we must emit a definition but where
1412       // we might not find a top-level definition:
1413       //   - member functions defined inline in their classes
1414       //   - friend functions defined inline in some class
1415       //   - special member functions with implicit definitions
1416       // If we ever change our AST traversal to walk into class methods,
1417       // this will be unnecessary.
1418       //
1419       // We also don't emit a definition for a function if it's going to be an
1420       // entry
1421       // in a vtable, unless it's already marked as used.
1422     } else if (getLangOpts().CPlusPlus && D) {
1423       // Look for a declaration that's lexically in a record.
1424       const FunctionDecl *FD = cast<FunctionDecl>(D);
1425       FD = FD->getMostRecentDecl();
1426       do {
1427         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1428           if (FD->isImplicit() && !ForVTable) {
1429             assert(FD->isUsed() &&
1430                    "Sema didn't mark implicit function as used!");
1431             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1432             break;
1433           } else if (FD->doesThisDeclarationHaveABody()) {
1434             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1435             break;
1436           }
1437         }
1438         FD = FD->getPreviousDecl();
1439       } while (FD);
1440     }
1441   }
1442 
1443   // Make sure the result is of the requested type.
1444   if (!IsIncompleteFunction) {
1445     assert(F->getType()->getElementType() == Ty);
1446     return F;
1447   }
1448 
1449   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1450   return llvm::ConstantExpr::getBitCast(F, PTy);
1451 }
1452 
1453 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1454 /// non-null, then this function will use the specified type if it has to
1455 /// create it (this occurs when we see a definition of the function).
1456 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1457                                                  llvm::Type *Ty,
1458                                                  bool ForVTable,
1459                                                  bool DontDefer) {
1460   // If there was no specific requested type, just convert it now.
1461   if (!Ty)
1462     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1463 
1464   StringRef MangledName = getMangledName(GD);
1465   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
1466 }
1467 
1468 /// CreateRuntimeFunction - Create a new runtime function with the specified
1469 /// type and name.
1470 llvm::Constant *
1471 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1472                                      StringRef Name,
1473                                      llvm::AttributeSet ExtraAttrs) {
1474   llvm::Constant *C =
1475       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1476                               /*DontDefer=*/false, ExtraAttrs);
1477   if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1478     if (F->empty())
1479       F->setCallingConv(getRuntimeCC());
1480   return C;
1481 }
1482 
1483 /// isTypeConstant - Determine whether an object of this type can be emitted
1484 /// as a constant.
1485 ///
1486 /// If ExcludeCtor is true, the duration when the object's constructor runs
1487 /// will not be considered. The caller will need to verify that the object is
1488 /// not written to during its construction.
1489 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1490   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1491     return false;
1492 
1493   if (Context.getLangOpts().CPlusPlus) {
1494     if (const CXXRecordDecl *Record
1495           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1496       return ExcludeCtor && !Record->hasMutableFields() &&
1497              Record->hasTrivialDestructor();
1498   }
1499 
1500   return true;
1501 }
1502 
1503 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1504 /// create and return an llvm GlobalVariable with the specified type.  If there
1505 /// is something in the module with the specified name, return it potentially
1506 /// bitcasted to the right type.
1507 ///
1508 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1509 /// to set the attributes on the global when it is first created.
1510 llvm::Constant *
1511 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1512                                      llvm::PointerType *Ty,
1513                                      const VarDecl *D,
1514                                      bool UnnamedAddr) {
1515   // Lookup the entry, lazily creating it if necessary.
1516   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1517   if (Entry) {
1518     if (WeakRefReferences.erase(Entry)) {
1519       if (D && !D->hasAttr<WeakAttr>())
1520         Entry->setLinkage(llvm::Function::ExternalLinkage);
1521     }
1522 
1523     if (UnnamedAddr)
1524       Entry->setUnnamedAddr(true);
1525 
1526     if (Entry->getType() == Ty)
1527       return Entry;
1528 
1529     // Make sure the result is of the correct type.
1530     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1531       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1532 
1533     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1534   }
1535 
1536   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1537   llvm::GlobalVariable *GV =
1538     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1539                              llvm::GlobalValue::ExternalLinkage,
1540                              0, MangledName, 0,
1541                              llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1542 
1543   // This is the first use or definition of a mangled name.  If there is a
1544   // deferred decl with this name, remember that we need to emit it at the end
1545   // of the file.
1546   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1547   if (DDI != DeferredDecls.end()) {
1548     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1549     // list, and remove it from DeferredDecls (since we don't need it anymore).
1550     addDeferredDeclToEmit(GV, DDI->second);
1551     DeferredDecls.erase(DDI);
1552   }
1553 
1554   // Handle things which are present even on external declarations.
1555   if (D) {
1556     // FIXME: This code is overly simple and should be merged with other global
1557     // handling.
1558     GV->setConstant(isTypeConstant(D->getType(), false));
1559 
1560     // Set linkage and visibility in case we never see a definition.
1561     LinkageInfo LV = D->getLinkageAndVisibility();
1562     if (LV.getLinkage() != ExternalLinkage) {
1563       // Don't set internal linkage on declarations.
1564     } else {
1565       if (D->hasAttr<DLLImportAttr>()) {
1566         GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1567         GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1568       } else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
1569         GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1570 
1571       // Set visibility on a declaration only if it's explicit.
1572       if (LV.isVisibilityExplicit())
1573         GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
1574     }
1575 
1576     if (D->getTLSKind()) {
1577       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1578         CXXThreadLocals.push_back(std::make_pair(D, GV));
1579       setTLSMode(GV, *D);
1580     }
1581 
1582     // If required by the ABI, treat declarations of static data members with
1583     // inline initializers as definitions.
1584     if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1585         D->isStaticDataMember() && D->hasInit() &&
1586         !D->isThisDeclarationADefinition())
1587       EmitGlobalVarDefinition(D);
1588   }
1589 
1590   if (AddrSpace != Ty->getAddressSpace())
1591     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1592 
1593   if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1594       D->getLanguageLinkage() == CLanguageLinkage &&
1595       D->getType().isConstant(Context) &&
1596       isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1597     GV->setSection(".cp.rodata");
1598 
1599   return GV;
1600 }
1601 
1602 
1603 llvm::GlobalVariable *
1604 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1605                                       llvm::Type *Ty,
1606                                       llvm::GlobalValue::LinkageTypes Linkage) {
1607   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1608   llvm::GlobalVariable *OldGV = 0;
1609 
1610 
1611   if (GV) {
1612     // Check if the variable has the right type.
1613     if (GV->getType()->getElementType() == Ty)
1614       return GV;
1615 
1616     // Because C++ name mangling, the only way we can end up with an already
1617     // existing global with the same name is if it has been declared extern "C".
1618     assert(GV->isDeclaration() && "Declaration has wrong type!");
1619     OldGV = GV;
1620   }
1621 
1622   // Create a new variable.
1623   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1624                                 Linkage, 0, Name);
1625 
1626   if (OldGV) {
1627     // Replace occurrences of the old variable if needed.
1628     GV->takeName(OldGV);
1629 
1630     if (!OldGV->use_empty()) {
1631       llvm::Constant *NewPtrForOldDecl =
1632       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1633       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1634     }
1635 
1636     OldGV->eraseFromParent();
1637   }
1638 
1639   return GV;
1640 }
1641 
1642 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1643 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1644 /// then it will be created with the specified type instead of whatever the
1645 /// normal requested type would be.
1646 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1647                                                   llvm::Type *Ty) {
1648   assert(D->hasGlobalStorage() && "Not a global variable");
1649   QualType ASTTy = D->getType();
1650   if (Ty == 0)
1651     Ty = getTypes().ConvertTypeForMem(ASTTy);
1652 
1653   llvm::PointerType *PTy =
1654     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1655 
1656   StringRef MangledName = getMangledName(D);
1657   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1658 }
1659 
1660 /// CreateRuntimeVariable - Create a new runtime global variable with the
1661 /// specified type and name.
1662 llvm::Constant *
1663 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1664                                      StringRef Name) {
1665   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1666                                true);
1667 }
1668 
1669 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1670   assert(!D->getInit() && "Cannot emit definite definitions here!");
1671 
1672   if (MayDeferGeneration(D)) {
1673     // If we have not seen a reference to this variable yet, place it
1674     // into the deferred declarations table to be emitted if needed
1675     // later.
1676     StringRef MangledName = getMangledName(D);
1677     if (!GetGlobalValue(MangledName)) {
1678       DeferredDecls[MangledName] = D;
1679       return;
1680     }
1681   }
1682 
1683   // The tentative definition is the only definition.
1684   EmitGlobalVarDefinition(D);
1685 }
1686 
1687 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1688     return Context.toCharUnitsFromBits(
1689       TheDataLayout.getTypeStoreSizeInBits(Ty));
1690 }
1691 
1692 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1693                                                  unsigned AddrSpace) {
1694   if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1695     if (D->hasAttr<CUDAConstantAttr>())
1696       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1697     else if (D->hasAttr<CUDASharedAttr>())
1698       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1699     else
1700       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1701   }
1702 
1703   return AddrSpace;
1704 }
1705 
1706 template<typename SomeDecl>
1707 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1708                                                llvm::GlobalValue *GV) {
1709   if (!getLangOpts().CPlusPlus)
1710     return;
1711 
1712   // Must have 'used' attribute, or else inline assembly can't rely on
1713   // the name existing.
1714   if (!D->template hasAttr<UsedAttr>())
1715     return;
1716 
1717   // Must have internal linkage and an ordinary name.
1718   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1719     return;
1720 
1721   // Must be in an extern "C" context. Entities declared directly within
1722   // a record are not extern "C" even if the record is in such a context.
1723   const SomeDecl *First = D->getFirstDecl();
1724   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1725     return;
1726 
1727   // OK, this is an internal linkage entity inside an extern "C" linkage
1728   // specification. Make a note of that so we can give it the "expected"
1729   // mangled name if nothing else is using that name.
1730   std::pair<StaticExternCMap::iterator, bool> R =
1731       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1732 
1733   // If we have multiple internal linkage entities with the same name
1734   // in extern "C" regions, none of them gets that name.
1735   if (!R.second)
1736     R.first->second = 0;
1737 }
1738 
1739 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1740   llvm::Constant *Init = 0;
1741   QualType ASTTy = D->getType();
1742   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1743   bool NeedsGlobalCtor = false;
1744   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1745 
1746   const VarDecl *InitDecl;
1747   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1748 
1749   if (!InitExpr) {
1750     // This is a tentative definition; tentative definitions are
1751     // implicitly initialized with { 0 }.
1752     //
1753     // Note that tentative definitions are only emitted at the end of
1754     // a translation unit, so they should never have incomplete
1755     // type. In addition, EmitTentativeDefinition makes sure that we
1756     // never attempt to emit a tentative definition if a real one
1757     // exists. A use may still exists, however, so we still may need
1758     // to do a RAUW.
1759     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1760     Init = EmitNullConstant(D->getType());
1761   } else {
1762     initializedGlobalDecl = GlobalDecl(D);
1763     Init = EmitConstantInit(*InitDecl);
1764 
1765     if (!Init) {
1766       QualType T = InitExpr->getType();
1767       if (D->getType()->isReferenceType())
1768         T = D->getType();
1769 
1770       if (getLangOpts().CPlusPlus) {
1771         Init = EmitNullConstant(T);
1772         NeedsGlobalCtor = true;
1773       } else {
1774         ErrorUnsupported(D, "static initializer");
1775         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1776       }
1777     } else {
1778       // We don't need an initializer, so remove the entry for the delayed
1779       // initializer position (just in case this entry was delayed) if we
1780       // also don't need to register a destructor.
1781       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
1782         DelayedCXXInitPosition.erase(D);
1783     }
1784   }
1785 
1786   llvm::Type* InitType = Init->getType();
1787   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1788 
1789   // Strip off a bitcast if we got one back.
1790   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1791     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1792            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1793            // All zero index gep.
1794            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1795     Entry = CE->getOperand(0);
1796   }
1797 
1798   // Entry is now either a Function or GlobalVariable.
1799   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1800 
1801   // We have a definition after a declaration with the wrong type.
1802   // We must make a new GlobalVariable* and update everything that used OldGV
1803   // (a declaration or tentative definition) with the new GlobalVariable*
1804   // (which will be a definition).
1805   //
1806   // This happens if there is a prototype for a global (e.g.
1807   // "extern int x[];") and then a definition of a different type (e.g.
1808   // "int x[10];"). This also happens when an initializer has a different type
1809   // from the type of the global (this happens with unions).
1810   if (GV == 0 ||
1811       GV->getType()->getElementType() != InitType ||
1812       GV->getType()->getAddressSpace() !=
1813        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
1814 
1815     // Move the old entry aside so that we'll create a new one.
1816     Entry->setName(StringRef());
1817 
1818     // Make a new global with the correct type, this is now guaranteed to work.
1819     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1820 
1821     // Replace all uses of the old global with the new global
1822     llvm::Constant *NewPtrForOldDecl =
1823         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1824     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1825 
1826     // Erase the old global, since it is no longer used.
1827     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1828   }
1829 
1830   MaybeHandleStaticInExternC(D, GV);
1831 
1832   if (D->hasAttr<AnnotateAttr>())
1833     AddGlobalAnnotations(D, GV);
1834 
1835   GV->setInitializer(Init);
1836 
1837   // If it is safe to mark the global 'constant', do so now.
1838   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1839                   isTypeConstant(D->getType(), true));
1840 
1841   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1842 
1843   // Set the llvm linkage type as appropriate.
1844   llvm::GlobalValue::LinkageTypes Linkage =
1845     GetLLVMLinkageVarDefinition(D, GV->isConstant());
1846   GV->setLinkage(Linkage);
1847   if (D->hasAttr<DLLImportAttr>())
1848     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1849   else if (D->hasAttr<DLLExportAttr>())
1850     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1851 
1852   // If required by the ABI, give definitions of static data members with inline
1853   // initializers linkonce_odr linkage.
1854   if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1855       D->isStaticDataMember() && InitExpr &&
1856       !InitDecl->isThisDeclarationADefinition())
1857     GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage);
1858 
1859   if (Linkage == llvm::GlobalVariable::CommonLinkage)
1860     // common vars aren't constant even if declared const.
1861     GV->setConstant(false);
1862 
1863   SetCommonAttributes(D, GV);
1864 
1865   // Emit the initializer function if necessary.
1866   if (NeedsGlobalCtor || NeedsGlobalDtor)
1867     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
1868 
1869   // If we are compiling with ASan, add metadata indicating dynamically
1870   // initialized globals.
1871   if (SanOpts.Address && NeedsGlobalCtor) {
1872     llvm::Module &M = getModule();
1873 
1874     llvm::NamedMDNode *DynamicInitializers =
1875         M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1876     llvm::Value *GlobalToAdd[] = { GV };
1877     llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1878     DynamicInitializers->addOperand(ThisGlobal);
1879   }
1880 
1881   // Emit global variable debug information.
1882   if (CGDebugInfo *DI = getModuleDebugInfo())
1883     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
1884       DI->EmitGlobalVariable(GV, D);
1885 }
1886 
1887 llvm::GlobalValue::LinkageTypes
1888 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
1889   GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1890   if (Linkage == GVA_Internal)
1891     return llvm::Function::InternalLinkage;
1892   else if (D->hasAttr<DLLImportAttr>())
1893     return llvm::Function::ExternalLinkage;
1894   else if (D->hasAttr<DLLExportAttr>())
1895     return llvm::Function::ExternalLinkage;
1896   else if (D->hasAttr<SelectAnyAttr>()) {
1897     // selectany symbols are externally visible, so use weak instead of
1898     // linkonce.  MSVC optimizes away references to const selectany globals, so
1899     // all definitions should be the same and ODR linkage should be used.
1900     // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1901     return llvm::GlobalVariable::WeakODRLinkage;
1902   } else if (D->hasAttr<WeakAttr>()) {
1903     if (isConstant)
1904       return llvm::GlobalVariable::WeakODRLinkage;
1905     else
1906       return llvm::GlobalVariable::WeakAnyLinkage;
1907   } else if (Linkage == GVA_TemplateInstantiation ||
1908              Linkage == GVA_ExplicitTemplateInstantiation)
1909     return llvm::GlobalVariable::WeakODRLinkage;
1910   else if (!getLangOpts().CPlusPlus &&
1911            ((!CodeGenOpts.NoCommon && !D->hasAttr<NoCommonAttr>()) ||
1912              D->hasAttr<CommonAttr>()) &&
1913            !D->hasExternalStorage() && !D->getInit() &&
1914            !D->hasAttr<SectionAttr>() && !D->getTLSKind() &&
1915            !D->hasAttr<WeakImportAttr>()) {
1916     // Thread local vars aren't considered common linkage.
1917     return llvm::GlobalVariable::CommonLinkage;
1918   } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1919              getTarget().getTriple().isMacOSX())
1920     // On Darwin, the backing variable for a C++11 thread_local variable always
1921     // has internal linkage; all accesses should just be calls to the
1922     // Itanium-specified entry point, which has the normal linkage of the
1923     // variable.
1924     return llvm::GlobalValue::InternalLinkage;
1925   return llvm::GlobalVariable::ExternalLinkage;
1926 }
1927 
1928 /// Replace the uses of a function that was declared with a non-proto type.
1929 /// We want to silently drop extra arguments from call sites
1930 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1931                                           llvm::Function *newFn) {
1932   // Fast path.
1933   if (old->use_empty()) return;
1934 
1935   llvm::Type *newRetTy = newFn->getReturnType();
1936   SmallVector<llvm::Value*, 4> newArgs;
1937 
1938   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1939          ui != ue; ) {
1940     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1941     llvm::User *user = *use;
1942 
1943     // Recognize and replace uses of bitcasts.  Most calls to
1944     // unprototyped functions will use bitcasts.
1945     if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1946       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1947         replaceUsesOfNonProtoConstant(bitcast, newFn);
1948       continue;
1949     }
1950 
1951     // Recognize calls to the function.
1952     llvm::CallSite callSite(user);
1953     if (!callSite) continue;
1954     if (!callSite.isCallee(use)) continue;
1955 
1956     // If the return types don't match exactly, then we can't
1957     // transform this call unless it's dead.
1958     if (callSite->getType() != newRetTy && !callSite->use_empty())
1959       continue;
1960 
1961     // Get the call site's attribute list.
1962     SmallVector<llvm::AttributeSet, 8> newAttrs;
1963     llvm::AttributeSet oldAttrs = callSite.getAttributes();
1964 
1965     // Collect any return attributes from the call.
1966     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
1967       newAttrs.push_back(
1968         llvm::AttributeSet::get(newFn->getContext(),
1969                                 oldAttrs.getRetAttributes()));
1970 
1971     // If the function was passed too few arguments, don't transform.
1972     unsigned newNumArgs = newFn->arg_size();
1973     if (callSite.arg_size() < newNumArgs) continue;
1974 
1975     // If extra arguments were passed, we silently drop them.
1976     // If any of the types mismatch, we don't transform.
1977     unsigned argNo = 0;
1978     bool dontTransform = false;
1979     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1980            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1981       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1982         dontTransform = true;
1983         break;
1984       }
1985 
1986       // Add any parameter attributes.
1987       if (oldAttrs.hasAttributes(argNo + 1))
1988         newAttrs.
1989           push_back(llvm::
1990                     AttributeSet::get(newFn->getContext(),
1991                                       oldAttrs.getParamAttributes(argNo + 1)));
1992     }
1993     if (dontTransform)
1994       continue;
1995 
1996     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
1997       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1998                                                  oldAttrs.getFnAttributes()));
1999 
2000     // Okay, we can transform this.  Create the new call instruction and copy
2001     // over the required information.
2002     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2003 
2004     llvm::CallSite newCall;
2005     if (callSite.isCall()) {
2006       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2007                                        callSite.getInstruction());
2008     } else {
2009       llvm::InvokeInst *oldInvoke =
2010         cast<llvm::InvokeInst>(callSite.getInstruction());
2011       newCall = llvm::InvokeInst::Create(newFn,
2012                                          oldInvoke->getNormalDest(),
2013                                          oldInvoke->getUnwindDest(),
2014                                          newArgs, "",
2015                                          callSite.getInstruction());
2016     }
2017     newArgs.clear(); // for the next iteration
2018 
2019     if (!newCall->getType()->isVoidTy())
2020       newCall->takeName(callSite.getInstruction());
2021     newCall.setAttributes(
2022                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2023     newCall.setCallingConv(callSite.getCallingConv());
2024 
2025     // Finally, remove the old call, replacing any uses with the new one.
2026     if (!callSite->use_empty())
2027       callSite->replaceAllUsesWith(newCall.getInstruction());
2028 
2029     // Copy debug location attached to CI.
2030     if (!callSite->getDebugLoc().isUnknown())
2031       newCall->setDebugLoc(callSite->getDebugLoc());
2032     callSite->eraseFromParent();
2033   }
2034 }
2035 
2036 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2037 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2038 /// existing call uses of the old function in the module, this adjusts them to
2039 /// call the new function directly.
2040 ///
2041 /// This is not just a cleanup: the always_inline pass requires direct calls to
2042 /// functions to be able to inline them.  If there is a bitcast in the way, it
2043 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2044 /// run at -O0.
2045 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2046                                                       llvm::Function *NewFn) {
2047   // If we're redefining a global as a function, don't transform it.
2048   if (!isa<llvm::Function>(Old)) return;
2049 
2050   replaceUsesOfNonProtoConstant(Old, NewFn);
2051 }
2052 
2053 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2054   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2055   // If we have a definition, this might be a deferred decl. If the
2056   // instantiation is explicit, make sure we emit it at the end.
2057   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2058     GetAddrOfGlobalVar(VD);
2059 
2060   EmitTopLevelDecl(VD);
2061 }
2062 
2063 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2064                                                  llvm::GlobalValue *GV) {
2065   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
2066 
2067   // Compute the function info and LLVM type.
2068   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2069   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2070 
2071   // Get or create the prototype for the function.
2072   llvm::Constant *Entry =
2073       GV ? GV
2074          : GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
2075 
2076   // Strip off a bitcast if we got one back.
2077   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2078     assert(CE->getOpcode() == llvm::Instruction::BitCast);
2079     Entry = CE->getOperand(0);
2080   }
2081 
2082   if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) {
2083     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2084     return;
2085   }
2086 
2087   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
2088     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
2089 
2090     // If the types mismatch then we have to rewrite the definition.
2091     assert(OldFn->isDeclaration() &&
2092            "Shouldn't replace non-declaration");
2093 
2094     // F is the Function* for the one with the wrong type, we must make a new
2095     // Function* and update everything that used F (a declaration) with the new
2096     // Function* (which will be a definition).
2097     //
2098     // This happens if there is a prototype for a function
2099     // (e.g. "int f()") and then a definition of a different type
2100     // (e.g. "int f(int x)").  Move the old function aside so that it
2101     // doesn't interfere with GetAddrOfFunction.
2102     OldFn->setName(StringRef());
2103     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2104 
2105     // This might be an implementation of a function without a
2106     // prototype, in which case, try to do special replacement of
2107     // calls which match the new prototype.  The really key thing here
2108     // is that we also potentially drop arguments from the call site
2109     // so as to make a direct call, which makes the inliner happier
2110     // and suppresses a number of optimizer warnings (!) about
2111     // dropping arguments.
2112     if (!OldFn->use_empty()) {
2113       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
2114       OldFn->removeDeadConstantUsers();
2115     }
2116 
2117     // Replace uses of F with the Function we will endow with a body.
2118     if (!Entry->use_empty()) {
2119       llvm::Constant *NewPtrForOldDecl =
2120         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
2121       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2122     }
2123 
2124     // Ok, delete the old function now, which is dead.
2125     OldFn->eraseFromParent();
2126 
2127     Entry = NewFn;
2128   }
2129 
2130   // We need to set linkage and visibility on the function before
2131   // generating code for it because various parts of IR generation
2132   // want to propagate this information down (e.g. to local static
2133   // declarations).
2134   llvm::Function *Fn = cast<llvm::Function>(Entry);
2135   setFunctionLinkage(GD, Fn);
2136 
2137   // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
2138   setGlobalVisibility(Fn, D);
2139 
2140   MaybeHandleStaticInExternC(D, Fn);
2141 
2142   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2143 
2144   SetFunctionDefinitionAttributes(D, Fn);
2145   SetLLVMFunctionAttributesForDefinition(D, Fn);
2146 
2147   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2148     AddGlobalCtor(Fn, CA->getPriority());
2149   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2150     AddGlobalDtor(Fn, DA->getPriority());
2151   if (D->hasAttr<AnnotateAttr>())
2152     AddGlobalAnnotations(D, Fn);
2153 
2154   llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this);
2155   if (PGOInit)
2156     AddGlobalCtor(PGOInit, 0);
2157 }
2158 
2159 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2160   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
2161   const AliasAttr *AA = D->getAttr<AliasAttr>();
2162   assert(AA && "Not an alias?");
2163 
2164   StringRef MangledName = getMangledName(GD);
2165 
2166   // If there is a definition in the module, then it wins over the alias.
2167   // This is dubious, but allow it to be safe.  Just ignore the alias.
2168   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2169   if (Entry && !Entry->isDeclaration())
2170     return;
2171 
2172   Aliases.push_back(GD);
2173 
2174   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2175 
2176   // Create a reference to the named value.  This ensures that it is emitted
2177   // if a deferred decl.
2178   llvm::Constant *Aliasee;
2179   if (isa<llvm::FunctionType>(DeclTy))
2180     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2181                                       /*ForVTable=*/false);
2182   else
2183     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2184                                     llvm::PointerType::getUnqual(DeclTy), 0);
2185 
2186   // Create the new alias itself, but don't set a name yet.
2187   llvm::GlobalValue *GA =
2188     new llvm::GlobalAlias(Aliasee->getType(),
2189                           llvm::Function::ExternalLinkage,
2190                           "", Aliasee, &getModule());
2191 
2192   if (Entry) {
2193     assert(Entry->isDeclaration());
2194 
2195     // If there is a declaration in the module, then we had an extern followed
2196     // by the alias, as in:
2197     //   extern int test6();
2198     //   ...
2199     //   int test6() __attribute__((alias("test7")));
2200     //
2201     // Remove it and replace uses of it with the alias.
2202     GA->takeName(Entry);
2203 
2204     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2205                                                           Entry->getType()));
2206     Entry->eraseFromParent();
2207   } else {
2208     GA->setName(MangledName);
2209   }
2210 
2211   // Set attributes which are particular to an alias; this is a
2212   // specialization of the attributes which may be set on a global
2213   // variable/function.
2214   if (D->hasAttr<DLLExportAttr>()) {
2215     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2216       // The dllexport attribute is ignored for undefined symbols.
2217       if (FD->hasBody())
2218         GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2219     } else {
2220       GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
2221     }
2222   } else if (D->hasAttr<WeakAttr>() ||
2223              D->hasAttr<WeakRefAttr>() ||
2224              D->isWeakImported()) {
2225     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2226   }
2227 
2228   SetCommonAttributes(D, GA);
2229 }
2230 
2231 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2232                                             ArrayRef<llvm::Type*> Tys) {
2233   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2234                                          Tys);
2235 }
2236 
2237 static llvm::StringMapEntry<llvm::Constant*> &
2238 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2239                          const StringLiteral *Literal,
2240                          bool TargetIsLSB,
2241                          bool &IsUTF16,
2242                          unsigned &StringLength) {
2243   StringRef String = Literal->getString();
2244   unsigned NumBytes = String.size();
2245 
2246   // Check for simple case.
2247   if (!Literal->containsNonAsciiOrNull()) {
2248     StringLength = NumBytes;
2249     return Map.GetOrCreateValue(String);
2250   }
2251 
2252   // Otherwise, convert the UTF8 literals into a string of shorts.
2253   IsUTF16 = true;
2254 
2255   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2256   const UTF8 *FromPtr = (const UTF8 *)String.data();
2257   UTF16 *ToPtr = &ToBuf[0];
2258 
2259   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2260                            &ToPtr, ToPtr + NumBytes,
2261                            strictConversion);
2262 
2263   // ConvertUTF8toUTF16 returns the length in ToPtr.
2264   StringLength = ToPtr - &ToBuf[0];
2265 
2266   // Add an explicit null.
2267   *ToPtr = 0;
2268   return Map.
2269     GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2270                                (StringLength + 1) * 2));
2271 }
2272 
2273 static llvm::StringMapEntry<llvm::Constant*> &
2274 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2275                        const StringLiteral *Literal,
2276                        unsigned &StringLength) {
2277   StringRef String = Literal->getString();
2278   StringLength = String.size();
2279   return Map.GetOrCreateValue(String);
2280 }
2281 
2282 llvm::Constant *
2283 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2284   unsigned StringLength = 0;
2285   bool isUTF16 = false;
2286   llvm::StringMapEntry<llvm::Constant*> &Entry =
2287     GetConstantCFStringEntry(CFConstantStringMap, Literal,
2288                              getDataLayout().isLittleEndian(),
2289                              isUTF16, StringLength);
2290 
2291   if (llvm::Constant *C = Entry.getValue())
2292     return C;
2293 
2294   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2295   llvm::Constant *Zeros[] = { Zero, Zero };
2296   llvm::Value *V;
2297 
2298   // If we don't already have it, get __CFConstantStringClassReference.
2299   if (!CFConstantStringClassRef) {
2300     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2301     Ty = llvm::ArrayType::get(Ty, 0);
2302     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2303                                            "__CFConstantStringClassReference");
2304     // Decay array -> ptr
2305     V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2306     CFConstantStringClassRef = V;
2307   }
2308   else
2309     V = CFConstantStringClassRef;
2310 
2311   QualType CFTy = getContext().getCFConstantStringType();
2312 
2313   llvm::StructType *STy =
2314     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2315 
2316   llvm::Constant *Fields[4];
2317 
2318   // Class pointer.
2319   Fields[0] = cast<llvm::ConstantExpr>(V);
2320 
2321   // Flags.
2322   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2323   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2324     llvm::ConstantInt::get(Ty, 0x07C8);
2325 
2326   // String pointer.
2327   llvm::Constant *C = 0;
2328   if (isUTF16) {
2329     ArrayRef<uint16_t> Arr =
2330       llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2331                                      const_cast<char *>(Entry.getKey().data())),
2332                                    Entry.getKey().size() / 2);
2333     C = llvm::ConstantDataArray::get(VMContext, Arr);
2334   } else {
2335     C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2336   }
2337 
2338   // Note: -fwritable-strings doesn't make the backing store strings of
2339   // CFStrings writable. (See <rdar://problem/10657500>)
2340   llvm::GlobalVariable *GV =
2341       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2342                                llvm::GlobalValue::PrivateLinkage, C, ".str");
2343   GV->setUnnamedAddr(true);
2344   // Don't enforce the target's minimum global alignment, since the only use
2345   // of the string is via this class initializer.
2346   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2347   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2348   // that changes the section it ends in, which surprises ld64.
2349   if (isUTF16) {
2350     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2351     GV->setAlignment(Align.getQuantity());
2352     GV->setSection("__TEXT,__ustring");
2353   } else {
2354     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2355     GV->setAlignment(Align.getQuantity());
2356     GV->setSection("__TEXT,__cstring,cstring_literals");
2357   }
2358 
2359   // String.
2360   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2361 
2362   if (isUTF16)
2363     // Cast the UTF16 string to the correct type.
2364     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2365 
2366   // String length.
2367   Ty = getTypes().ConvertType(getContext().LongTy);
2368   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2369 
2370   // The struct.
2371   C = llvm::ConstantStruct::get(STy, Fields);
2372   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2373                                 llvm::GlobalVariable::PrivateLinkage, C,
2374                                 "_unnamed_cfstring_");
2375   GV->setSection("__DATA,__cfstring");
2376   Entry.setValue(GV);
2377 
2378   return GV;
2379 }
2380 
2381 llvm::Constant *
2382 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2383   unsigned StringLength = 0;
2384   llvm::StringMapEntry<llvm::Constant*> &Entry =
2385     GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2386 
2387   if (llvm::Constant *C = Entry.getValue())
2388     return C;
2389 
2390   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2391   llvm::Constant *Zeros[] = { Zero, Zero };
2392   llvm::Value *V;
2393   // If we don't already have it, get _NSConstantStringClassReference.
2394   if (!ConstantStringClassRef) {
2395     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2396     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2397     llvm::Constant *GV;
2398     if (LangOpts.ObjCRuntime.isNonFragile()) {
2399       std::string str =
2400         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2401                             : "OBJC_CLASS_$_" + StringClass;
2402       GV = getObjCRuntime().GetClassGlobal(str);
2403       // Make sure the result is of the correct type.
2404       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2405       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2406       ConstantStringClassRef = V;
2407     } else {
2408       std::string str =
2409         StringClass.empty() ? "_NSConstantStringClassReference"
2410                             : "_" + StringClass + "ClassReference";
2411       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2412       GV = CreateRuntimeVariable(PTy, str);
2413       // Decay array -> ptr
2414       V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2415       ConstantStringClassRef = V;
2416     }
2417   }
2418   else
2419     V = ConstantStringClassRef;
2420 
2421   if (!NSConstantStringType) {
2422     // Construct the type for a constant NSString.
2423     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2424     D->startDefinition();
2425 
2426     QualType FieldTypes[3];
2427 
2428     // const int *isa;
2429     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2430     // const char *str;
2431     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2432     // unsigned int length;
2433     FieldTypes[2] = Context.UnsignedIntTy;
2434 
2435     // Create fields
2436     for (unsigned i = 0; i < 3; ++i) {
2437       FieldDecl *Field = FieldDecl::Create(Context, D,
2438                                            SourceLocation(),
2439                                            SourceLocation(), 0,
2440                                            FieldTypes[i], /*TInfo=*/0,
2441                                            /*BitWidth=*/0,
2442                                            /*Mutable=*/false,
2443                                            ICIS_NoInit);
2444       Field->setAccess(AS_public);
2445       D->addDecl(Field);
2446     }
2447 
2448     D->completeDefinition();
2449     QualType NSTy = Context.getTagDeclType(D);
2450     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2451   }
2452 
2453   llvm::Constant *Fields[3];
2454 
2455   // Class pointer.
2456   Fields[0] = cast<llvm::ConstantExpr>(V);
2457 
2458   // String pointer.
2459   llvm::Constant *C =
2460     llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2461 
2462   llvm::GlobalValue::LinkageTypes Linkage;
2463   bool isConstant;
2464   Linkage = llvm::GlobalValue::PrivateLinkage;
2465   isConstant = !LangOpts.WritableStrings;
2466 
2467   llvm::GlobalVariable *GV =
2468   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2469                            ".str");
2470   GV->setUnnamedAddr(true);
2471   // Don't enforce the target's minimum global alignment, since the only use
2472   // of the string is via this class initializer.
2473   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2474   GV->setAlignment(Align.getQuantity());
2475   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2476 
2477   // String length.
2478   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2479   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2480 
2481   // The struct.
2482   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2483   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2484                                 llvm::GlobalVariable::PrivateLinkage, C,
2485                                 "_unnamed_nsstring_");
2486   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2487   const char *NSStringNonFragileABISection =
2488       "__DATA,__objc_stringobj,regular,no_dead_strip";
2489   // FIXME. Fix section.
2490   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2491                      ? NSStringNonFragileABISection
2492                      : NSStringSection);
2493   Entry.setValue(GV);
2494 
2495   return GV;
2496 }
2497 
2498 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2499   if (ObjCFastEnumerationStateType.isNull()) {
2500     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2501     D->startDefinition();
2502 
2503     QualType FieldTypes[] = {
2504       Context.UnsignedLongTy,
2505       Context.getPointerType(Context.getObjCIdType()),
2506       Context.getPointerType(Context.UnsignedLongTy),
2507       Context.getConstantArrayType(Context.UnsignedLongTy,
2508                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2509     };
2510 
2511     for (size_t i = 0; i < 4; ++i) {
2512       FieldDecl *Field = FieldDecl::Create(Context,
2513                                            D,
2514                                            SourceLocation(),
2515                                            SourceLocation(), 0,
2516                                            FieldTypes[i], /*TInfo=*/0,
2517                                            /*BitWidth=*/0,
2518                                            /*Mutable=*/false,
2519                                            ICIS_NoInit);
2520       Field->setAccess(AS_public);
2521       D->addDecl(Field);
2522     }
2523 
2524     D->completeDefinition();
2525     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2526   }
2527 
2528   return ObjCFastEnumerationStateType;
2529 }
2530 
2531 llvm::Constant *
2532 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2533   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2534 
2535   // Don't emit it as the address of the string, emit the string data itself
2536   // as an inline array.
2537   if (E->getCharByteWidth() == 1) {
2538     SmallString<64> Str(E->getString());
2539 
2540     // Resize the string to the right size, which is indicated by its type.
2541     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2542     Str.resize(CAT->getSize().getZExtValue());
2543     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2544   }
2545 
2546   llvm::ArrayType *AType =
2547     cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2548   llvm::Type *ElemTy = AType->getElementType();
2549   unsigned NumElements = AType->getNumElements();
2550 
2551   // Wide strings have either 2-byte or 4-byte elements.
2552   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2553     SmallVector<uint16_t, 32> Elements;
2554     Elements.reserve(NumElements);
2555 
2556     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2557       Elements.push_back(E->getCodeUnit(i));
2558     Elements.resize(NumElements);
2559     return llvm::ConstantDataArray::get(VMContext, Elements);
2560   }
2561 
2562   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2563   SmallVector<uint32_t, 32> Elements;
2564   Elements.reserve(NumElements);
2565 
2566   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2567     Elements.push_back(E->getCodeUnit(i));
2568   Elements.resize(NumElements);
2569   return llvm::ConstantDataArray::get(VMContext, Elements);
2570 }
2571 
2572 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2573 /// constant array for the given string literal.
2574 llvm::Constant *
2575 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
2576   CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
2577   if (S->isAscii() || S->isUTF8()) {
2578     SmallString<64> Str(S->getString());
2579 
2580     // Resize the string to the right size, which is indicated by its type.
2581     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2582     Str.resize(CAT->getSize().getZExtValue());
2583     return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
2584   }
2585 
2586   // FIXME: the following does not memoize wide strings.
2587   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2588   llvm::GlobalVariable *GV =
2589     new llvm::GlobalVariable(getModule(),C->getType(),
2590                              !LangOpts.WritableStrings,
2591                              llvm::GlobalValue::PrivateLinkage,
2592                              C,".str");
2593 
2594   GV->setAlignment(Align.getQuantity());
2595   GV->setUnnamedAddr(true);
2596   return GV;
2597 }
2598 
2599 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2600 /// array for the given ObjCEncodeExpr node.
2601 llvm::Constant *
2602 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2603   std::string Str;
2604   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2605 
2606   return GetAddrOfConstantCString(Str);
2607 }
2608 
2609 
2610 /// GenerateWritableString -- Creates storage for a string literal.
2611 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
2612                                              bool constant,
2613                                              CodeGenModule &CGM,
2614                                              const char *GlobalName,
2615                                              unsigned Alignment) {
2616   // Create Constant for this string literal. Don't add a '\0'.
2617   llvm::Constant *C =
2618       llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
2619 
2620   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
2621   unsigned AddrSpace = 0;
2622   if (CGM.getLangOpts().OpenCL)
2623     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2624 
2625   // Create a global variable for this string
2626   llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2627       CGM.getModule(), C->getType(), constant,
2628       llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0,
2629       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2630   GV->setAlignment(Alignment);
2631   GV->setUnnamedAddr(true);
2632   return GV;
2633 }
2634 
2635 /// GetAddrOfConstantString - Returns a pointer to a character array
2636 /// containing the literal. This contents are exactly that of the
2637 /// given string, i.e. it will not be null terminated automatically;
2638 /// see GetAddrOfConstantCString. Note that whether the result is
2639 /// actually a pointer to an LLVM constant depends on
2640 /// Feature.WriteableStrings.
2641 ///
2642 /// The result has pointer to array type.
2643 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
2644                                                        const char *GlobalName,
2645                                                        unsigned Alignment) {
2646   // Get the default prefix if a name wasn't specified.
2647   if (!GlobalName)
2648     GlobalName = ".str";
2649 
2650   if (Alignment == 0)
2651     Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2652       .getQuantity();
2653 
2654   // Don't share any string literals if strings aren't constant.
2655   if (LangOpts.WritableStrings)
2656     return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
2657 
2658   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2659     ConstantStringMap.GetOrCreateValue(Str);
2660 
2661   if (llvm::GlobalVariable *GV = Entry.getValue()) {
2662     if (Alignment > GV->getAlignment()) {
2663       GV->setAlignment(Alignment);
2664     }
2665     return GV;
2666   }
2667 
2668   // Create a global variable for this.
2669   llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2670                                                    Alignment);
2671   Entry.setValue(GV);
2672   return GV;
2673 }
2674 
2675 /// GetAddrOfConstantCString - Returns a pointer to a character
2676 /// array containing the literal and a terminating '\0'
2677 /// character. The result has pointer to array type.
2678 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
2679                                                         const char *GlobalName,
2680                                                         unsigned Alignment) {
2681   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2682   return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
2683 }
2684 
2685 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
2686     const MaterializeTemporaryExpr *E, const Expr *Init) {
2687   assert((E->getStorageDuration() == SD_Static ||
2688           E->getStorageDuration() == SD_Thread) && "not a global temporary");
2689   const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2690 
2691   // If we're not materializing a subobject of the temporary, keep the
2692   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
2693   QualType MaterializedType = Init->getType();
2694   if (Init == E->GetTemporaryExpr())
2695     MaterializedType = E->getType();
2696 
2697   llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2698   if (Slot)
2699     return Slot;
2700 
2701   // FIXME: If an externally-visible declaration extends multiple temporaries,
2702   // we need to give each temporary the same name in every translation unit (and
2703   // we also need to make the temporaries externally-visible).
2704   SmallString<256> Name;
2705   llvm::raw_svector_ostream Out(Name);
2706   getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
2707   Out.flush();
2708 
2709   APValue *Value = 0;
2710   if (E->getStorageDuration() == SD_Static) {
2711     // We might have a cached constant initializer for this temporary. Note
2712     // that this might have a different value from the value computed by
2713     // evaluating the initializer if the surrounding constant expression
2714     // modifies the temporary.
2715     Value = getContext().getMaterializedTemporaryValue(E, false);
2716     if (Value && Value->isUninit())
2717       Value = 0;
2718   }
2719 
2720   // Try evaluating it now, it might have a constant initializer.
2721   Expr::EvalResult EvalResult;
2722   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2723       !EvalResult.hasSideEffects())
2724     Value = &EvalResult.Val;
2725 
2726   llvm::Constant *InitialValue = 0;
2727   bool Constant = false;
2728   llvm::Type *Type;
2729   if (Value) {
2730     // The temporary has a constant initializer, use it.
2731     InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2732     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2733     Type = InitialValue->getType();
2734   } else {
2735     // No initializer, the initialization will be provided when we
2736     // initialize the declaration which performed lifetime extension.
2737     Type = getTypes().ConvertTypeForMem(MaterializedType);
2738   }
2739 
2740   // Create a global variable for this lifetime-extended temporary.
2741   llvm::GlobalVariable *GV =
2742     new llvm::GlobalVariable(getModule(), Type, Constant,
2743                              llvm::GlobalValue::PrivateLinkage,
2744                              InitialValue, Name.c_str());
2745   GV->setAlignment(
2746       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
2747   if (VD->getTLSKind())
2748     setTLSMode(GV, *VD);
2749   Slot = GV;
2750   return GV;
2751 }
2752 
2753 /// EmitObjCPropertyImplementations - Emit information for synthesized
2754 /// properties for an implementation.
2755 void CodeGenModule::EmitObjCPropertyImplementations(const
2756                                                     ObjCImplementationDecl *D) {
2757   for (ObjCImplementationDecl::propimpl_iterator
2758          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
2759     ObjCPropertyImplDecl *PID = *i;
2760 
2761     // Dynamic is just for type-checking.
2762     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2763       ObjCPropertyDecl *PD = PID->getPropertyDecl();
2764 
2765       // Determine which methods need to be implemented, some may have
2766       // been overridden. Note that ::isPropertyAccessor is not the method
2767       // we want, that just indicates if the decl came from a
2768       // property. What we want to know is if the method is defined in
2769       // this implementation.
2770       if (!D->getInstanceMethod(PD->getGetterName()))
2771         CodeGenFunction(*this).GenerateObjCGetter(
2772                                  const_cast<ObjCImplementationDecl *>(D), PID);
2773       if (!PD->isReadOnly() &&
2774           !D->getInstanceMethod(PD->getSetterName()))
2775         CodeGenFunction(*this).GenerateObjCSetter(
2776                                  const_cast<ObjCImplementationDecl *>(D), PID);
2777     }
2778   }
2779 }
2780 
2781 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
2782   const ObjCInterfaceDecl *iface = impl->getClassInterface();
2783   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
2784        ivar; ivar = ivar->getNextIvar())
2785     if (ivar->getType().isDestructedType())
2786       return true;
2787 
2788   return false;
2789 }
2790 
2791 /// EmitObjCIvarInitializations - Emit information for ivar initialization
2792 /// for an implementation.
2793 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
2794   // We might need a .cxx_destruct even if we don't have any ivar initializers.
2795   if (needsDestructMethod(D)) {
2796     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2797     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2798     ObjCMethodDecl *DTORMethod =
2799       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
2800                              cxxSelector, getContext().VoidTy, 0, D,
2801                              /*isInstance=*/true, /*isVariadic=*/false,
2802                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
2803                              /*isDefined=*/false, ObjCMethodDecl::Required);
2804     D->addInstanceMethod(DTORMethod);
2805     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
2806     D->setHasDestructors(true);
2807   }
2808 
2809   // If the implementation doesn't have any ivar initializers, we don't need
2810   // a .cxx_construct.
2811   if (D->getNumIvarInitializers() == 0)
2812     return;
2813 
2814   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2815   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2816   // The constructor returns 'self'.
2817   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2818                                                 D->getLocation(),
2819                                                 D->getLocation(),
2820                                                 cxxSelector,
2821                                                 getContext().getObjCIdType(), 0,
2822                                                 D, /*isInstance=*/true,
2823                                                 /*isVariadic=*/false,
2824                                                 /*isPropertyAccessor=*/true,
2825                                                 /*isImplicitlyDeclared=*/true,
2826                                                 /*isDefined=*/false,
2827                                                 ObjCMethodDecl::Required);
2828   D->addInstanceMethod(CTORMethod);
2829   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
2830   D->setHasNonZeroConstructors(true);
2831 }
2832 
2833 /// EmitNamespace - Emit all declarations in a namespace.
2834 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
2835   for (auto *I : ND->decls()) {
2836     if (const auto *VD = dyn_cast<VarDecl>(I))
2837       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2838           VD->getTemplateSpecializationKind() != TSK_Undeclared)
2839         continue;
2840     EmitTopLevelDecl(I);
2841   }
2842 }
2843 
2844 // EmitLinkageSpec - Emit all declarations in a linkage spec.
2845 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
2846   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2847       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
2848     ErrorUnsupported(LSD, "linkage spec");
2849     return;
2850   }
2851 
2852   for (auto *I : LSD->decls()) {
2853     // Meta-data for ObjC class includes references to implemented methods.
2854     // Generate class's method definitions first.
2855     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
2856       for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2857            MEnd = OID->meth_end();
2858            M != MEnd; ++M)
2859         EmitTopLevelDecl(*M);
2860     }
2861     EmitTopLevelDecl(I);
2862   }
2863 }
2864 
2865 /// EmitTopLevelDecl - Emit code for a single top level declaration.
2866 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2867   // Ignore dependent declarations.
2868   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2869     return;
2870 
2871   switch (D->getKind()) {
2872   case Decl::CXXConversion:
2873   case Decl::CXXMethod:
2874   case Decl::Function:
2875     // Skip function templates
2876     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2877         cast<FunctionDecl>(D)->isLateTemplateParsed())
2878       return;
2879 
2880     EmitGlobal(cast<FunctionDecl>(D));
2881     break;
2882 
2883   case Decl::Var:
2884     // Skip variable templates
2885     if (cast<VarDecl>(D)->getDescribedVarTemplate())
2886       return;
2887   case Decl::VarTemplateSpecialization:
2888     EmitGlobal(cast<VarDecl>(D));
2889     break;
2890 
2891   // Indirect fields from global anonymous structs and unions can be
2892   // ignored; only the actual variable requires IR gen support.
2893   case Decl::IndirectField:
2894     break;
2895 
2896   // C++ Decls
2897   case Decl::Namespace:
2898     EmitNamespace(cast<NamespaceDecl>(D));
2899     break;
2900     // No code generation needed.
2901   case Decl::UsingShadow:
2902   case Decl::ClassTemplate:
2903   case Decl::VarTemplate:
2904   case Decl::VarTemplatePartialSpecialization:
2905   case Decl::FunctionTemplate:
2906   case Decl::TypeAliasTemplate:
2907   case Decl::Block:
2908   case Decl::Empty:
2909     break;
2910   case Decl::Using:          // using X; [C++]
2911     if (CGDebugInfo *DI = getModuleDebugInfo())
2912         DI->EmitUsingDecl(cast<UsingDecl>(*D));
2913     return;
2914   case Decl::NamespaceAlias:
2915     if (CGDebugInfo *DI = getModuleDebugInfo())
2916         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
2917     return;
2918   case Decl::UsingDirective: // using namespace X; [C++]
2919     if (CGDebugInfo *DI = getModuleDebugInfo())
2920       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2921     return;
2922   case Decl::CXXConstructor:
2923     // Skip function templates
2924     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2925         cast<FunctionDecl>(D)->isLateTemplateParsed())
2926       return;
2927 
2928     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2929     break;
2930   case Decl::CXXDestructor:
2931     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2932       return;
2933     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2934     break;
2935 
2936   case Decl::StaticAssert:
2937     // Nothing to do.
2938     break;
2939 
2940   // Objective-C Decls
2941 
2942   // Forward declarations, no (immediate) code generation.
2943   case Decl::ObjCInterface:
2944   case Decl::ObjCCategory:
2945     break;
2946 
2947   case Decl::ObjCProtocol: {
2948     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2949     if (Proto->isThisDeclarationADefinition())
2950       ObjCRuntime->GenerateProtocol(Proto);
2951     break;
2952   }
2953 
2954   case Decl::ObjCCategoryImpl:
2955     // Categories have properties but don't support synthesize so we
2956     // can ignore them here.
2957     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2958     break;
2959 
2960   case Decl::ObjCImplementation: {
2961     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2962     EmitObjCPropertyImplementations(OMD);
2963     EmitObjCIvarInitializations(OMD);
2964     ObjCRuntime->GenerateClass(OMD);
2965     // Emit global variable debug information.
2966     if (CGDebugInfo *DI = getModuleDebugInfo())
2967       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2968         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2969             OMD->getClassInterface()), OMD->getLocation());
2970     break;
2971   }
2972   case Decl::ObjCMethod: {
2973     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2974     // If this is not a prototype, emit the body.
2975     if (OMD->getBody())
2976       CodeGenFunction(*this).GenerateObjCMethod(OMD);
2977     break;
2978   }
2979   case Decl::ObjCCompatibleAlias:
2980     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
2981     break;
2982 
2983   case Decl::LinkageSpec:
2984     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
2985     break;
2986 
2987   case Decl::FileScopeAsm: {
2988     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
2989     StringRef AsmString = AD->getAsmString()->getString();
2990 
2991     const std::string &S = getModule().getModuleInlineAsm();
2992     if (S.empty())
2993       getModule().setModuleInlineAsm(AsmString);
2994     else if (S.end()[-1] == '\n')
2995       getModule().setModuleInlineAsm(S + AsmString.str());
2996     else
2997       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
2998     break;
2999   }
3000 
3001   case Decl::Import: {
3002     ImportDecl *Import = cast<ImportDecl>(D);
3003 
3004     // Ignore import declarations that come from imported modules.
3005     if (clang::Module *Owner = Import->getOwningModule()) {
3006       if (getLangOpts().CurrentModule.empty() ||
3007           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3008         break;
3009     }
3010 
3011     ImportedModules.insert(Import->getImportedModule());
3012     break;
3013   }
3014 
3015   case Decl::ClassTemplateSpecialization: {
3016     const ClassTemplateSpecializationDecl *Spec =
3017         cast<ClassTemplateSpecializationDecl>(D);
3018     if (DebugInfo &&
3019         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
3020       DebugInfo->completeTemplateDefinition(*Spec);
3021   }
3022 
3023   default:
3024     // Make sure we handled everything we should, every other kind is a
3025     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3026     // function. Need to recode Decl::Kind to do that easily.
3027     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3028   }
3029 }
3030 
3031 /// Turns the given pointer into a constant.
3032 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3033                                           const void *Ptr) {
3034   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3035   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3036   return llvm::ConstantInt::get(i64, PtrInt);
3037 }
3038 
3039 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3040                                    llvm::NamedMDNode *&GlobalMetadata,
3041                                    GlobalDecl D,
3042                                    llvm::GlobalValue *Addr) {
3043   if (!GlobalMetadata)
3044     GlobalMetadata =
3045       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3046 
3047   // TODO: should we report variant information for ctors/dtors?
3048   llvm::Value *Ops[] = {
3049     Addr,
3050     GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3051   };
3052   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3053 }
3054 
3055 /// For each function which is declared within an extern "C" region and marked
3056 /// as 'used', but has internal linkage, create an alias from the unmangled
3057 /// name to the mangled name if possible. People expect to be able to refer
3058 /// to such functions with an unmangled name from inline assembly within the
3059 /// same translation unit.
3060 void CodeGenModule::EmitStaticExternCAliases() {
3061   for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3062                                   E = StaticExternCValues.end();
3063        I != E; ++I) {
3064     IdentifierInfo *Name = I->first;
3065     llvm::GlobalValue *Val = I->second;
3066     if (Val && !getModule().getNamedValue(Name->getName()))
3067       addUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
3068                                           Name->getName(), Val, &getModule()));
3069   }
3070 }
3071 
3072 /// Emits metadata nodes associating all the global values in the
3073 /// current module with the Decls they came from.  This is useful for
3074 /// projects using IR gen as a subroutine.
3075 ///
3076 /// Since there's currently no way to associate an MDNode directly
3077 /// with an llvm::GlobalValue, we create a global named metadata
3078 /// with the name 'clang.global.decl.ptrs'.
3079 void CodeGenModule::EmitDeclMetadata() {
3080   llvm::NamedMDNode *GlobalMetadata = 0;
3081 
3082   // StaticLocalDeclMap
3083   for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
3084          I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3085        I != E; ++I) {
3086     llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3087     EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3088   }
3089 }
3090 
3091 /// Emits metadata nodes for all the local variables in the current
3092 /// function.
3093 void CodeGenFunction::EmitDeclMetadata() {
3094   if (LocalDeclMap.empty()) return;
3095 
3096   llvm::LLVMContext &Context = getLLVMContext();
3097 
3098   // Find the unique metadata ID for this name.
3099   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3100 
3101   llvm::NamedMDNode *GlobalMetadata = 0;
3102 
3103   for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3104          I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3105     const Decl *D = I->first;
3106     llvm::Value *Addr = I->second;
3107 
3108     if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3109       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3110       Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
3111     } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3112       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3113       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3114     }
3115   }
3116 }
3117 
3118 void CodeGenModule::EmitVersionIdentMetadata() {
3119   llvm::NamedMDNode *IdentMetadata =
3120     TheModule.getOrInsertNamedMetadata("llvm.ident");
3121   std::string Version = getClangFullVersion();
3122   llvm::LLVMContext &Ctx = TheModule.getContext();
3123 
3124   llvm::Value *IdentNode[] = {
3125     llvm::MDString::get(Ctx, Version)
3126   };
3127   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3128 }
3129 
3130 void CodeGenModule::EmitCoverageFile() {
3131   if (!getCodeGenOpts().CoverageFile.empty()) {
3132     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3133       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3134       llvm::LLVMContext &Ctx = TheModule.getContext();
3135       llvm::MDString *CoverageFile =
3136           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3137       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3138         llvm::MDNode *CU = CUNode->getOperand(i);
3139         llvm::Value *node[] = { CoverageFile, CU };
3140         llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3141         GCov->addOperand(N);
3142       }
3143     }
3144   }
3145 }
3146 
3147 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3148                                                      QualType GuidType) {
3149   // Sema has checked that all uuid strings are of the form
3150   // "12345678-1234-1234-1234-1234567890ab".
3151   assert(Uuid.size() == 36);
3152   for (unsigned i = 0; i < 36; ++i) {
3153     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3154     else                                         assert(isHexDigit(Uuid[i]));
3155   }
3156 
3157   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3158 
3159   llvm::Constant *Field3[8];
3160   for (unsigned Idx = 0; Idx < 8; ++Idx)
3161     Field3[Idx] = llvm::ConstantInt::get(
3162         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3163 
3164   llvm::Constant *Fields[4] = {
3165     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3166     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3167     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3168     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3169   };
3170 
3171   return llvm::ConstantStruct::getAnon(Fields);
3172 }
3173