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