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