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