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