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