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