xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision a8fbef44fe2347942e2eb76e5b9144d74b5bdc7e)
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   emitAtAvailableLinkGuard();
418   emitLLVMUsed();
419   if (SanStats)
420     SanStats->finish();
421 
422   if (CodeGenOpts.Autolink &&
423       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
424     EmitModuleLinkOptions();
425   }
426 
427   if (CodeGenOpts.DwarfVersion) {
428     // We actually want the latest version when there are conflicts.
429     // We can change from Warning to Latest if such mode is supported.
430     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
431                               CodeGenOpts.DwarfVersion);
432   }
433   if (CodeGenOpts.EmitCodeView) {
434     // Indicate that we want CodeView in the metadata.
435     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
436   }
437   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
438     // We don't support LTO with 2 with different StrictVTablePointers
439     // FIXME: we could support it by stripping all the information introduced
440     // by StrictVTablePointers.
441 
442     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
443 
444     llvm::Metadata *Ops[2] = {
445               llvm::MDString::get(VMContext, "StrictVTablePointers"),
446               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
447                   llvm::Type::getInt32Ty(VMContext), 1))};
448 
449     getModule().addModuleFlag(llvm::Module::Require,
450                               "StrictVTablePointersRequirement",
451                               llvm::MDNode::get(VMContext, Ops));
452   }
453   if (DebugInfo)
454     // We support a single version in the linked module. The LLVM
455     // parser will drop debug info with a different version number
456     // (and warn about it, too).
457     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
458                               llvm::DEBUG_METADATA_VERSION);
459 
460   // We need to record the widths of enums and wchar_t, so that we can generate
461   // the correct build attributes in the ARM backend.
462   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
463   if (   Arch == llvm::Triple::arm
464       || Arch == llvm::Triple::armeb
465       || Arch == llvm::Triple::thumb
466       || Arch == llvm::Triple::thumbeb) {
467     // Width of wchar_t in bytes
468     uint64_t WCharWidth =
469         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
470     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
471 
472     // The minimum width of an enum in bytes
473     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
474     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
475   }
476 
477   if (CodeGenOpts.SanitizeCfiCrossDso) {
478     // Indicate that we want cross-DSO control flow integrity checks.
479     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
480   }
481 
482   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
483     // Indicate whether __nvvm_reflect should be configured to flush denormal
484     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
485     // property.)
486     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
487                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
488   }
489 
490   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
491     assert(PLevel < 3 && "Invalid PIC Level");
492     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
493     if (Context.getLangOpts().PIE)
494       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
495   }
496 
497   SimplifyPersonality();
498 
499   if (getCodeGenOpts().EmitDeclMetadata)
500     EmitDeclMetadata();
501 
502   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
503     EmitCoverageFile();
504 
505   if (DebugInfo)
506     DebugInfo->finalize();
507 
508   EmitVersionIdentMetadata();
509 
510   EmitTargetMetadata();
511 }
512 
513 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
514   // Make sure that this type is translated.
515   Types.UpdateCompletedType(TD);
516 }
517 
518 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
519   // Make sure that this type is translated.
520   Types.RefreshTypeCacheForClass(RD);
521 }
522 
523 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
524   if (!TBAA)
525     return nullptr;
526   return TBAA->getTBAAInfo(QTy);
527 }
528 
529 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
530   if (!TBAA)
531     return nullptr;
532   return TBAA->getTBAAInfoForVTablePtr();
533 }
534 
535 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
536   if (!TBAA)
537     return nullptr;
538   return TBAA->getTBAAStructInfo(QTy);
539 }
540 
541 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
542                                                   llvm::MDNode *AccessN,
543                                                   uint64_t O) {
544   if (!TBAA)
545     return nullptr;
546   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
547 }
548 
549 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
550 /// and struct-path aware TBAA, the tag has the same format:
551 /// base type, access type and offset.
552 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
553 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
554                                                 llvm::MDNode *TBAAInfo,
555                                                 bool ConvertTypeToTag) {
556   if (ConvertTypeToTag && TBAA)
557     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
558                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
559   else
560     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
561 }
562 
563 void CodeGenModule::DecorateInstructionWithInvariantGroup(
564     llvm::Instruction *I, const CXXRecordDecl *RD) {
565   llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
566   auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
567   // Check if we have to wrap MDString in MDNode.
568   if (!MetaDataNode)
569     MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
570   I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
571 }
572 
573 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
574   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
575   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
576 }
577 
578 /// ErrorUnsupported - Print out an error that codegen doesn't support the
579 /// specified stmt yet.
580 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
581   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
582                                                "cannot compile this %0 yet");
583   std::string Msg = Type;
584   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
585     << Msg << S->getSourceRange();
586 }
587 
588 /// ErrorUnsupported - Print out an error that codegen doesn't support the
589 /// specified decl yet.
590 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
591   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
592                                                "cannot compile this %0 yet");
593   std::string Msg = Type;
594   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
595 }
596 
597 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
598   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
599 }
600 
601 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
602                                         const NamedDecl *D) const {
603   // Internal definitions always have default visibility.
604   if (GV->hasLocalLinkage()) {
605     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
606     return;
607   }
608 
609   // Set visibility for definitions.
610   LinkageInfo LV = D->getLinkageAndVisibility();
611   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
612     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
613 }
614 
615 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
616   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
617       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
618       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
619       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
620       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
621 }
622 
623 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
624     CodeGenOptions::TLSModel M) {
625   switch (M) {
626   case CodeGenOptions::GeneralDynamicTLSModel:
627     return llvm::GlobalVariable::GeneralDynamicTLSModel;
628   case CodeGenOptions::LocalDynamicTLSModel:
629     return llvm::GlobalVariable::LocalDynamicTLSModel;
630   case CodeGenOptions::InitialExecTLSModel:
631     return llvm::GlobalVariable::InitialExecTLSModel;
632   case CodeGenOptions::LocalExecTLSModel:
633     return llvm::GlobalVariable::LocalExecTLSModel;
634   }
635   llvm_unreachable("Invalid TLS model!");
636 }
637 
638 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
639   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
640 
641   llvm::GlobalValue::ThreadLocalMode TLM;
642   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
643 
644   // Override the TLS model if it is explicitly specified.
645   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
646     TLM = GetLLVMTLSModel(Attr->getModel());
647   }
648 
649   GV->setThreadLocalMode(TLM);
650 }
651 
652 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
653   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
654 
655   // Some ABIs don't have constructor variants.  Make sure that base and
656   // complete constructors get mangled the same.
657   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
658     if (!getTarget().getCXXABI().hasConstructorVariants()) {
659       CXXCtorType OrigCtorType = GD.getCtorType();
660       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
661       if (OrigCtorType == Ctor_Base)
662         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
663     }
664   }
665 
666   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
667   if (!FoundStr.empty())
668     return FoundStr;
669 
670   const auto *ND = cast<NamedDecl>(GD.getDecl());
671   SmallString<256> Buffer;
672   StringRef Str;
673   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
674     llvm::raw_svector_ostream Out(Buffer);
675     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
676       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
677     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
678       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
679     else
680       getCXXABI().getMangleContext().mangleName(ND, Out);
681     Str = Out.str();
682   } else {
683     IdentifierInfo *II = ND->getIdentifier();
684     assert(II && "Attempt to mangle unnamed decl.");
685     const auto *FD = dyn_cast<FunctionDecl>(ND);
686 
687     if (FD &&
688         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
689       llvm::raw_svector_ostream Out(Buffer);
690       Out << "__regcall3__" << II->getName();
691       Str = Out.str();
692     } else {
693       Str = II->getName();
694     }
695   }
696 
697   // Keep the first result in the case of a mangling collision.
698   auto Result = Manglings.insert(std::make_pair(Str, GD));
699   return FoundStr = Result.first->first();
700 }
701 
702 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
703                                              const BlockDecl *BD) {
704   MangleContext &MangleCtx = getCXXABI().getMangleContext();
705   const Decl *D = GD.getDecl();
706 
707   SmallString<256> Buffer;
708   llvm::raw_svector_ostream Out(Buffer);
709   if (!D)
710     MangleCtx.mangleGlobalBlock(BD,
711       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
712   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
713     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
714   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
715     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
716   else
717     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
718 
719   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
720   return Result.first->first();
721 }
722 
723 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
724   return getModule().getNamedValue(Name);
725 }
726 
727 /// AddGlobalCtor - Add a function to the list that will be called before
728 /// main() runs.
729 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
730                                   llvm::Constant *AssociatedData) {
731   // FIXME: Type coercion of void()* types.
732   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
733 }
734 
735 /// AddGlobalDtor - Add a function to the list that will be called
736 /// when the module is unloaded.
737 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
738   // FIXME: Type coercion of void()* types.
739   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
740 }
741 
742 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
743   if (Fns.empty()) return;
744 
745   // Ctor function type is void()*.
746   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
747   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
748 
749   // Get the type of a ctor entry, { i32, void ()*, i8* }.
750   llvm::StructType *CtorStructTy = llvm::StructType::get(
751       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
752 
753   // Construct the constructor and destructor arrays.
754   ConstantInitBuilder builder(*this);
755   auto ctors = builder.beginArray(CtorStructTy);
756   for (const auto &I : Fns) {
757     auto ctor = ctors.beginStruct(CtorStructTy);
758     ctor.addInt(Int32Ty, I.Priority);
759     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
760     if (I.AssociatedData)
761       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
762     else
763       ctor.addNullPointer(VoidPtrTy);
764     ctor.finishAndAddTo(ctors);
765   }
766 
767   auto list =
768     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
769                                 /*constant*/ false,
770                                 llvm::GlobalValue::AppendingLinkage);
771 
772   // The LTO linker doesn't seem to like it when we set an alignment
773   // on appending variables.  Take it off as a workaround.
774   list->setAlignment(0);
775 
776   Fns.clear();
777 }
778 
779 llvm::GlobalValue::LinkageTypes
780 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
781   const auto *D = cast<FunctionDecl>(GD.getDecl());
782 
783   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
784 
785   if (isa<CXXDestructorDecl>(D) &&
786       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
787                                          GD.getDtorType())) {
788     // Destructor variants in the Microsoft C++ ABI are always internal or
789     // linkonce_odr thunks emitted on an as-needed basis.
790     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
791                                    : llvm::GlobalValue::LinkOnceODRLinkage;
792   }
793 
794   if (isa<CXXConstructorDecl>(D) &&
795       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
796       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
797     // Our approach to inheriting constructors is fundamentally different from
798     // that used by the MS ABI, so keep our inheriting constructor thunks
799     // internal rather than trying to pick an unambiguous mangling for them.
800     return llvm::GlobalValue::InternalLinkage;
801   }
802 
803   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
804 }
805 
806 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
807   const auto *FD = cast<FunctionDecl>(GD.getDecl());
808 
809   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
810     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
811       // Don't dllexport/import destructor thunks.
812       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
813       return;
814     }
815   }
816 
817   if (FD->hasAttr<DLLImportAttr>())
818     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
819   else if (FD->hasAttr<DLLExportAttr>())
820     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
821   else
822     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
823 }
824 
825 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
826   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
827   if (!MDS) return nullptr;
828 
829   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
830 }
831 
832 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
833                                                     llvm::Function *F) {
834   setNonAliasAttributes(D, F);
835 }
836 
837 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
838                                               const CGFunctionInfo &Info,
839                                               llvm::Function *F) {
840   unsigned CallingConv;
841   AttributeListType AttributeList;
842   ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
843                          false);
844   F->setAttributes(llvm::AttributeList::get(getLLVMContext(), AttributeList));
845   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
846 }
847 
848 /// Determines whether the language options require us to model
849 /// unwind exceptions.  We treat -fexceptions as mandating this
850 /// except under the fragile ObjC ABI with only ObjC exceptions
851 /// enabled.  This means, for example, that C with -fexceptions
852 /// enables this.
853 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
854   // If exceptions are completely disabled, obviously this is false.
855   if (!LangOpts.Exceptions) return false;
856 
857   // If C++ exceptions are enabled, this is true.
858   if (LangOpts.CXXExceptions) return true;
859 
860   // If ObjC exceptions are enabled, this depends on the ABI.
861   if (LangOpts.ObjCExceptions) {
862     return LangOpts.ObjCRuntime.hasUnwindExceptions();
863   }
864 
865   return true;
866 }
867 
868 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
869                                                            llvm::Function *F) {
870   llvm::AttrBuilder B;
871 
872   if (CodeGenOpts.UnwindTables)
873     B.addAttribute(llvm::Attribute::UWTable);
874 
875   if (!hasUnwindExceptions(LangOpts))
876     B.addAttribute(llvm::Attribute::NoUnwind);
877 
878   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
879     B.addAttribute(llvm::Attribute::StackProtect);
880   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
881     B.addAttribute(llvm::Attribute::StackProtectStrong);
882   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
883     B.addAttribute(llvm::Attribute::StackProtectReq);
884 
885   if (!D) {
886     // If we don't have a declaration to control inlining, the function isn't
887     // explicitly marked as alwaysinline for semantic reasons, and inlining is
888     // disabled, mark the function as noinline.
889     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
890         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
891       B.addAttribute(llvm::Attribute::NoInline);
892 
893     F->addAttributes(
894         llvm::AttributeList::FunctionIndex,
895         llvm::AttributeList::get(F->getContext(),
896                                  llvm::AttributeList::FunctionIndex, B));
897     return;
898   }
899 
900   if (D->hasAttr<OptimizeNoneAttr>()) {
901     B.addAttribute(llvm::Attribute::OptimizeNone);
902 
903     // OptimizeNone implies noinline; we should not be inlining such functions.
904     B.addAttribute(llvm::Attribute::NoInline);
905     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
906            "OptimizeNone and AlwaysInline on same function!");
907 
908     // We still need to handle naked functions even though optnone subsumes
909     // much of their semantics.
910     if (D->hasAttr<NakedAttr>())
911       B.addAttribute(llvm::Attribute::Naked);
912 
913     // OptimizeNone wins over OptimizeForSize and MinSize.
914     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
915     F->removeFnAttr(llvm::Attribute::MinSize);
916   } else if (D->hasAttr<NakedAttr>()) {
917     // Naked implies noinline: we should not be inlining such functions.
918     B.addAttribute(llvm::Attribute::Naked);
919     B.addAttribute(llvm::Attribute::NoInline);
920   } else if (D->hasAttr<NoDuplicateAttr>()) {
921     B.addAttribute(llvm::Attribute::NoDuplicate);
922   } else if (D->hasAttr<NoInlineAttr>()) {
923     B.addAttribute(llvm::Attribute::NoInline);
924   } else if (D->hasAttr<AlwaysInlineAttr>() &&
925              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
926     // (noinline wins over always_inline, and we can't specify both in IR)
927     B.addAttribute(llvm::Attribute::AlwaysInline);
928   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
929     // If we're not inlining, then force everything that isn't always_inline to
930     // carry an explicit noinline attribute.
931     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
932       B.addAttribute(llvm::Attribute::NoInline);
933   } else {
934     // Otherwise, propagate the inline hint attribute and potentially use its
935     // absence to mark things as noinline.
936     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
937       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
938             return Redecl->isInlineSpecified();
939           })) {
940         B.addAttribute(llvm::Attribute::InlineHint);
941       } else if (CodeGenOpts.getInlining() ==
942                      CodeGenOptions::OnlyHintInlining &&
943                  !FD->isInlined() &&
944                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
945         B.addAttribute(llvm::Attribute::NoInline);
946       }
947     }
948   }
949 
950   // Add other optimization related attributes if we are optimizing this
951   // function.
952   if (!D->hasAttr<OptimizeNoneAttr>()) {
953     if (D->hasAttr<ColdAttr>()) {
954       B.addAttribute(llvm::Attribute::OptimizeForSize);
955       B.addAttribute(llvm::Attribute::Cold);
956     }
957 
958     if (D->hasAttr<MinSizeAttr>())
959       B.addAttribute(llvm::Attribute::MinSize);
960   }
961 
962   F->addAttributes(llvm::AttributeList::FunctionIndex,
963                    llvm::AttributeList::get(
964                        F->getContext(), llvm::AttributeList::FunctionIndex, B));
965 
966   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
967   if (alignment)
968     F->setAlignment(alignment);
969 
970   // Some C++ ABIs require 2-byte alignment for member functions, in order to
971   // reserve a bit for differentiating between virtual and non-virtual member
972   // functions. If the current target's C++ ABI requires this and this is a
973   // member function, set its alignment accordingly.
974   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
975     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
976       F->setAlignment(2);
977   }
978 
979   // In the cross-dso CFI mode, we want !type attributes on definitions only.
980   if (CodeGenOpts.SanitizeCfiCrossDso)
981     if (auto *FD = dyn_cast<FunctionDecl>(D))
982       CreateFunctionTypeMetadata(FD, F);
983 }
984 
985 void CodeGenModule::SetCommonAttributes(const Decl *D,
986                                         llvm::GlobalValue *GV) {
987   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
988     setGlobalVisibility(GV, ND);
989   else
990     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
991 
992   if (D && D->hasAttr<UsedAttr>())
993     addUsedGlobal(GV);
994 }
995 
996 void CodeGenModule::setAliasAttributes(const Decl *D,
997                                        llvm::GlobalValue *GV) {
998   SetCommonAttributes(D, GV);
999 
1000   // Process the dllexport attribute based on whether the original definition
1001   // (not necessarily the aliasee) was exported.
1002   if (D->hasAttr<DLLExportAttr>())
1003     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1004 }
1005 
1006 void CodeGenModule::setNonAliasAttributes(const Decl *D,
1007                                           llvm::GlobalObject *GO) {
1008   SetCommonAttributes(D, GO);
1009 
1010   if (D)
1011     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1012       GO->setSection(SA->getName());
1013 
1014   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1015 }
1016 
1017 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1018                                                   llvm::Function *F,
1019                                                   const CGFunctionInfo &FI) {
1020   SetLLVMFunctionAttributes(D, FI, F);
1021   SetLLVMFunctionAttributesForDefinition(D, F);
1022 
1023   F->setLinkage(llvm::Function::InternalLinkage);
1024 
1025   setNonAliasAttributes(D, F);
1026 }
1027 
1028 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1029                                          const NamedDecl *ND) {
1030   // Set linkage and visibility in case we never see a definition.
1031   LinkageInfo LV = ND->getLinkageAndVisibility();
1032   if (LV.getLinkage() != ExternalLinkage) {
1033     // Don't set internal linkage on declarations.
1034   } else {
1035     if (ND->hasAttr<DLLImportAttr>()) {
1036       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1037       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1038     } else if (ND->hasAttr<DLLExportAttr>()) {
1039       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
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::AttributeList::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::AttributeList::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 *CodeGenModule::GetOrCreateLLVMFunction(
1915     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
1916     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
1917     ForDefinition_t IsForDefinition) {
1918   const Decl *D = GD.getDecl();
1919 
1920   // Lookup the entry, lazily creating it if necessary.
1921   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1922   if (Entry) {
1923     if (WeakRefReferences.erase(Entry)) {
1924       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1925       if (FD && !FD->hasAttr<WeakAttr>())
1926         Entry->setLinkage(llvm::Function::ExternalLinkage);
1927     }
1928 
1929     // Handle dropped DLL attributes.
1930     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1931       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1932 
1933     // If there are two attempts to define the same mangled name, issue an
1934     // error.
1935     if (IsForDefinition && !Entry->isDeclaration()) {
1936       GlobalDecl OtherGD;
1937       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1938       // to make sure that we issue an error only once.
1939       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1940           (GD.getCanonicalDecl().getDecl() !=
1941            OtherGD.getCanonicalDecl().getDecl()) &&
1942           DiagnosedConflictingDefinitions.insert(GD).second) {
1943         getDiags().Report(D->getLocation(),
1944                           diag::err_duplicate_mangled_name);
1945         getDiags().Report(OtherGD.getDecl()->getLocation(),
1946                           diag::note_previous_definition);
1947       }
1948     }
1949 
1950     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1951         (Entry->getType()->getElementType() == Ty)) {
1952       return Entry;
1953     }
1954 
1955     // Make sure the result is of the correct type.
1956     // (If function is requested for a definition, we always need to create a new
1957     // function, not just return a bitcast.)
1958     if (!IsForDefinition)
1959       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1960   }
1961 
1962   // This function doesn't have a complete type (for example, the return
1963   // type is an incomplete struct). Use a fake type instead, and make
1964   // sure not to try to set attributes.
1965   bool IsIncompleteFunction = false;
1966 
1967   llvm::FunctionType *FTy;
1968   if (isa<llvm::FunctionType>(Ty)) {
1969     FTy = cast<llvm::FunctionType>(Ty);
1970   } else {
1971     FTy = llvm::FunctionType::get(VoidTy, false);
1972     IsIncompleteFunction = true;
1973   }
1974 
1975   llvm::Function *F =
1976       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1977                              Entry ? StringRef() : MangledName, &getModule());
1978 
1979   // If we already created a function with the same mangled name (but different
1980   // type) before, take its name and add it to the list of functions to be
1981   // replaced with F at the end of CodeGen.
1982   //
1983   // This happens if there is a prototype for a function (e.g. "int f()") and
1984   // then a definition of a different type (e.g. "int f(int x)").
1985   if (Entry) {
1986     F->takeName(Entry);
1987 
1988     // This might be an implementation of a function without a prototype, in
1989     // which case, try to do special replacement of calls which match the new
1990     // prototype.  The really key thing here is that we also potentially drop
1991     // arguments from the call site so as to make a direct call, which makes the
1992     // inliner happier and suppresses a number of optimizer warnings (!) about
1993     // dropping arguments.
1994     if (!Entry->use_empty()) {
1995       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
1996       Entry->removeDeadConstantUsers();
1997     }
1998 
1999     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2000         F, Entry->getType()->getElementType()->getPointerTo());
2001     addGlobalValReplacement(Entry, BC);
2002   }
2003 
2004   assert(F->getName() == MangledName && "name was uniqued!");
2005   if (D)
2006     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2007   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2008     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2009     F->addAttributes(llvm::AttributeList::FunctionIndex,
2010                      llvm::AttributeList::get(
2011                          VMContext, llvm::AttributeList::FunctionIndex, B));
2012   }
2013 
2014   if (!DontDefer) {
2015     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2016     // each other bottoming out with the base dtor.  Therefore we emit non-base
2017     // dtors on usage, even if there is no dtor definition in the TU.
2018     if (D && isa<CXXDestructorDecl>(D) &&
2019         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2020                                            GD.getDtorType()))
2021       addDeferredDeclToEmit(F, GD);
2022 
2023     // This is the first use or definition of a mangled name.  If there is a
2024     // deferred decl with this name, remember that we need to emit it at the end
2025     // of the file.
2026     auto DDI = DeferredDecls.find(MangledName);
2027     if (DDI != DeferredDecls.end()) {
2028       // Move the potentially referenced deferred decl to the
2029       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2030       // don't need it anymore).
2031       addDeferredDeclToEmit(F, DDI->second);
2032       DeferredDecls.erase(DDI);
2033 
2034       // Otherwise, there are cases we have to worry about where we're
2035       // using a declaration for which we must emit a definition but where
2036       // we might not find a top-level definition:
2037       //   - member functions defined inline in their classes
2038       //   - friend functions defined inline in some class
2039       //   - special member functions with implicit definitions
2040       // If we ever change our AST traversal to walk into class methods,
2041       // this will be unnecessary.
2042       //
2043       // We also don't emit a definition for a function if it's going to be an
2044       // entry in a vtable, unless it's already marked as used.
2045     } else if (getLangOpts().CPlusPlus && D) {
2046       // Look for a declaration that's lexically in a record.
2047       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2048            FD = FD->getPreviousDecl()) {
2049         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2050           if (FD->doesThisDeclarationHaveABody()) {
2051             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
2052             break;
2053           }
2054         }
2055       }
2056     }
2057   }
2058 
2059   // Make sure the result is of the requested type.
2060   if (!IsIncompleteFunction) {
2061     assert(F->getType()->getElementType() == Ty);
2062     return F;
2063   }
2064 
2065   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2066   return llvm::ConstantExpr::getBitCast(F, PTy);
2067 }
2068 
2069 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2070 /// non-null, then this function will use the specified type if it has to
2071 /// create it (this occurs when we see a definition of the function).
2072 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2073                                                  llvm::Type *Ty,
2074                                                  bool ForVTable,
2075                                                  bool DontDefer,
2076                                               ForDefinition_t IsForDefinition) {
2077   // If there was no specific requested type, just convert it now.
2078   if (!Ty) {
2079     const auto *FD = cast<FunctionDecl>(GD.getDecl());
2080     auto CanonTy = Context.getCanonicalType(FD->getType());
2081     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2082   }
2083 
2084   StringRef MangledName = getMangledName(GD);
2085   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2086                                  /*IsThunk=*/false, llvm::AttributeList(),
2087                                  IsForDefinition);
2088 }
2089 
2090 static const FunctionDecl *
2091 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2092   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2093   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2094 
2095   IdentifierInfo &CII = C.Idents.get(Name);
2096   for (const auto &Result : DC->lookup(&CII))
2097     if (const auto FD = dyn_cast<FunctionDecl>(Result))
2098       return FD;
2099 
2100   if (!C.getLangOpts().CPlusPlus)
2101     return nullptr;
2102 
2103   // Demangle the premangled name from getTerminateFn()
2104   IdentifierInfo &CXXII =
2105       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2106           ? C.Idents.get("terminate")
2107           : C.Idents.get(Name);
2108 
2109   for (const auto &N : {"__cxxabiv1", "std"}) {
2110     IdentifierInfo &NS = C.Idents.get(N);
2111     for (const auto &Result : DC->lookup(&NS)) {
2112       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2113       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2114         for (const auto &Result : LSD->lookup(&NS))
2115           if ((ND = dyn_cast<NamespaceDecl>(Result)))
2116             break;
2117 
2118       if (ND)
2119         for (const auto &Result : ND->lookup(&CXXII))
2120           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2121             return FD;
2122     }
2123   }
2124 
2125   return nullptr;
2126 }
2127 
2128 /// CreateRuntimeFunction - Create a new runtime function with the specified
2129 /// type and name.
2130 llvm::Constant *
2131 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2132                                      llvm::AttributeList ExtraAttrs,
2133                                      bool Local) {
2134   llvm::Constant *C =
2135       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2136                               /*DontDefer=*/false, /*IsThunk=*/false,
2137                               ExtraAttrs);
2138 
2139   if (auto *F = dyn_cast<llvm::Function>(C)) {
2140     if (F->empty()) {
2141       F->setCallingConv(getRuntimeCC());
2142 
2143       if (!Local && getTriple().isOSBinFormatCOFF() &&
2144           !getCodeGenOpts().LTOVisibilityPublicStd) {
2145         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2146         if (!FD || FD->hasAttr<DLLImportAttr>()) {
2147           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2148           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2149         }
2150       }
2151     }
2152   }
2153 
2154   return C;
2155 }
2156 
2157 /// CreateBuiltinFunction - Create a new builtin function with the specified
2158 /// type and name.
2159 llvm::Constant *
2160 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2161                                      llvm::AttributeList ExtraAttrs) {
2162   llvm::Constant *C =
2163       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2164                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2165   if (auto *F = dyn_cast<llvm::Function>(C))
2166     if (F->empty())
2167       F->setCallingConv(getBuiltinCC());
2168   return C;
2169 }
2170 
2171 /// isTypeConstant - Determine whether an object of this type can be emitted
2172 /// as a constant.
2173 ///
2174 /// If ExcludeCtor is true, the duration when the object's constructor runs
2175 /// will not be considered. The caller will need to verify that the object is
2176 /// not written to during its construction.
2177 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2178   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2179     return false;
2180 
2181   if (Context.getLangOpts().CPlusPlus) {
2182     if (const CXXRecordDecl *Record
2183           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2184       return ExcludeCtor && !Record->hasMutableFields() &&
2185              Record->hasTrivialDestructor();
2186   }
2187 
2188   return true;
2189 }
2190 
2191 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2192 /// create and return an llvm GlobalVariable with the specified type.  If there
2193 /// is something in the module with the specified name, return it potentially
2194 /// bitcasted to the right type.
2195 ///
2196 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2197 /// to set the attributes on the global when it is first created.
2198 ///
2199 /// If IsForDefinition is true, it is guranteed that an actual global with
2200 /// type Ty will be returned, not conversion of a variable with the same
2201 /// mangled name but some other type.
2202 llvm::Constant *
2203 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2204                                      llvm::PointerType *Ty,
2205                                      const VarDecl *D,
2206                                      ForDefinition_t IsForDefinition) {
2207   // Lookup the entry, lazily creating it if necessary.
2208   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2209   if (Entry) {
2210     if (WeakRefReferences.erase(Entry)) {
2211       if (D && !D->hasAttr<WeakAttr>())
2212         Entry->setLinkage(llvm::Function::ExternalLinkage);
2213     }
2214 
2215     // Handle dropped DLL attributes.
2216     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2217       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2218 
2219     if (Entry->getType() == Ty)
2220       return Entry;
2221 
2222     // If there are two attempts to define the same mangled name, issue an
2223     // error.
2224     if (IsForDefinition && !Entry->isDeclaration()) {
2225       GlobalDecl OtherGD;
2226       const VarDecl *OtherD;
2227 
2228       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2229       // to make sure that we issue an error only once.
2230       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2231           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2232           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2233           OtherD->hasInit() &&
2234           DiagnosedConflictingDefinitions.insert(D).second) {
2235         getDiags().Report(D->getLocation(),
2236                           diag::err_duplicate_mangled_name);
2237         getDiags().Report(OtherGD.getDecl()->getLocation(),
2238                           diag::note_previous_definition);
2239       }
2240     }
2241 
2242     // Make sure the result is of the correct type.
2243     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2244       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2245 
2246     // (If global is requested for a definition, we always need to create a new
2247     // global, not just return a bitcast.)
2248     if (!IsForDefinition)
2249       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2250   }
2251 
2252   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2253   auto *GV = new llvm::GlobalVariable(
2254       getModule(), Ty->getElementType(), false,
2255       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2256       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2257 
2258   // If we already created a global with the same mangled name (but different
2259   // type) before, take its name and remove it from its parent.
2260   if (Entry) {
2261     GV->takeName(Entry);
2262 
2263     if (!Entry->use_empty()) {
2264       llvm::Constant *NewPtrForOldDecl =
2265           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2266       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2267     }
2268 
2269     Entry->eraseFromParent();
2270   }
2271 
2272   // This is the first use or definition of a mangled name.  If there is a
2273   // deferred decl with this name, remember that we need to emit it at the end
2274   // of the file.
2275   auto DDI = DeferredDecls.find(MangledName);
2276   if (DDI != DeferredDecls.end()) {
2277     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2278     // list, and remove it from DeferredDecls (since we don't need it anymore).
2279     addDeferredDeclToEmit(GV, DDI->second);
2280     DeferredDecls.erase(DDI);
2281   }
2282 
2283   // Handle things which are present even on external declarations.
2284   if (D) {
2285     // FIXME: This code is overly simple and should be merged with other global
2286     // handling.
2287     GV->setConstant(isTypeConstant(D->getType(), false));
2288 
2289     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2290 
2291     setLinkageAndVisibilityForGV(GV, D);
2292 
2293     if (D->getTLSKind()) {
2294       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2295         CXXThreadLocals.push_back(D);
2296       setTLSMode(GV, *D);
2297     }
2298 
2299     // If required by the ABI, treat declarations of static data members with
2300     // inline initializers as definitions.
2301     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2302       EmitGlobalVarDefinition(D);
2303     }
2304 
2305     // Handle XCore specific ABI requirements.
2306     if (getTriple().getArch() == llvm::Triple::xcore &&
2307         D->getLanguageLinkage() == CLanguageLinkage &&
2308         D->getType().isConstant(Context) &&
2309         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2310       GV->setSection(".cp.rodata");
2311   }
2312 
2313   if (AddrSpace != Ty->getAddressSpace())
2314     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2315 
2316   return GV;
2317 }
2318 
2319 llvm::Constant *
2320 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2321                                ForDefinition_t IsForDefinition) {
2322   const Decl *D = GD.getDecl();
2323   if (isa<CXXConstructorDecl>(D))
2324     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2325                                 getFromCtorType(GD.getCtorType()),
2326                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2327                                 /*DontDefer=*/false, IsForDefinition);
2328   else if (isa<CXXDestructorDecl>(D))
2329     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2330                                 getFromDtorType(GD.getDtorType()),
2331                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2332                                 /*DontDefer=*/false, IsForDefinition);
2333   else if (isa<CXXMethodDecl>(D)) {
2334     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2335         cast<CXXMethodDecl>(D));
2336     auto Ty = getTypes().GetFunctionType(*FInfo);
2337     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2338                              IsForDefinition);
2339   } else if (isa<FunctionDecl>(D)) {
2340     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2341     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2342     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2343                              IsForDefinition);
2344   } else
2345     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2346                               IsForDefinition);
2347 }
2348 
2349 llvm::GlobalVariable *
2350 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2351                                       llvm::Type *Ty,
2352                                       llvm::GlobalValue::LinkageTypes Linkage) {
2353   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2354   llvm::GlobalVariable *OldGV = nullptr;
2355 
2356   if (GV) {
2357     // Check if the variable has the right type.
2358     if (GV->getType()->getElementType() == Ty)
2359       return GV;
2360 
2361     // Because C++ name mangling, the only way we can end up with an already
2362     // existing global with the same name is if it has been declared extern "C".
2363     assert(GV->isDeclaration() && "Declaration has wrong type!");
2364     OldGV = GV;
2365   }
2366 
2367   // Create a new variable.
2368   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2369                                 Linkage, nullptr, Name);
2370 
2371   if (OldGV) {
2372     // Replace occurrences of the old variable if needed.
2373     GV->takeName(OldGV);
2374 
2375     if (!OldGV->use_empty()) {
2376       llvm::Constant *NewPtrForOldDecl =
2377       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2378       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2379     }
2380 
2381     OldGV->eraseFromParent();
2382   }
2383 
2384   if (supportsCOMDAT() && GV->isWeakForLinker() &&
2385       !GV->hasAvailableExternallyLinkage())
2386     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2387 
2388   return GV;
2389 }
2390 
2391 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2392 /// given global variable.  If Ty is non-null and if the global doesn't exist,
2393 /// then it will be created with the specified type instead of whatever the
2394 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2395 /// that an actual global with type Ty will be returned, not conversion of a
2396 /// variable with the same mangled name but some other type.
2397 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2398                                                   llvm::Type *Ty,
2399                                            ForDefinition_t IsForDefinition) {
2400   assert(D->hasGlobalStorage() && "Not a global variable");
2401   QualType ASTTy = D->getType();
2402   if (!Ty)
2403     Ty = getTypes().ConvertTypeForMem(ASTTy);
2404 
2405   llvm::PointerType *PTy =
2406     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2407 
2408   StringRef MangledName = getMangledName(D);
2409   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2410 }
2411 
2412 /// CreateRuntimeVariable - Create a new runtime global variable with the
2413 /// specified type and name.
2414 llvm::Constant *
2415 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2416                                      StringRef Name) {
2417   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2418 }
2419 
2420 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2421   assert(!D->getInit() && "Cannot emit definite definitions here!");
2422 
2423   StringRef MangledName = getMangledName(D);
2424   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2425 
2426   // We already have a definition, not declaration, with the same mangled name.
2427   // Emitting of declaration is not required (and actually overwrites emitted
2428   // definition).
2429   if (GV && !GV->isDeclaration())
2430     return;
2431 
2432   // If we have not seen a reference to this variable yet, place it into the
2433   // deferred declarations table to be emitted if needed later.
2434   if (!MustBeEmitted(D) && !GV) {
2435       DeferredDecls[MangledName] = D;
2436       return;
2437   }
2438 
2439   // The tentative definition is the only definition.
2440   EmitGlobalVarDefinition(D);
2441 }
2442 
2443 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2444   return Context.toCharUnitsFromBits(
2445       getDataLayout().getTypeStoreSizeInBits(Ty));
2446 }
2447 
2448 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2449                                                  unsigned AddrSpace) {
2450   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2451     if (D->hasAttr<CUDAConstantAttr>())
2452       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2453     else if (D->hasAttr<CUDASharedAttr>())
2454       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2455     else
2456       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2457   }
2458 
2459   return AddrSpace;
2460 }
2461 
2462 template<typename SomeDecl>
2463 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2464                                                llvm::GlobalValue *GV) {
2465   if (!getLangOpts().CPlusPlus)
2466     return;
2467 
2468   // Must have 'used' attribute, or else inline assembly can't rely on
2469   // the name existing.
2470   if (!D->template hasAttr<UsedAttr>())
2471     return;
2472 
2473   // Must have internal linkage and an ordinary name.
2474   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2475     return;
2476 
2477   // Must be in an extern "C" context. Entities declared directly within
2478   // a record are not extern "C" even if the record is in such a context.
2479   const SomeDecl *First = D->getFirstDecl();
2480   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2481     return;
2482 
2483   // OK, this is an internal linkage entity inside an extern "C" linkage
2484   // specification. Make a note of that so we can give it the "expected"
2485   // mangled name if nothing else is using that name.
2486   std::pair<StaticExternCMap::iterator, bool> R =
2487       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2488 
2489   // If we have multiple internal linkage entities with the same name
2490   // in extern "C" regions, none of them gets that name.
2491   if (!R.second)
2492     R.first->second = nullptr;
2493 }
2494 
2495 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2496   if (!CGM.supportsCOMDAT())
2497     return false;
2498 
2499   if (D.hasAttr<SelectAnyAttr>())
2500     return true;
2501 
2502   GVALinkage Linkage;
2503   if (auto *VD = dyn_cast<VarDecl>(&D))
2504     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2505   else
2506     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2507 
2508   switch (Linkage) {
2509   case GVA_Internal:
2510   case GVA_AvailableExternally:
2511   case GVA_StrongExternal:
2512     return false;
2513   case GVA_DiscardableODR:
2514   case GVA_StrongODR:
2515     return true;
2516   }
2517   llvm_unreachable("No such linkage");
2518 }
2519 
2520 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2521                                           llvm::GlobalObject &GO) {
2522   if (!shouldBeInCOMDAT(*this, D))
2523     return;
2524   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2525 }
2526 
2527 /// Pass IsTentative as true if you want to create a tentative definition.
2528 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2529                                             bool IsTentative) {
2530   // OpenCL global variables of sampler type are translated to function calls,
2531   // therefore no need to be translated.
2532   QualType ASTTy = D->getType();
2533   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2534     return;
2535 
2536   llvm::Constant *Init = nullptr;
2537   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2538   bool NeedsGlobalCtor = false;
2539   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2540 
2541   const VarDecl *InitDecl;
2542   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2543 
2544   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2545   // as part of their declaration."  Sema has already checked for
2546   // error cases, so we just need to set Init to UndefValue.
2547   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2548       D->hasAttr<CUDASharedAttr>())
2549     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2550   else if (!InitExpr) {
2551     // This is a tentative definition; tentative definitions are
2552     // implicitly initialized with { 0 }.
2553     //
2554     // Note that tentative definitions are only emitted at the end of
2555     // a translation unit, so they should never have incomplete
2556     // type. In addition, EmitTentativeDefinition makes sure that we
2557     // never attempt to emit a tentative definition if a real one
2558     // exists. A use may still exists, however, so we still may need
2559     // to do a RAUW.
2560     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2561     Init = EmitNullConstant(D->getType());
2562   } else {
2563     initializedGlobalDecl = GlobalDecl(D);
2564     Init = EmitConstantInit(*InitDecl);
2565 
2566     if (!Init) {
2567       QualType T = InitExpr->getType();
2568       if (D->getType()->isReferenceType())
2569         T = D->getType();
2570 
2571       if (getLangOpts().CPlusPlus) {
2572         Init = EmitNullConstant(T);
2573         NeedsGlobalCtor = true;
2574       } else {
2575         ErrorUnsupported(D, "static initializer");
2576         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2577       }
2578     } else {
2579       // We don't need an initializer, so remove the entry for the delayed
2580       // initializer position (just in case this entry was delayed) if we
2581       // also don't need to register a destructor.
2582       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2583         DelayedCXXInitPosition.erase(D);
2584     }
2585   }
2586 
2587   llvm::Type* InitType = Init->getType();
2588   llvm::Constant *Entry =
2589       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2590 
2591   // Strip off a bitcast if we got one back.
2592   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2593     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2594            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2595            // All zero index gep.
2596            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2597     Entry = CE->getOperand(0);
2598   }
2599 
2600   // Entry is now either a Function or GlobalVariable.
2601   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2602 
2603   // We have a definition after a declaration with the wrong type.
2604   // We must make a new GlobalVariable* and update everything that used OldGV
2605   // (a declaration or tentative definition) with the new GlobalVariable*
2606   // (which will be a definition).
2607   //
2608   // This happens if there is a prototype for a global (e.g.
2609   // "extern int x[];") and then a definition of a different type (e.g.
2610   // "int x[10];"). This also happens when an initializer has a different type
2611   // from the type of the global (this happens with unions).
2612   if (!GV ||
2613       GV->getType()->getElementType() != InitType ||
2614       GV->getType()->getAddressSpace() !=
2615        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2616 
2617     // Move the old entry aside so that we'll create a new one.
2618     Entry->setName(StringRef());
2619 
2620     // Make a new global with the correct type, this is now guaranteed to work.
2621     GV = cast<llvm::GlobalVariable>(
2622         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2623 
2624     // Replace all uses of the old global with the new global
2625     llvm::Constant *NewPtrForOldDecl =
2626         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2627     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2628 
2629     // Erase the old global, since it is no longer used.
2630     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2631   }
2632 
2633   MaybeHandleStaticInExternC(D, GV);
2634 
2635   if (D->hasAttr<AnnotateAttr>())
2636     AddGlobalAnnotations(D, GV);
2637 
2638   // Set the llvm linkage type as appropriate.
2639   llvm::GlobalValue::LinkageTypes Linkage =
2640       getLLVMLinkageVarDefinition(D, GV->isConstant());
2641 
2642   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2643   // the device. [...]"
2644   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2645   // __device__, declares a variable that: [...]
2646   // Is accessible from all the threads within the grid and from the host
2647   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2648   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2649   if (GV && LangOpts.CUDA) {
2650     if (LangOpts.CUDAIsDevice) {
2651       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2652         GV->setExternallyInitialized(true);
2653     } else {
2654       // Host-side shadows of external declarations of device-side
2655       // global variables become internal definitions. These have to
2656       // be internal in order to prevent name conflicts with global
2657       // host variables with the same name in a different TUs.
2658       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2659         Linkage = llvm::GlobalValue::InternalLinkage;
2660 
2661         // Shadow variables and their properties must be registered
2662         // with CUDA runtime.
2663         unsigned Flags = 0;
2664         if (!D->hasDefinition())
2665           Flags |= CGCUDARuntime::ExternDeviceVar;
2666         if (D->hasAttr<CUDAConstantAttr>())
2667           Flags |= CGCUDARuntime::ConstantDeviceVar;
2668         getCUDARuntime().registerDeviceVar(*GV, Flags);
2669       } else if (D->hasAttr<CUDASharedAttr>())
2670         // __shared__ variables are odd. Shadows do get created, but
2671         // they are not registered with the CUDA runtime, so they
2672         // can't really be used to access their device-side
2673         // counterparts. It's not clear yet whether it's nvcc's bug or
2674         // a feature, but we've got to do the same for compatibility.
2675         Linkage = llvm::GlobalValue::InternalLinkage;
2676     }
2677   }
2678   GV->setInitializer(Init);
2679 
2680   // If it is safe to mark the global 'constant', do so now.
2681   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2682                   isTypeConstant(D->getType(), true));
2683 
2684   // If it is in a read-only section, mark it 'constant'.
2685   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2686     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2687     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2688       GV->setConstant(true);
2689   }
2690 
2691   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2692 
2693 
2694   // On Darwin, if the normal linkage of a C++ thread_local variable is
2695   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2696   // copies within a linkage unit; otherwise, the backing variable has
2697   // internal linkage and all accesses should just be calls to the
2698   // Itanium-specified entry point, which has the normal linkage of the
2699   // variable. This is to preserve the ability to change the implementation
2700   // behind the scenes.
2701   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2702       Context.getTargetInfo().getTriple().isOSDarwin() &&
2703       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2704       !llvm::GlobalVariable::isWeakLinkage(Linkage))
2705     Linkage = llvm::GlobalValue::InternalLinkage;
2706 
2707   GV->setLinkage(Linkage);
2708   if (D->hasAttr<DLLImportAttr>())
2709     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2710   else if (D->hasAttr<DLLExportAttr>())
2711     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2712   else
2713     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2714 
2715   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2716     // common vars aren't constant even if declared const.
2717     GV->setConstant(false);
2718     // Tentative definition of global variables may be initialized with
2719     // non-zero null pointers. In this case they should have weak linkage
2720     // since common linkage must have zero initializer and must not have
2721     // explicit section therefore cannot have non-zero initial value.
2722     if (!GV->getInitializer()->isNullValue())
2723       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2724   }
2725 
2726   setNonAliasAttributes(D, GV);
2727 
2728   if (D->getTLSKind() && !GV->isThreadLocal()) {
2729     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2730       CXXThreadLocals.push_back(D);
2731     setTLSMode(GV, *D);
2732   }
2733 
2734   maybeSetTrivialComdat(*D, *GV);
2735 
2736   // Emit the initializer function if necessary.
2737   if (NeedsGlobalCtor || NeedsGlobalDtor)
2738     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2739 
2740   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2741 
2742   // Emit global variable debug information.
2743   if (CGDebugInfo *DI = getModuleDebugInfo())
2744     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2745       DI->EmitGlobalVariable(GV, D);
2746 }
2747 
2748 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2749                                       CodeGenModule &CGM, const VarDecl *D,
2750                                       bool NoCommon) {
2751   // Don't give variables common linkage if -fno-common was specified unless it
2752   // was overridden by a NoCommon attribute.
2753   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2754     return true;
2755 
2756   // C11 6.9.2/2:
2757   //   A declaration of an identifier for an object that has file scope without
2758   //   an initializer, and without a storage-class specifier or with the
2759   //   storage-class specifier static, constitutes a tentative definition.
2760   if (D->getInit() || D->hasExternalStorage())
2761     return true;
2762 
2763   // A variable cannot be both common and exist in a section.
2764   if (D->hasAttr<SectionAttr>())
2765     return true;
2766 
2767   // Thread local vars aren't considered common linkage.
2768   if (D->getTLSKind())
2769     return true;
2770 
2771   // Tentative definitions marked with WeakImportAttr are true definitions.
2772   if (D->hasAttr<WeakImportAttr>())
2773     return true;
2774 
2775   // A variable cannot be both common and exist in a comdat.
2776   if (shouldBeInCOMDAT(CGM, *D))
2777     return true;
2778 
2779   // Declarations with a required alignment do not have common linkage in MSVC
2780   // mode.
2781   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2782     if (D->hasAttr<AlignedAttr>())
2783       return true;
2784     QualType VarType = D->getType();
2785     if (Context.isAlignmentRequired(VarType))
2786       return true;
2787 
2788     if (const auto *RT = VarType->getAs<RecordType>()) {
2789       const RecordDecl *RD = RT->getDecl();
2790       for (const FieldDecl *FD : RD->fields()) {
2791         if (FD->isBitField())
2792           continue;
2793         if (FD->hasAttr<AlignedAttr>())
2794           return true;
2795         if (Context.isAlignmentRequired(FD->getType()))
2796           return true;
2797       }
2798     }
2799   }
2800 
2801   return false;
2802 }
2803 
2804 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2805     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2806   if (Linkage == GVA_Internal)
2807     return llvm::Function::InternalLinkage;
2808 
2809   if (D->hasAttr<WeakAttr>()) {
2810     if (IsConstantVariable)
2811       return llvm::GlobalVariable::WeakODRLinkage;
2812     else
2813       return llvm::GlobalVariable::WeakAnyLinkage;
2814   }
2815 
2816   // We are guaranteed to have a strong definition somewhere else,
2817   // so we can use available_externally linkage.
2818   if (Linkage == GVA_AvailableExternally)
2819     return llvm::GlobalValue::AvailableExternallyLinkage;
2820 
2821   // Note that Apple's kernel linker doesn't support symbol
2822   // coalescing, so we need to avoid linkonce and weak linkages there.
2823   // Normally, this means we just map to internal, but for explicit
2824   // instantiations we'll map to external.
2825 
2826   // In C++, the compiler has to emit a definition in every translation unit
2827   // that references the function.  We should use linkonce_odr because
2828   // a) if all references in this translation unit are optimized away, we
2829   // don't need to codegen it.  b) if the function persists, it needs to be
2830   // merged with other definitions. c) C++ has the ODR, so we know the
2831   // definition is dependable.
2832   if (Linkage == GVA_DiscardableODR)
2833     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2834                                             : llvm::Function::InternalLinkage;
2835 
2836   // An explicit instantiation of a template has weak linkage, since
2837   // explicit instantiations can occur in multiple translation units
2838   // and must all be equivalent. However, we are not allowed to
2839   // throw away these explicit instantiations.
2840   //
2841   // We don't currently support CUDA device code spread out across multiple TUs,
2842   // so say that CUDA templates are either external (for kernels) or internal.
2843   // This lets llvm perform aggressive inter-procedural optimizations.
2844   if (Linkage == GVA_StrongODR) {
2845     if (Context.getLangOpts().AppleKext)
2846       return llvm::Function::ExternalLinkage;
2847     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2848       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2849                                           : llvm::Function::InternalLinkage;
2850     return llvm::Function::WeakODRLinkage;
2851   }
2852 
2853   // C++ doesn't have tentative definitions and thus cannot have common
2854   // linkage.
2855   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2856       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2857                                  CodeGenOpts.NoCommon))
2858     return llvm::GlobalVariable::CommonLinkage;
2859 
2860   // selectany symbols are externally visible, so use weak instead of
2861   // linkonce.  MSVC optimizes away references to const selectany globals, so
2862   // all definitions should be the same and ODR linkage should be used.
2863   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2864   if (D->hasAttr<SelectAnyAttr>())
2865     return llvm::GlobalVariable::WeakODRLinkage;
2866 
2867   // Otherwise, we have strong external linkage.
2868   assert(Linkage == GVA_StrongExternal);
2869   return llvm::GlobalVariable::ExternalLinkage;
2870 }
2871 
2872 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2873     const VarDecl *VD, bool IsConstant) {
2874   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2875   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2876 }
2877 
2878 /// Replace the uses of a function that was declared with a non-proto type.
2879 /// We want to silently drop extra arguments from call sites
2880 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2881                                           llvm::Function *newFn) {
2882   // Fast path.
2883   if (old->use_empty()) return;
2884 
2885   llvm::Type *newRetTy = newFn->getReturnType();
2886   SmallVector<llvm::Value*, 4> newArgs;
2887   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2888 
2889   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2890          ui != ue; ) {
2891     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2892     llvm::User *user = use->getUser();
2893 
2894     // Recognize and replace uses of bitcasts.  Most calls to
2895     // unprototyped functions will use bitcasts.
2896     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2897       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2898         replaceUsesOfNonProtoConstant(bitcast, newFn);
2899       continue;
2900     }
2901 
2902     // Recognize calls to the function.
2903     llvm::CallSite callSite(user);
2904     if (!callSite) continue;
2905     if (!callSite.isCallee(&*use)) continue;
2906 
2907     // If the return types don't match exactly, then we can't
2908     // transform this call unless it's dead.
2909     if (callSite->getType() != newRetTy && !callSite->use_empty())
2910       continue;
2911 
2912     // Get the call site's attribute list.
2913     SmallVector<llvm::AttributeList, 8> newAttrs;
2914     llvm::AttributeList oldAttrs = callSite.getAttributes();
2915 
2916     // Collect any return attributes from the call.
2917     if (oldAttrs.hasAttributes(llvm::AttributeList::ReturnIndex))
2918       newAttrs.push_back(llvm::AttributeList::get(newFn->getContext(),
2919                                                   oldAttrs.getRetAttributes()));
2920 
2921     // If the function was passed too few arguments, don't transform.
2922     unsigned newNumArgs = newFn->arg_size();
2923     if (callSite.arg_size() < newNumArgs) continue;
2924 
2925     // If extra arguments were passed, we silently drop them.
2926     // If any of the types mismatch, we don't transform.
2927     unsigned argNo = 0;
2928     bool dontTransform = false;
2929     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2930            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2931       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2932         dontTransform = true;
2933         break;
2934       }
2935 
2936       // Add any parameter attributes.
2937       if (oldAttrs.hasAttributes(argNo + 1))
2938         newAttrs.push_back(llvm::AttributeList::get(
2939             newFn->getContext(), oldAttrs.getParamAttributes(argNo + 1)));
2940     }
2941     if (dontTransform)
2942       continue;
2943 
2944     if (oldAttrs.hasAttributes(llvm::AttributeList::FunctionIndex))
2945       newAttrs.push_back(llvm::AttributeList::get(newFn->getContext(),
2946                                                   oldAttrs.getFnAttributes()));
2947 
2948     // Okay, we can transform this.  Create the new call instruction and copy
2949     // over the required information.
2950     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2951 
2952     // Copy over any operand bundles.
2953     callSite.getOperandBundlesAsDefs(newBundles);
2954 
2955     llvm::CallSite newCall;
2956     if (callSite.isCall()) {
2957       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2958                                        callSite.getInstruction());
2959     } else {
2960       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2961       newCall = llvm::InvokeInst::Create(newFn,
2962                                          oldInvoke->getNormalDest(),
2963                                          oldInvoke->getUnwindDest(),
2964                                          newArgs, newBundles, "",
2965                                          callSite.getInstruction());
2966     }
2967     newArgs.clear(); // for the next iteration
2968 
2969     if (!newCall->getType()->isVoidTy())
2970       newCall->takeName(callSite.getInstruction());
2971     newCall.setAttributes(
2972         llvm::AttributeList::get(newFn->getContext(), newAttrs));
2973     newCall.setCallingConv(callSite.getCallingConv());
2974 
2975     // Finally, remove the old call, replacing any uses with the new one.
2976     if (!callSite->use_empty())
2977       callSite->replaceAllUsesWith(newCall.getInstruction());
2978 
2979     // Copy debug location attached to CI.
2980     if (callSite->getDebugLoc())
2981       newCall->setDebugLoc(callSite->getDebugLoc());
2982 
2983     callSite->eraseFromParent();
2984   }
2985 }
2986 
2987 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2988 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2989 /// existing call uses of the old function in the module, this adjusts them to
2990 /// call the new function directly.
2991 ///
2992 /// This is not just a cleanup: the always_inline pass requires direct calls to
2993 /// functions to be able to inline them.  If there is a bitcast in the way, it
2994 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2995 /// run at -O0.
2996 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2997                                                       llvm::Function *NewFn) {
2998   // If we're redefining a global as a function, don't transform it.
2999   if (!isa<llvm::Function>(Old)) return;
3000 
3001   replaceUsesOfNonProtoConstant(Old, NewFn);
3002 }
3003 
3004 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3005   auto DK = VD->isThisDeclarationADefinition();
3006   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3007     return;
3008 
3009   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3010   // If we have a definition, this might be a deferred decl. If the
3011   // instantiation is explicit, make sure we emit it at the end.
3012   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3013     GetAddrOfGlobalVar(VD);
3014 
3015   EmitTopLevelDecl(VD);
3016 }
3017 
3018 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3019                                                  llvm::GlobalValue *GV) {
3020   const auto *D = cast<FunctionDecl>(GD.getDecl());
3021 
3022   // Compute the function info and LLVM type.
3023   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3024   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3025 
3026   // Get or create the prototype for the function.
3027   if (!GV || (GV->getType()->getElementType() != Ty))
3028     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3029                                                    /*DontDefer=*/true,
3030                                                    ForDefinition));
3031 
3032   // Already emitted.
3033   if (!GV->isDeclaration())
3034     return;
3035 
3036   // We need to set linkage and visibility on the function before
3037   // generating code for it because various parts of IR generation
3038   // want to propagate this information down (e.g. to local static
3039   // declarations).
3040   auto *Fn = cast<llvm::Function>(GV);
3041   setFunctionLinkage(GD, Fn);
3042   setFunctionDLLStorageClass(GD, Fn);
3043 
3044   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3045   setGlobalVisibility(Fn, D);
3046 
3047   MaybeHandleStaticInExternC(D, Fn);
3048 
3049   maybeSetTrivialComdat(*D, *Fn);
3050 
3051   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3052 
3053   setFunctionDefinitionAttributes(D, Fn);
3054   SetLLVMFunctionAttributesForDefinition(D, Fn);
3055 
3056   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3057     AddGlobalCtor(Fn, CA->getPriority());
3058   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3059     AddGlobalDtor(Fn, DA->getPriority());
3060   if (D->hasAttr<AnnotateAttr>())
3061     AddGlobalAnnotations(D, Fn);
3062 }
3063 
3064 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3065   const auto *D = cast<ValueDecl>(GD.getDecl());
3066   const AliasAttr *AA = D->getAttr<AliasAttr>();
3067   assert(AA && "Not an alias?");
3068 
3069   StringRef MangledName = getMangledName(GD);
3070 
3071   if (AA->getAliasee() == MangledName) {
3072     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3073     return;
3074   }
3075 
3076   // If there is a definition in the module, then it wins over the alias.
3077   // This is dubious, but allow it to be safe.  Just ignore the alias.
3078   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3079   if (Entry && !Entry->isDeclaration())
3080     return;
3081 
3082   Aliases.push_back(GD);
3083 
3084   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3085 
3086   // Create a reference to the named value.  This ensures that it is emitted
3087   // if a deferred decl.
3088   llvm::Constant *Aliasee;
3089   if (isa<llvm::FunctionType>(DeclTy))
3090     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3091                                       /*ForVTable=*/false);
3092   else
3093     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3094                                     llvm::PointerType::getUnqual(DeclTy),
3095                                     /*D=*/nullptr);
3096 
3097   // Create the new alias itself, but don't set a name yet.
3098   auto *GA = llvm::GlobalAlias::create(
3099       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3100 
3101   if (Entry) {
3102     if (GA->getAliasee() == Entry) {
3103       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3104       return;
3105     }
3106 
3107     assert(Entry->isDeclaration());
3108 
3109     // If there is a declaration in the module, then we had an extern followed
3110     // by the alias, as in:
3111     //   extern int test6();
3112     //   ...
3113     //   int test6() __attribute__((alias("test7")));
3114     //
3115     // Remove it and replace uses of it with the alias.
3116     GA->takeName(Entry);
3117 
3118     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3119                                                           Entry->getType()));
3120     Entry->eraseFromParent();
3121   } else {
3122     GA->setName(MangledName);
3123   }
3124 
3125   // Set attributes which are particular to an alias; this is a
3126   // specialization of the attributes which may be set on a global
3127   // variable/function.
3128   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3129       D->isWeakImported()) {
3130     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3131   }
3132 
3133   if (const auto *VD = dyn_cast<VarDecl>(D))
3134     if (VD->getTLSKind())
3135       setTLSMode(GA, *VD);
3136 
3137   setAliasAttributes(D, GA);
3138 }
3139 
3140 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3141   const auto *D = cast<ValueDecl>(GD.getDecl());
3142   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3143   assert(IFA && "Not an ifunc?");
3144 
3145   StringRef MangledName = getMangledName(GD);
3146 
3147   if (IFA->getResolver() == MangledName) {
3148     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3149     return;
3150   }
3151 
3152   // Report an error if some definition overrides ifunc.
3153   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3154   if (Entry && !Entry->isDeclaration()) {
3155     GlobalDecl OtherGD;
3156     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3157         DiagnosedConflictingDefinitions.insert(GD).second) {
3158       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3159       Diags.Report(OtherGD.getDecl()->getLocation(),
3160                    diag::note_previous_definition);
3161     }
3162     return;
3163   }
3164 
3165   Aliases.push_back(GD);
3166 
3167   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3168   llvm::Constant *Resolver =
3169       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3170                               /*ForVTable=*/false);
3171   llvm::GlobalIFunc *GIF =
3172       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3173                                 "", Resolver, &getModule());
3174   if (Entry) {
3175     if (GIF->getResolver() == Entry) {
3176       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3177       return;
3178     }
3179     assert(Entry->isDeclaration());
3180 
3181     // If there is a declaration in the module, then we had an extern followed
3182     // by the ifunc, as in:
3183     //   extern int test();
3184     //   ...
3185     //   int test() __attribute__((ifunc("resolver")));
3186     //
3187     // Remove it and replace uses of it with the ifunc.
3188     GIF->takeName(Entry);
3189 
3190     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3191                                                           Entry->getType()));
3192     Entry->eraseFromParent();
3193   } else
3194     GIF->setName(MangledName);
3195 
3196   SetCommonAttributes(D, GIF);
3197 }
3198 
3199 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3200                                             ArrayRef<llvm::Type*> Tys) {
3201   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3202                                          Tys);
3203 }
3204 
3205 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3206 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3207                          const StringLiteral *Literal, bool TargetIsLSB,
3208                          bool &IsUTF16, unsigned &StringLength) {
3209   StringRef String = Literal->getString();
3210   unsigned NumBytes = String.size();
3211 
3212   // Check for simple case.
3213   if (!Literal->containsNonAsciiOrNull()) {
3214     StringLength = NumBytes;
3215     return *Map.insert(std::make_pair(String, nullptr)).first;
3216   }
3217 
3218   // Otherwise, convert the UTF8 literals into a string of shorts.
3219   IsUTF16 = true;
3220 
3221   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3222   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3223   llvm::UTF16 *ToPtr = &ToBuf[0];
3224 
3225   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3226                                  ToPtr + NumBytes, llvm::strictConversion);
3227 
3228   // ConvertUTF8toUTF16 returns the length in ToPtr.
3229   StringLength = ToPtr - &ToBuf[0];
3230 
3231   // Add an explicit null.
3232   *ToPtr = 0;
3233   return *Map.insert(std::make_pair(
3234                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3235                                    (StringLength + 1) * 2),
3236                          nullptr)).first;
3237 }
3238 
3239 ConstantAddress
3240 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3241   unsigned StringLength = 0;
3242   bool isUTF16 = false;
3243   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3244       GetConstantCFStringEntry(CFConstantStringMap, Literal,
3245                                getDataLayout().isLittleEndian(), isUTF16,
3246                                StringLength);
3247 
3248   if (auto *C = Entry.second)
3249     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3250 
3251   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3252   llvm::Constant *Zeros[] = { Zero, Zero };
3253 
3254   // If we don't already have it, get __CFConstantStringClassReference.
3255   if (!CFConstantStringClassRef) {
3256     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3257     Ty = llvm::ArrayType::get(Ty, 0);
3258     llvm::Constant *GV =
3259         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3260 
3261     if (getTriple().isOSBinFormatCOFF()) {
3262       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3263       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3264       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3265       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3266 
3267       const VarDecl *VD = nullptr;
3268       for (const auto &Result : DC->lookup(&II))
3269         if ((VD = dyn_cast<VarDecl>(Result)))
3270           break;
3271 
3272       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3273         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3274         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3275       } else {
3276         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3277         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3278       }
3279     }
3280 
3281     // Decay array -> ptr
3282     CFConstantStringClassRef =
3283         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3284   }
3285 
3286   QualType CFTy = getContext().getCFConstantStringType();
3287 
3288   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3289 
3290   ConstantInitBuilder Builder(*this);
3291   auto Fields = Builder.beginStruct(STy);
3292 
3293   // Class pointer.
3294   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3295 
3296   // Flags.
3297   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3298 
3299   // String pointer.
3300   llvm::Constant *C = nullptr;
3301   if (isUTF16) {
3302     auto Arr = llvm::makeArrayRef(
3303         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3304         Entry.first().size() / 2);
3305     C = llvm::ConstantDataArray::get(VMContext, Arr);
3306   } else {
3307     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3308   }
3309 
3310   // Note: -fwritable-strings doesn't make the backing store strings of
3311   // CFStrings writable. (See <rdar://problem/10657500>)
3312   auto *GV =
3313       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3314                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3315   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3316   // Don't enforce the target's minimum global alignment, since the only use
3317   // of the string is via this class initializer.
3318   CharUnits Align = isUTF16
3319                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3320                         : getContext().getTypeAlignInChars(getContext().CharTy);
3321   GV->setAlignment(Align.getQuantity());
3322 
3323   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3324   // Without it LLVM can merge the string with a non unnamed_addr one during
3325   // LTO.  Doing that changes the section it ends in, which surprises ld64.
3326   if (getTriple().isOSBinFormatMachO())
3327     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3328                            : "__TEXT,__cstring,cstring_literals");
3329 
3330   // String.
3331   llvm::Constant *Str =
3332       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3333 
3334   if (isUTF16)
3335     // Cast the UTF16 string to the correct type.
3336     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3337   Fields.add(Str);
3338 
3339   // String length.
3340   auto Ty = getTypes().ConvertType(getContext().LongTy);
3341   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3342 
3343   CharUnits Alignment = getPointerAlign();
3344 
3345   // The struct.
3346   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3347                                     /*isConstant=*/false,
3348                                     llvm::GlobalVariable::PrivateLinkage);
3349   switch (getTriple().getObjectFormat()) {
3350   case llvm::Triple::UnknownObjectFormat:
3351     llvm_unreachable("unknown file format");
3352   case llvm::Triple::COFF:
3353   case llvm::Triple::ELF:
3354   case llvm::Triple::Wasm:
3355     GV->setSection("cfstring");
3356     break;
3357   case llvm::Triple::MachO:
3358     GV->setSection("__DATA,__cfstring");
3359     break;
3360   }
3361   Entry.second = GV;
3362 
3363   return ConstantAddress(GV, Alignment);
3364 }
3365 
3366 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3367   if (ObjCFastEnumerationStateType.isNull()) {
3368     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3369     D->startDefinition();
3370 
3371     QualType FieldTypes[] = {
3372       Context.UnsignedLongTy,
3373       Context.getPointerType(Context.getObjCIdType()),
3374       Context.getPointerType(Context.UnsignedLongTy),
3375       Context.getConstantArrayType(Context.UnsignedLongTy,
3376                            llvm::APInt(32, 5), ArrayType::Normal, 0)
3377     };
3378 
3379     for (size_t i = 0; i < 4; ++i) {
3380       FieldDecl *Field = FieldDecl::Create(Context,
3381                                            D,
3382                                            SourceLocation(),
3383                                            SourceLocation(), nullptr,
3384                                            FieldTypes[i], /*TInfo=*/nullptr,
3385                                            /*BitWidth=*/nullptr,
3386                                            /*Mutable=*/false,
3387                                            ICIS_NoInit);
3388       Field->setAccess(AS_public);
3389       D->addDecl(Field);
3390     }
3391 
3392     D->completeDefinition();
3393     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3394   }
3395 
3396   return ObjCFastEnumerationStateType;
3397 }
3398 
3399 llvm::Constant *
3400 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3401   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3402 
3403   // Don't emit it as the address of the string, emit the string data itself
3404   // as an inline array.
3405   if (E->getCharByteWidth() == 1) {
3406     SmallString<64> Str(E->getString());
3407 
3408     // Resize the string to the right size, which is indicated by its type.
3409     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3410     Str.resize(CAT->getSize().getZExtValue());
3411     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3412   }
3413 
3414   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3415   llvm::Type *ElemTy = AType->getElementType();
3416   unsigned NumElements = AType->getNumElements();
3417 
3418   // Wide strings have either 2-byte or 4-byte elements.
3419   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3420     SmallVector<uint16_t, 32> Elements;
3421     Elements.reserve(NumElements);
3422 
3423     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3424       Elements.push_back(E->getCodeUnit(i));
3425     Elements.resize(NumElements);
3426     return llvm::ConstantDataArray::get(VMContext, Elements);
3427   }
3428 
3429   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3430   SmallVector<uint32_t, 32> Elements;
3431   Elements.reserve(NumElements);
3432 
3433   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3434     Elements.push_back(E->getCodeUnit(i));
3435   Elements.resize(NumElements);
3436   return llvm::ConstantDataArray::get(VMContext, Elements);
3437 }
3438 
3439 static llvm::GlobalVariable *
3440 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3441                       CodeGenModule &CGM, StringRef GlobalName,
3442                       CharUnits Alignment) {
3443   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3444   unsigned AddrSpace = 0;
3445   if (CGM.getLangOpts().OpenCL)
3446     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3447 
3448   llvm::Module &M = CGM.getModule();
3449   // Create a global variable for this string
3450   auto *GV = new llvm::GlobalVariable(
3451       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3452       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3453   GV->setAlignment(Alignment.getQuantity());
3454   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3455   if (GV->isWeakForLinker()) {
3456     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3457     GV->setComdat(M.getOrInsertComdat(GV->getName()));
3458   }
3459 
3460   return GV;
3461 }
3462 
3463 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3464 /// constant array for the given string literal.
3465 ConstantAddress
3466 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3467                                                   StringRef Name) {
3468   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3469 
3470   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3471   llvm::GlobalVariable **Entry = nullptr;
3472   if (!LangOpts.WritableStrings) {
3473     Entry = &ConstantStringMap[C];
3474     if (auto GV = *Entry) {
3475       if (Alignment.getQuantity() > GV->getAlignment())
3476         GV->setAlignment(Alignment.getQuantity());
3477       return ConstantAddress(GV, Alignment);
3478     }
3479   }
3480 
3481   SmallString<256> MangledNameBuffer;
3482   StringRef GlobalVariableName;
3483   llvm::GlobalValue::LinkageTypes LT;
3484 
3485   // Mangle the string literal if the ABI allows for it.  However, we cannot
3486   // do this if  we are compiling with ASan or -fwritable-strings because they
3487   // rely on strings having normal linkage.
3488   if (!LangOpts.WritableStrings &&
3489       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3490       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3491     llvm::raw_svector_ostream Out(MangledNameBuffer);
3492     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3493 
3494     LT = llvm::GlobalValue::LinkOnceODRLinkage;
3495     GlobalVariableName = MangledNameBuffer;
3496   } else {
3497     LT = llvm::GlobalValue::PrivateLinkage;
3498     GlobalVariableName = Name;
3499   }
3500 
3501   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3502   if (Entry)
3503     *Entry = GV;
3504 
3505   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3506                                   QualType());
3507   return ConstantAddress(GV, Alignment);
3508 }
3509 
3510 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3511 /// array for the given ObjCEncodeExpr node.
3512 ConstantAddress
3513 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3514   std::string Str;
3515   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3516 
3517   return GetAddrOfConstantCString(Str);
3518 }
3519 
3520 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3521 /// the literal and a terminating '\0' character.
3522 /// The result has pointer to array type.
3523 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3524     const std::string &Str, const char *GlobalName) {
3525   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3526   CharUnits Alignment =
3527     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3528 
3529   llvm::Constant *C =
3530       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3531 
3532   // Don't share any string literals if strings aren't constant.
3533   llvm::GlobalVariable **Entry = nullptr;
3534   if (!LangOpts.WritableStrings) {
3535     Entry = &ConstantStringMap[C];
3536     if (auto GV = *Entry) {
3537       if (Alignment.getQuantity() > GV->getAlignment())
3538         GV->setAlignment(Alignment.getQuantity());
3539       return ConstantAddress(GV, Alignment);
3540     }
3541   }
3542 
3543   // Get the default prefix if a name wasn't specified.
3544   if (!GlobalName)
3545     GlobalName = ".str";
3546   // Create a global variable for this.
3547   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3548                                   GlobalName, Alignment);
3549   if (Entry)
3550     *Entry = GV;
3551   return ConstantAddress(GV, Alignment);
3552 }
3553 
3554 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3555     const MaterializeTemporaryExpr *E, const Expr *Init) {
3556   assert((E->getStorageDuration() == SD_Static ||
3557           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3558   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3559 
3560   // If we're not materializing a subobject of the temporary, keep the
3561   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3562   QualType MaterializedType = Init->getType();
3563   if (Init == E->GetTemporaryExpr())
3564     MaterializedType = E->getType();
3565 
3566   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3567 
3568   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3569     return ConstantAddress(Slot, Align);
3570 
3571   // FIXME: If an externally-visible declaration extends multiple temporaries,
3572   // we need to give each temporary the same name in every translation unit (and
3573   // we also need to make the temporaries externally-visible).
3574   SmallString<256> Name;
3575   llvm::raw_svector_ostream Out(Name);
3576   getCXXABI().getMangleContext().mangleReferenceTemporary(
3577       VD, E->getManglingNumber(), Out);
3578 
3579   APValue *Value = nullptr;
3580   if (E->getStorageDuration() == SD_Static) {
3581     // We might have a cached constant initializer for this temporary. Note
3582     // that this might have a different value from the value computed by
3583     // evaluating the initializer if the surrounding constant expression
3584     // modifies the temporary.
3585     Value = getContext().getMaterializedTemporaryValue(E, false);
3586     if (Value && Value->isUninit())
3587       Value = nullptr;
3588   }
3589 
3590   // Try evaluating it now, it might have a constant initializer.
3591   Expr::EvalResult EvalResult;
3592   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3593       !EvalResult.hasSideEffects())
3594     Value = &EvalResult.Val;
3595 
3596   llvm::Constant *InitialValue = nullptr;
3597   bool Constant = false;
3598   llvm::Type *Type;
3599   if (Value) {
3600     // The temporary has a constant initializer, use it.
3601     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3602     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3603     Type = InitialValue->getType();
3604   } else {
3605     // No initializer, the initialization will be provided when we
3606     // initialize the declaration which performed lifetime extension.
3607     Type = getTypes().ConvertTypeForMem(MaterializedType);
3608   }
3609 
3610   // Create a global variable for this lifetime-extended temporary.
3611   llvm::GlobalValue::LinkageTypes Linkage =
3612       getLLVMLinkageVarDefinition(VD, Constant);
3613   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3614     const VarDecl *InitVD;
3615     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3616         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3617       // Temporaries defined inside a class get linkonce_odr linkage because the
3618       // class can be defined in multipe translation units.
3619       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3620     } else {
3621       // There is no need for this temporary to have external linkage if the
3622       // VarDecl has external linkage.
3623       Linkage = llvm::GlobalVariable::InternalLinkage;
3624     }
3625   }
3626   unsigned AddrSpace = GetGlobalVarAddressSpace(
3627       VD, getContext().getTargetAddressSpace(MaterializedType));
3628   auto *GV = new llvm::GlobalVariable(
3629       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3630       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3631       AddrSpace);
3632   setGlobalVisibility(GV, VD);
3633   GV->setAlignment(Align.getQuantity());
3634   if (supportsCOMDAT() && GV->isWeakForLinker())
3635     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3636   if (VD->getTLSKind())
3637     setTLSMode(GV, *VD);
3638   MaterializedGlobalTemporaryMap[E] = GV;
3639   return ConstantAddress(GV, Align);
3640 }
3641 
3642 /// EmitObjCPropertyImplementations - Emit information for synthesized
3643 /// properties for an implementation.
3644 void CodeGenModule::EmitObjCPropertyImplementations(const
3645                                                     ObjCImplementationDecl *D) {
3646   for (const auto *PID : D->property_impls()) {
3647     // Dynamic is just for type-checking.
3648     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3649       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3650 
3651       // Determine which methods need to be implemented, some may have
3652       // been overridden. Note that ::isPropertyAccessor is not the method
3653       // we want, that just indicates if the decl came from a
3654       // property. What we want to know is if the method is defined in
3655       // this implementation.
3656       if (!D->getInstanceMethod(PD->getGetterName()))
3657         CodeGenFunction(*this).GenerateObjCGetter(
3658                                  const_cast<ObjCImplementationDecl *>(D), PID);
3659       if (!PD->isReadOnly() &&
3660           !D->getInstanceMethod(PD->getSetterName()))
3661         CodeGenFunction(*this).GenerateObjCSetter(
3662                                  const_cast<ObjCImplementationDecl *>(D), PID);
3663     }
3664   }
3665 }
3666 
3667 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3668   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3669   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3670        ivar; ivar = ivar->getNextIvar())
3671     if (ivar->getType().isDestructedType())
3672       return true;
3673 
3674   return false;
3675 }
3676 
3677 static bool AllTrivialInitializers(CodeGenModule &CGM,
3678                                    ObjCImplementationDecl *D) {
3679   CodeGenFunction CGF(CGM);
3680   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3681        E = D->init_end(); B != E; ++B) {
3682     CXXCtorInitializer *CtorInitExp = *B;
3683     Expr *Init = CtorInitExp->getInit();
3684     if (!CGF.isTrivialInitializer(Init))
3685       return false;
3686   }
3687   return true;
3688 }
3689 
3690 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3691 /// for an implementation.
3692 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3693   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3694   if (needsDestructMethod(D)) {
3695     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3696     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3697     ObjCMethodDecl *DTORMethod =
3698       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3699                              cxxSelector, getContext().VoidTy, nullptr, D,
3700                              /*isInstance=*/true, /*isVariadic=*/false,
3701                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3702                              /*isDefined=*/false, ObjCMethodDecl::Required);
3703     D->addInstanceMethod(DTORMethod);
3704     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3705     D->setHasDestructors(true);
3706   }
3707 
3708   // If the implementation doesn't have any ivar initializers, we don't need
3709   // a .cxx_construct.
3710   if (D->getNumIvarInitializers() == 0 ||
3711       AllTrivialInitializers(*this, D))
3712     return;
3713 
3714   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3715   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3716   // The constructor returns 'self'.
3717   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3718                                                 D->getLocation(),
3719                                                 D->getLocation(),
3720                                                 cxxSelector,
3721                                                 getContext().getObjCIdType(),
3722                                                 nullptr, D, /*isInstance=*/true,
3723                                                 /*isVariadic=*/false,
3724                                                 /*isPropertyAccessor=*/true,
3725                                                 /*isImplicitlyDeclared=*/true,
3726                                                 /*isDefined=*/false,
3727                                                 ObjCMethodDecl::Required);
3728   D->addInstanceMethod(CTORMethod);
3729   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3730   D->setHasNonZeroConstructors(true);
3731 }
3732 
3733 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3734 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3735   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3736       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3737     ErrorUnsupported(LSD, "linkage spec");
3738     return;
3739   }
3740 
3741   EmitDeclContext(LSD);
3742 }
3743 
3744 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3745   for (auto *I : DC->decls()) {
3746     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3747     // are themselves considered "top-level", so EmitTopLevelDecl on an
3748     // ObjCImplDecl does not recursively visit them. We need to do that in
3749     // case they're nested inside another construct (LinkageSpecDecl /
3750     // ExportDecl) that does stop them from being considered "top-level".
3751     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3752       for (auto *M : OID->methods())
3753         EmitTopLevelDecl(M);
3754     }
3755 
3756     EmitTopLevelDecl(I);
3757   }
3758 }
3759 
3760 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3761 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3762   // Ignore dependent declarations.
3763   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3764     return;
3765 
3766   switch (D->getKind()) {
3767   case Decl::CXXConversion:
3768   case Decl::CXXMethod:
3769   case Decl::Function:
3770     // Skip function templates
3771     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3772         cast<FunctionDecl>(D)->isLateTemplateParsed())
3773       return;
3774 
3775     EmitGlobal(cast<FunctionDecl>(D));
3776     // Always provide some coverage mapping
3777     // even for the functions that aren't emitted.
3778     AddDeferredUnusedCoverageMapping(D);
3779     break;
3780 
3781   case Decl::Var:
3782   case Decl::Decomposition:
3783     // Skip variable templates
3784     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3785       return;
3786   case Decl::VarTemplateSpecialization:
3787     EmitGlobal(cast<VarDecl>(D));
3788     if (auto *DD = dyn_cast<DecompositionDecl>(D))
3789       for (auto *B : DD->bindings())
3790         if (auto *HD = B->getHoldingVar())
3791           EmitGlobal(HD);
3792     break;
3793 
3794   // Indirect fields from global anonymous structs and unions can be
3795   // ignored; only the actual variable requires IR gen support.
3796   case Decl::IndirectField:
3797     break;
3798 
3799   // C++ Decls
3800   case Decl::Namespace:
3801     EmitDeclContext(cast<NamespaceDecl>(D));
3802     break;
3803   case Decl::CXXRecord:
3804     // Emit any static data members, they may be definitions.
3805     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3806       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3807         EmitTopLevelDecl(I);
3808     break;
3809     // No code generation needed.
3810   case Decl::UsingShadow:
3811   case Decl::ClassTemplate:
3812   case Decl::VarTemplate:
3813   case Decl::VarTemplatePartialSpecialization:
3814   case Decl::FunctionTemplate:
3815   case Decl::TypeAliasTemplate:
3816   case Decl::Block:
3817   case Decl::Empty:
3818     break;
3819   case Decl::Using:          // using X; [C++]
3820     if (CGDebugInfo *DI = getModuleDebugInfo())
3821         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3822     return;
3823   case Decl::NamespaceAlias:
3824     if (CGDebugInfo *DI = getModuleDebugInfo())
3825         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3826     return;
3827   case Decl::UsingDirective: // using namespace X; [C++]
3828     if (CGDebugInfo *DI = getModuleDebugInfo())
3829       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3830     return;
3831   case Decl::CXXConstructor:
3832     // Skip function templates
3833     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3834         cast<FunctionDecl>(D)->isLateTemplateParsed())
3835       return;
3836 
3837     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3838     break;
3839   case Decl::CXXDestructor:
3840     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3841       return;
3842     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3843     break;
3844 
3845   case Decl::StaticAssert:
3846     // Nothing to do.
3847     break;
3848 
3849   // Objective-C Decls
3850 
3851   // Forward declarations, no (immediate) code generation.
3852   case Decl::ObjCInterface:
3853   case Decl::ObjCCategory:
3854     break;
3855 
3856   case Decl::ObjCProtocol: {
3857     auto *Proto = cast<ObjCProtocolDecl>(D);
3858     if (Proto->isThisDeclarationADefinition())
3859       ObjCRuntime->GenerateProtocol(Proto);
3860     break;
3861   }
3862 
3863   case Decl::ObjCCategoryImpl:
3864     // Categories have properties but don't support synthesize so we
3865     // can ignore them here.
3866     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3867     break;
3868 
3869   case Decl::ObjCImplementation: {
3870     auto *OMD = cast<ObjCImplementationDecl>(D);
3871     EmitObjCPropertyImplementations(OMD);
3872     EmitObjCIvarInitializations(OMD);
3873     ObjCRuntime->GenerateClass(OMD);
3874     // Emit global variable debug information.
3875     if (CGDebugInfo *DI = getModuleDebugInfo())
3876       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3877         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3878             OMD->getClassInterface()), OMD->getLocation());
3879     break;
3880   }
3881   case Decl::ObjCMethod: {
3882     auto *OMD = cast<ObjCMethodDecl>(D);
3883     // If this is not a prototype, emit the body.
3884     if (OMD->getBody())
3885       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3886     break;
3887   }
3888   case Decl::ObjCCompatibleAlias:
3889     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3890     break;
3891 
3892   case Decl::PragmaComment: {
3893     const auto *PCD = cast<PragmaCommentDecl>(D);
3894     switch (PCD->getCommentKind()) {
3895     case PCK_Unknown:
3896       llvm_unreachable("unexpected pragma comment kind");
3897     case PCK_Linker:
3898       AppendLinkerOptions(PCD->getArg());
3899       break;
3900     case PCK_Lib:
3901       AddDependentLib(PCD->getArg());
3902       break;
3903     case PCK_Compiler:
3904     case PCK_ExeStr:
3905     case PCK_User:
3906       break; // We ignore all of these.
3907     }
3908     break;
3909   }
3910 
3911   case Decl::PragmaDetectMismatch: {
3912     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3913     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3914     break;
3915   }
3916 
3917   case Decl::LinkageSpec:
3918     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3919     break;
3920 
3921   case Decl::FileScopeAsm: {
3922     // File-scope asm is ignored during device-side CUDA compilation.
3923     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3924       break;
3925     // File-scope asm is ignored during device-side OpenMP compilation.
3926     if (LangOpts.OpenMPIsDevice)
3927       break;
3928     auto *AD = cast<FileScopeAsmDecl>(D);
3929     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3930     break;
3931   }
3932 
3933   case Decl::Import: {
3934     auto *Import = cast<ImportDecl>(D);
3935 
3936     // If we've already imported this module, we're done.
3937     if (!ImportedModules.insert(Import->getImportedModule()))
3938       break;
3939 
3940     // Emit debug information for direct imports.
3941     if (!Import->getImportedOwningModule()) {
3942       if (CGDebugInfo *DI = getModuleDebugInfo())
3943         DI->EmitImportDecl(*Import);
3944     }
3945 
3946     // Find all of the submodules and emit the module initializers.
3947     llvm::SmallPtrSet<clang::Module *, 16> Visited;
3948     SmallVector<clang::Module *, 16> Stack;
3949     Visited.insert(Import->getImportedModule());
3950     Stack.push_back(Import->getImportedModule());
3951 
3952     while (!Stack.empty()) {
3953       clang::Module *Mod = Stack.pop_back_val();
3954       if (!EmittedModuleInitializers.insert(Mod).second)
3955         continue;
3956 
3957       for (auto *D : Context.getModuleInitializers(Mod))
3958         EmitTopLevelDecl(D);
3959 
3960       // Visit the submodules of this module.
3961       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
3962                                              SubEnd = Mod->submodule_end();
3963            Sub != SubEnd; ++Sub) {
3964         // Skip explicit children; they need to be explicitly imported to emit
3965         // the initializers.
3966         if ((*Sub)->IsExplicit)
3967           continue;
3968 
3969         if (Visited.insert(*Sub).second)
3970           Stack.push_back(*Sub);
3971       }
3972     }
3973     break;
3974   }
3975 
3976   case Decl::Export:
3977     EmitDeclContext(cast<ExportDecl>(D));
3978     break;
3979 
3980   case Decl::OMPThreadPrivate:
3981     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3982     break;
3983 
3984   case Decl::ClassTemplateSpecialization: {
3985     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3986     if (DebugInfo &&
3987         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3988         Spec->hasDefinition())
3989       DebugInfo->completeTemplateDefinition(*Spec);
3990     break;
3991   }
3992 
3993   case Decl::OMPDeclareReduction:
3994     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
3995     break;
3996 
3997   default:
3998     // Make sure we handled everything we should, every other kind is a
3999     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4000     // function. Need to recode Decl::Kind to do that easily.
4001     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4002     break;
4003   }
4004 }
4005 
4006 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4007   // Do we need to generate coverage mapping?
4008   if (!CodeGenOpts.CoverageMapping)
4009     return;
4010   switch (D->getKind()) {
4011   case Decl::CXXConversion:
4012   case Decl::CXXMethod:
4013   case Decl::Function:
4014   case Decl::ObjCMethod:
4015   case Decl::CXXConstructor:
4016   case Decl::CXXDestructor: {
4017     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4018       return;
4019     auto I = DeferredEmptyCoverageMappingDecls.find(D);
4020     if (I == DeferredEmptyCoverageMappingDecls.end())
4021       DeferredEmptyCoverageMappingDecls[D] = true;
4022     break;
4023   }
4024   default:
4025     break;
4026   };
4027 }
4028 
4029 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4030   // Do we need to generate coverage mapping?
4031   if (!CodeGenOpts.CoverageMapping)
4032     return;
4033   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4034     if (Fn->isTemplateInstantiation())
4035       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4036   }
4037   auto I = DeferredEmptyCoverageMappingDecls.find(D);
4038   if (I == DeferredEmptyCoverageMappingDecls.end())
4039     DeferredEmptyCoverageMappingDecls[D] = false;
4040   else
4041     I->second = false;
4042 }
4043 
4044 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4045   std::vector<const Decl *> DeferredDecls;
4046   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4047     if (!I.second)
4048       continue;
4049     DeferredDecls.push_back(I.first);
4050   }
4051   // Sort the declarations by their location to make sure that the tests get a
4052   // predictable order for the coverage mapping for the unused declarations.
4053   if (CodeGenOpts.DumpCoverageMapping)
4054     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4055               [] (const Decl *LHS, const Decl *RHS) {
4056       return LHS->getLocStart() < RHS->getLocStart();
4057     });
4058   for (const auto *D : DeferredDecls) {
4059     switch (D->getKind()) {
4060     case Decl::CXXConversion:
4061     case Decl::CXXMethod:
4062     case Decl::Function:
4063     case Decl::ObjCMethod: {
4064       CodeGenPGO PGO(*this);
4065       GlobalDecl GD(cast<FunctionDecl>(D));
4066       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4067                                   getFunctionLinkage(GD));
4068       break;
4069     }
4070     case Decl::CXXConstructor: {
4071       CodeGenPGO PGO(*this);
4072       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4073       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4074                                   getFunctionLinkage(GD));
4075       break;
4076     }
4077     case Decl::CXXDestructor: {
4078       CodeGenPGO PGO(*this);
4079       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4080       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4081                                   getFunctionLinkage(GD));
4082       break;
4083     }
4084     default:
4085       break;
4086     };
4087   }
4088 }
4089 
4090 /// Turns the given pointer into a constant.
4091 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4092                                           const void *Ptr) {
4093   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4094   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4095   return llvm::ConstantInt::get(i64, PtrInt);
4096 }
4097 
4098 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4099                                    llvm::NamedMDNode *&GlobalMetadata,
4100                                    GlobalDecl D,
4101                                    llvm::GlobalValue *Addr) {
4102   if (!GlobalMetadata)
4103     GlobalMetadata =
4104       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4105 
4106   // TODO: should we report variant information for ctors/dtors?
4107   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4108                            llvm::ConstantAsMetadata::get(GetPointerConstant(
4109                                CGM.getLLVMContext(), D.getDecl()))};
4110   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4111 }
4112 
4113 /// For each function which is declared within an extern "C" region and marked
4114 /// as 'used', but has internal linkage, create an alias from the unmangled
4115 /// name to the mangled name if possible. People expect to be able to refer
4116 /// to such functions with an unmangled name from inline assembly within the
4117 /// same translation unit.
4118 void CodeGenModule::EmitStaticExternCAliases() {
4119   // Don't do anything if we're generating CUDA device code -- the NVPTX
4120   // assembly target doesn't support aliases.
4121   if (Context.getTargetInfo().getTriple().isNVPTX())
4122     return;
4123   for (auto &I : StaticExternCValues) {
4124     IdentifierInfo *Name = I.first;
4125     llvm::GlobalValue *Val = I.second;
4126     if (Val && !getModule().getNamedValue(Name->getName()))
4127       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4128   }
4129 }
4130 
4131 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4132                                              GlobalDecl &Result) const {
4133   auto Res = Manglings.find(MangledName);
4134   if (Res == Manglings.end())
4135     return false;
4136   Result = Res->getValue();
4137   return true;
4138 }
4139 
4140 /// Emits metadata nodes associating all the global values in the
4141 /// current module with the Decls they came from.  This is useful for
4142 /// projects using IR gen as a subroutine.
4143 ///
4144 /// Since there's currently no way to associate an MDNode directly
4145 /// with an llvm::GlobalValue, we create a global named metadata
4146 /// with the name 'clang.global.decl.ptrs'.
4147 void CodeGenModule::EmitDeclMetadata() {
4148   llvm::NamedMDNode *GlobalMetadata = nullptr;
4149 
4150   for (auto &I : MangledDeclNames) {
4151     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4152     // Some mangled names don't necessarily have an associated GlobalValue
4153     // in this module, e.g. if we mangled it for DebugInfo.
4154     if (Addr)
4155       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4156   }
4157 }
4158 
4159 /// Emits metadata nodes for all the local variables in the current
4160 /// function.
4161 void CodeGenFunction::EmitDeclMetadata() {
4162   if (LocalDeclMap.empty()) return;
4163 
4164   llvm::LLVMContext &Context = getLLVMContext();
4165 
4166   // Find the unique metadata ID for this name.
4167   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4168 
4169   llvm::NamedMDNode *GlobalMetadata = nullptr;
4170 
4171   for (auto &I : LocalDeclMap) {
4172     const Decl *D = I.first;
4173     llvm::Value *Addr = I.second.getPointer();
4174     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4175       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4176       Alloca->setMetadata(
4177           DeclPtrKind, llvm::MDNode::get(
4178                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4179     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4180       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4181       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4182     }
4183   }
4184 }
4185 
4186 void CodeGenModule::EmitVersionIdentMetadata() {
4187   llvm::NamedMDNode *IdentMetadata =
4188     TheModule.getOrInsertNamedMetadata("llvm.ident");
4189   std::string Version = getClangFullVersion();
4190   llvm::LLVMContext &Ctx = TheModule.getContext();
4191 
4192   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4193   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4194 }
4195 
4196 void CodeGenModule::EmitTargetMetadata() {
4197   // Warning, new MangledDeclNames may be appended within this loop.
4198   // We rely on MapVector insertions adding new elements to the end
4199   // of the container.
4200   // FIXME: Move this loop into the one target that needs it, and only
4201   // loop over those declarations for which we couldn't emit the target
4202   // metadata when we emitted the declaration.
4203   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4204     auto Val = *(MangledDeclNames.begin() + I);
4205     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4206     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4207     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4208   }
4209 }
4210 
4211 void CodeGenModule::EmitCoverageFile() {
4212   if (getCodeGenOpts().CoverageDataFile.empty() &&
4213       getCodeGenOpts().CoverageNotesFile.empty())
4214     return;
4215 
4216   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4217   if (!CUNode)
4218     return;
4219 
4220   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4221   llvm::LLVMContext &Ctx = TheModule.getContext();
4222   auto *CoverageDataFile =
4223       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4224   auto *CoverageNotesFile =
4225       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4226   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4227     llvm::MDNode *CU = CUNode->getOperand(i);
4228     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4229     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4230   }
4231 }
4232 
4233 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4234   // Sema has checked that all uuid strings are of the form
4235   // "12345678-1234-1234-1234-1234567890ab".
4236   assert(Uuid.size() == 36);
4237   for (unsigned i = 0; i < 36; ++i) {
4238     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4239     else                                         assert(isHexDigit(Uuid[i]));
4240   }
4241 
4242   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4243   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4244 
4245   llvm::Constant *Field3[8];
4246   for (unsigned Idx = 0; Idx < 8; ++Idx)
4247     Field3[Idx] = llvm::ConstantInt::get(
4248         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4249 
4250   llvm::Constant *Fields[4] = {
4251     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4252     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4253     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4254     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4255   };
4256 
4257   return llvm::ConstantStruct::getAnon(Fields);
4258 }
4259 
4260 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4261                                                        bool ForEH) {
4262   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4263   // FIXME: should we even be calling this method if RTTI is disabled
4264   // and it's not for EH?
4265   if (!ForEH && !getLangOpts().RTTI)
4266     return llvm::Constant::getNullValue(Int8PtrTy);
4267 
4268   if (ForEH && Ty->isObjCObjectPointerType() &&
4269       LangOpts.ObjCRuntime.isGNUFamily())
4270     return ObjCRuntime->GetEHType(Ty);
4271 
4272   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4273 }
4274 
4275 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4276   for (auto RefExpr : D->varlists()) {
4277     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4278     bool PerformInit =
4279         VD->getAnyInitializer() &&
4280         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4281                                                         /*ForRef=*/false);
4282 
4283     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4284     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4285             VD, Addr, RefExpr->getLocStart(), PerformInit))
4286       CXXGlobalInits.push_back(InitFunction);
4287   }
4288 }
4289 
4290 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4291   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4292   if (InternalId)
4293     return InternalId;
4294 
4295   if (isExternallyVisible(T->getLinkage())) {
4296     std::string OutName;
4297     llvm::raw_string_ostream Out(OutName);
4298     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4299 
4300     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4301   } else {
4302     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4303                                            llvm::ArrayRef<llvm::Metadata *>());
4304   }
4305 
4306   return InternalId;
4307 }
4308 
4309 /// Returns whether this module needs the "all-vtables" type identifier.
4310 bool CodeGenModule::NeedAllVtablesTypeId() const {
4311   // Returns true if at least one of vtable-based CFI checkers is enabled and
4312   // is not in the trapping mode.
4313   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4314            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4315           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4316            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4317           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4318            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4319           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4320            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4321 }
4322 
4323 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4324                                           CharUnits Offset,
4325                                           const CXXRecordDecl *RD) {
4326   llvm::Metadata *MD =
4327       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4328   VTable->addTypeMetadata(Offset.getQuantity(), MD);
4329 
4330   if (CodeGenOpts.SanitizeCfiCrossDso)
4331     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4332       VTable->addTypeMetadata(Offset.getQuantity(),
4333                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4334 
4335   if (NeedAllVtablesTypeId()) {
4336     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4337     VTable->addTypeMetadata(Offset.getQuantity(), MD);
4338   }
4339 }
4340 
4341 // Fills in the supplied string map with the set of target features for the
4342 // passed in function.
4343 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4344                                           const FunctionDecl *FD) {
4345   StringRef TargetCPU = Target.getTargetOpts().CPU;
4346   if (const auto *TD = FD->getAttr<TargetAttr>()) {
4347     // If we have a TargetAttr build up the feature map based on that.
4348     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4349 
4350     // Make a copy of the features as passed on the command line into the
4351     // beginning of the additional features from the function to override.
4352     ParsedAttr.first.insert(ParsedAttr.first.begin(),
4353                             Target.getTargetOpts().FeaturesAsWritten.begin(),
4354                             Target.getTargetOpts().FeaturesAsWritten.end());
4355 
4356     if (ParsedAttr.second != "")
4357       TargetCPU = ParsedAttr.second;
4358 
4359     // Now populate the feature map, first with the TargetCPU which is either
4360     // the default or a new one from the target attribute string. Then we'll use
4361     // the passed in features (FeaturesAsWritten) along with the new ones from
4362     // the attribute.
4363     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4364   } else {
4365     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4366                           Target.getTargetOpts().Features);
4367   }
4368 }
4369 
4370 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4371   if (!SanStats)
4372     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4373 
4374   return *SanStats;
4375 }
4376 llvm::Value *
4377 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4378                                                   CodeGenFunction &CGF) {
4379   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4380   auto SamplerT = getOpenCLRuntime().getSamplerType();
4381   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4382   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4383                                 "__translate_sampler_initializer"),
4384                                 {C});
4385 }
4386