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