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