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