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