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