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