xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 6b2a61d3a5c1c1ac968e0593b8d9151207216882)
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       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2669 
2670   if (Entry) {
2671     if (GA->getAliasee() == Entry) {
2672       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2673       return;
2674     }
2675 
2676     assert(Entry->isDeclaration());
2677 
2678     // If there is a declaration in the module, then we had an extern followed
2679     // by the alias, as in:
2680     //   extern int test6();
2681     //   ...
2682     //   int test6() __attribute__((alias("test7")));
2683     //
2684     // Remove it and replace uses of it with the alias.
2685     GA->takeName(Entry);
2686 
2687     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2688                                                           Entry->getType()));
2689     Entry->eraseFromParent();
2690   } else {
2691     GA->setName(MangledName);
2692   }
2693 
2694   // Set attributes which are particular to an alias; this is a
2695   // specialization of the attributes which may be set on a global
2696   // variable/function.
2697   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2698       D->isWeakImported()) {
2699     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2700   }
2701 
2702   if (const auto *VD = dyn_cast<VarDecl>(D))
2703     if (VD->getTLSKind())
2704       setTLSMode(GA, *VD);
2705 
2706   setAliasAttributes(D, GA);
2707 }
2708 
2709 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2710                                             ArrayRef<llvm::Type*> Tys) {
2711   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2712                                          Tys);
2713 }
2714 
2715 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2716 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2717                          const StringLiteral *Literal, bool TargetIsLSB,
2718                          bool &IsUTF16, unsigned &StringLength) {
2719   StringRef String = Literal->getString();
2720   unsigned NumBytes = String.size();
2721 
2722   // Check for simple case.
2723   if (!Literal->containsNonAsciiOrNull()) {
2724     StringLength = NumBytes;
2725     return *Map.insert(std::make_pair(String, nullptr)).first;
2726   }
2727 
2728   // Otherwise, convert the UTF8 literals into a string of shorts.
2729   IsUTF16 = true;
2730 
2731   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2732   const UTF8 *FromPtr = (const UTF8 *)String.data();
2733   UTF16 *ToPtr = &ToBuf[0];
2734 
2735   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2736                            &ToPtr, ToPtr + NumBytes,
2737                            strictConversion);
2738 
2739   // ConvertUTF8toUTF16 returns the length in ToPtr.
2740   StringLength = ToPtr - &ToBuf[0];
2741 
2742   // Add an explicit null.
2743   *ToPtr = 0;
2744   return *Map.insert(std::make_pair(
2745                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2746                                    (StringLength + 1) * 2),
2747                          nullptr)).first;
2748 }
2749 
2750 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2751 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2752                        const StringLiteral *Literal, unsigned &StringLength) {
2753   StringRef String = Literal->getString();
2754   StringLength = String.size();
2755   return *Map.insert(std::make_pair(String, nullptr)).first;
2756 }
2757 
2758 ConstantAddress
2759 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2760   unsigned StringLength = 0;
2761   bool isUTF16 = false;
2762   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2763       GetConstantCFStringEntry(CFConstantStringMap, Literal,
2764                                getDataLayout().isLittleEndian(), isUTF16,
2765                                StringLength);
2766 
2767   if (auto *C = Entry.second)
2768     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2769 
2770   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2771   llvm::Constant *Zeros[] = { Zero, Zero };
2772   llvm::Value *V;
2773 
2774   // If we don't already have it, get __CFConstantStringClassReference.
2775   if (!CFConstantStringClassRef) {
2776     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2777     Ty = llvm::ArrayType::get(Ty, 0);
2778     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2779                                            "__CFConstantStringClassReference");
2780     // Decay array -> ptr
2781     V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2782     CFConstantStringClassRef = V;
2783   }
2784   else
2785     V = CFConstantStringClassRef;
2786 
2787   QualType CFTy = getContext().getCFConstantStringType();
2788 
2789   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2790 
2791   llvm::Constant *Fields[4];
2792 
2793   // Class pointer.
2794   Fields[0] = cast<llvm::ConstantExpr>(V);
2795 
2796   // Flags.
2797   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2798   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2799     llvm::ConstantInt::get(Ty, 0x07C8);
2800 
2801   // String pointer.
2802   llvm::Constant *C = nullptr;
2803   if (isUTF16) {
2804     ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2805         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2806         Entry.first().size() / 2);
2807     C = llvm::ConstantDataArray::get(VMContext, Arr);
2808   } else {
2809     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2810   }
2811 
2812   // Note: -fwritable-strings doesn't make the backing store strings of
2813   // CFStrings writable. (See <rdar://problem/10657500>)
2814   auto *GV =
2815       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2816                                llvm::GlobalValue::PrivateLinkage, C, ".str");
2817   GV->setUnnamedAddr(true);
2818   // Don't enforce the target's minimum global alignment, since the only use
2819   // of the string is via this class initializer.
2820   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2821   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2822   // that changes the section it ends in, which surprises ld64.
2823   if (isUTF16) {
2824     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2825     GV->setAlignment(Align.getQuantity());
2826     GV->setSection("__TEXT,__ustring");
2827   } else {
2828     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2829     GV->setAlignment(Align.getQuantity());
2830     GV->setSection("__TEXT,__cstring,cstring_literals");
2831   }
2832 
2833   // String.
2834   Fields[2] =
2835       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2836 
2837   if (isUTF16)
2838     // Cast the UTF16 string to the correct type.
2839     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2840 
2841   // String length.
2842   Ty = getTypes().ConvertType(getContext().LongTy);
2843   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2844 
2845   CharUnits Alignment = getPointerAlign();
2846 
2847   // The struct.
2848   C = llvm::ConstantStruct::get(STy, Fields);
2849   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2850                                 llvm::GlobalVariable::PrivateLinkage, C,
2851                                 "_unnamed_cfstring_");
2852   GV->setSection("__DATA,__cfstring");
2853   GV->setAlignment(Alignment.getQuantity());
2854   Entry.second = GV;
2855 
2856   return ConstantAddress(GV, Alignment);
2857 }
2858 
2859 ConstantAddress
2860 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2861   unsigned StringLength = 0;
2862   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2863       GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2864 
2865   if (auto *C = Entry.second)
2866     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2867 
2868   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2869   llvm::Constant *Zeros[] = { Zero, Zero };
2870   llvm::Value *V;
2871   // If we don't already have it, get _NSConstantStringClassReference.
2872   if (!ConstantStringClassRef) {
2873     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2874     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2875     llvm::Constant *GV;
2876     if (LangOpts.ObjCRuntime.isNonFragile()) {
2877       std::string str =
2878         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2879                             : "OBJC_CLASS_$_" + StringClass;
2880       GV = getObjCRuntime().GetClassGlobal(str);
2881       // Make sure the result is of the correct type.
2882       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2883       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2884       ConstantStringClassRef = V;
2885     } else {
2886       std::string str =
2887         StringClass.empty() ? "_NSConstantStringClassReference"
2888                             : "_" + StringClass + "ClassReference";
2889       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2890       GV = CreateRuntimeVariable(PTy, str);
2891       // Decay array -> ptr
2892       V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
2893       ConstantStringClassRef = V;
2894     }
2895   } else
2896     V = ConstantStringClassRef;
2897 
2898   if (!NSConstantStringType) {
2899     // Construct the type for a constant NSString.
2900     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2901     D->startDefinition();
2902 
2903     QualType FieldTypes[3];
2904 
2905     // const int *isa;
2906     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2907     // const char *str;
2908     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2909     // unsigned int length;
2910     FieldTypes[2] = Context.UnsignedIntTy;
2911 
2912     // Create fields
2913     for (unsigned i = 0; i < 3; ++i) {
2914       FieldDecl *Field = FieldDecl::Create(Context, D,
2915                                            SourceLocation(),
2916                                            SourceLocation(), nullptr,
2917                                            FieldTypes[i], /*TInfo=*/nullptr,
2918                                            /*BitWidth=*/nullptr,
2919                                            /*Mutable=*/false,
2920                                            ICIS_NoInit);
2921       Field->setAccess(AS_public);
2922       D->addDecl(Field);
2923     }
2924 
2925     D->completeDefinition();
2926     QualType NSTy = Context.getTagDeclType(D);
2927     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2928   }
2929 
2930   llvm::Constant *Fields[3];
2931 
2932   // Class pointer.
2933   Fields[0] = cast<llvm::ConstantExpr>(V);
2934 
2935   // String pointer.
2936   llvm::Constant *C =
2937       llvm::ConstantDataArray::getString(VMContext, Entry.first());
2938 
2939   llvm::GlobalValue::LinkageTypes Linkage;
2940   bool isConstant;
2941   Linkage = llvm::GlobalValue::PrivateLinkage;
2942   isConstant = !LangOpts.WritableStrings;
2943 
2944   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2945                                       Linkage, C, ".str");
2946   GV->setUnnamedAddr(true);
2947   // Don't enforce the target's minimum global alignment, since the only use
2948   // of the string is via this class initializer.
2949   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2950   GV->setAlignment(Align.getQuantity());
2951   Fields[1] =
2952       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2953 
2954   // String length.
2955   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2956   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2957 
2958   // The struct.
2959   CharUnits Alignment = getPointerAlign();
2960   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2961   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2962                                 llvm::GlobalVariable::PrivateLinkage, C,
2963                                 "_unnamed_nsstring_");
2964   GV->setAlignment(Alignment.getQuantity());
2965   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2966   const char *NSStringNonFragileABISection =
2967       "__DATA,__objc_stringobj,regular,no_dead_strip";
2968   // FIXME. Fix section.
2969   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2970                      ? NSStringNonFragileABISection
2971                      : NSStringSection);
2972   Entry.second = GV;
2973 
2974   return ConstantAddress(GV, Alignment);
2975 }
2976 
2977 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2978   if (ObjCFastEnumerationStateType.isNull()) {
2979     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2980     D->startDefinition();
2981 
2982     QualType FieldTypes[] = {
2983       Context.UnsignedLongTy,
2984       Context.getPointerType(Context.getObjCIdType()),
2985       Context.getPointerType(Context.UnsignedLongTy),
2986       Context.getConstantArrayType(Context.UnsignedLongTy,
2987                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2988     };
2989 
2990     for (size_t i = 0; i < 4; ++i) {
2991       FieldDecl *Field = FieldDecl::Create(Context,
2992                                            D,
2993                                            SourceLocation(),
2994                                            SourceLocation(), nullptr,
2995                                            FieldTypes[i], /*TInfo=*/nullptr,
2996                                            /*BitWidth=*/nullptr,
2997                                            /*Mutable=*/false,
2998                                            ICIS_NoInit);
2999       Field->setAccess(AS_public);
3000       D->addDecl(Field);
3001     }
3002 
3003     D->completeDefinition();
3004     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3005   }
3006 
3007   return ObjCFastEnumerationStateType;
3008 }
3009 
3010 llvm::Constant *
3011 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3012   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3013 
3014   // Don't emit it as the address of the string, emit the string data itself
3015   // as an inline array.
3016   if (E->getCharByteWidth() == 1) {
3017     SmallString<64> Str(E->getString());
3018 
3019     // Resize the string to the right size, which is indicated by its type.
3020     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3021     Str.resize(CAT->getSize().getZExtValue());
3022     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3023   }
3024 
3025   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3026   llvm::Type *ElemTy = AType->getElementType();
3027   unsigned NumElements = AType->getNumElements();
3028 
3029   // Wide strings have either 2-byte or 4-byte elements.
3030   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3031     SmallVector<uint16_t, 32> Elements;
3032     Elements.reserve(NumElements);
3033 
3034     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3035       Elements.push_back(E->getCodeUnit(i));
3036     Elements.resize(NumElements);
3037     return llvm::ConstantDataArray::get(VMContext, Elements);
3038   }
3039 
3040   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3041   SmallVector<uint32_t, 32> Elements;
3042   Elements.reserve(NumElements);
3043 
3044   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3045     Elements.push_back(E->getCodeUnit(i));
3046   Elements.resize(NumElements);
3047   return llvm::ConstantDataArray::get(VMContext, Elements);
3048 }
3049 
3050 static llvm::GlobalVariable *
3051 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3052                       CodeGenModule &CGM, StringRef GlobalName,
3053                       CharUnits Alignment) {
3054   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3055   unsigned AddrSpace = 0;
3056   if (CGM.getLangOpts().OpenCL)
3057     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3058 
3059   llvm::Module &M = CGM.getModule();
3060   // Create a global variable for this string
3061   auto *GV = new llvm::GlobalVariable(
3062       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3063       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3064   GV->setAlignment(Alignment.getQuantity());
3065   GV->setUnnamedAddr(true);
3066   if (GV->isWeakForLinker()) {
3067     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3068     GV->setComdat(M.getOrInsertComdat(GV->getName()));
3069   }
3070 
3071   return GV;
3072 }
3073 
3074 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3075 /// constant array for the given string literal.
3076 ConstantAddress
3077 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3078                                                   StringRef Name) {
3079   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3080 
3081   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3082   llvm::GlobalVariable **Entry = nullptr;
3083   if (!LangOpts.WritableStrings) {
3084     Entry = &ConstantStringMap[C];
3085     if (auto GV = *Entry) {
3086       if (Alignment.getQuantity() > GV->getAlignment())
3087         GV->setAlignment(Alignment.getQuantity());
3088       return ConstantAddress(GV, Alignment);
3089     }
3090   }
3091 
3092   SmallString<256> MangledNameBuffer;
3093   StringRef GlobalVariableName;
3094   llvm::GlobalValue::LinkageTypes LT;
3095 
3096   // Mangle the string literal if the ABI allows for it.  However, we cannot
3097   // do this if  we are compiling with ASan or -fwritable-strings because they
3098   // rely on strings having normal linkage.
3099   if (!LangOpts.WritableStrings &&
3100       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3101       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3102     llvm::raw_svector_ostream Out(MangledNameBuffer);
3103     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3104 
3105     LT = llvm::GlobalValue::LinkOnceODRLinkage;
3106     GlobalVariableName = MangledNameBuffer;
3107   } else {
3108     LT = llvm::GlobalValue::PrivateLinkage;
3109     GlobalVariableName = Name;
3110   }
3111 
3112   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3113   if (Entry)
3114     *Entry = GV;
3115 
3116   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3117                                   QualType());
3118   return ConstantAddress(GV, Alignment);
3119 }
3120 
3121 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3122 /// array for the given ObjCEncodeExpr node.
3123 ConstantAddress
3124 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3125   std::string Str;
3126   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3127 
3128   return GetAddrOfConstantCString(Str);
3129 }
3130 
3131 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3132 /// the literal and a terminating '\0' character.
3133 /// The result has pointer to array type.
3134 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3135     const std::string &Str, const char *GlobalName) {
3136   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3137   CharUnits Alignment =
3138     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3139 
3140   llvm::Constant *C =
3141       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3142 
3143   // Don't share any string literals if strings aren't constant.
3144   llvm::GlobalVariable **Entry = nullptr;
3145   if (!LangOpts.WritableStrings) {
3146     Entry = &ConstantStringMap[C];
3147     if (auto GV = *Entry) {
3148       if (Alignment.getQuantity() > GV->getAlignment())
3149         GV->setAlignment(Alignment.getQuantity());
3150       return ConstantAddress(GV, Alignment);
3151     }
3152   }
3153 
3154   // Get the default prefix if a name wasn't specified.
3155   if (!GlobalName)
3156     GlobalName = ".str";
3157   // Create a global variable for this.
3158   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3159                                   GlobalName, Alignment);
3160   if (Entry)
3161     *Entry = GV;
3162   return ConstantAddress(GV, Alignment);
3163 }
3164 
3165 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3166     const MaterializeTemporaryExpr *E, const Expr *Init) {
3167   assert((E->getStorageDuration() == SD_Static ||
3168           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3169   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3170 
3171   // If we're not materializing a subobject of the temporary, keep the
3172   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3173   QualType MaterializedType = Init->getType();
3174   if (Init == E->GetTemporaryExpr())
3175     MaterializedType = E->getType();
3176 
3177   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3178 
3179   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3180     return ConstantAddress(Slot, Align);
3181 
3182   // FIXME: If an externally-visible declaration extends multiple temporaries,
3183   // we need to give each temporary the same name in every translation unit (and
3184   // we also need to make the temporaries externally-visible).
3185   SmallString<256> Name;
3186   llvm::raw_svector_ostream Out(Name);
3187   getCXXABI().getMangleContext().mangleReferenceTemporary(
3188       VD, E->getManglingNumber(), Out);
3189 
3190   APValue *Value = nullptr;
3191   if (E->getStorageDuration() == SD_Static) {
3192     // We might have a cached constant initializer for this temporary. Note
3193     // that this might have a different value from the value computed by
3194     // evaluating the initializer if the surrounding constant expression
3195     // modifies the temporary.
3196     Value = getContext().getMaterializedTemporaryValue(E, false);
3197     if (Value && Value->isUninit())
3198       Value = nullptr;
3199   }
3200 
3201   // Try evaluating it now, it might have a constant initializer.
3202   Expr::EvalResult EvalResult;
3203   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3204       !EvalResult.hasSideEffects())
3205     Value = &EvalResult.Val;
3206 
3207   llvm::Constant *InitialValue = nullptr;
3208   bool Constant = false;
3209   llvm::Type *Type;
3210   if (Value) {
3211     // The temporary has a constant initializer, use it.
3212     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3213     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3214     Type = InitialValue->getType();
3215   } else {
3216     // No initializer, the initialization will be provided when we
3217     // initialize the declaration which performed lifetime extension.
3218     Type = getTypes().ConvertTypeForMem(MaterializedType);
3219   }
3220 
3221   // Create a global variable for this lifetime-extended temporary.
3222   llvm::GlobalValue::LinkageTypes Linkage =
3223       getLLVMLinkageVarDefinition(VD, Constant);
3224   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3225     const VarDecl *InitVD;
3226     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3227         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3228       // Temporaries defined inside a class get linkonce_odr linkage because the
3229       // class can be defined in multipe translation units.
3230       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3231     } else {
3232       // There is no need for this temporary to have external linkage if the
3233       // VarDecl has external linkage.
3234       Linkage = llvm::GlobalVariable::InternalLinkage;
3235     }
3236   }
3237   unsigned AddrSpace = GetGlobalVarAddressSpace(
3238       VD, getContext().getTargetAddressSpace(MaterializedType));
3239   auto *GV = new llvm::GlobalVariable(
3240       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3241       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3242       AddrSpace);
3243   setGlobalVisibility(GV, VD);
3244   GV->setAlignment(Align.getQuantity());
3245   if (supportsCOMDAT() && GV->isWeakForLinker())
3246     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3247   if (VD->getTLSKind())
3248     setTLSMode(GV, *VD);
3249   MaterializedGlobalTemporaryMap[E] = GV;
3250   return ConstantAddress(GV, Align);
3251 }
3252 
3253 /// EmitObjCPropertyImplementations - Emit information for synthesized
3254 /// properties for an implementation.
3255 void CodeGenModule::EmitObjCPropertyImplementations(const
3256                                                     ObjCImplementationDecl *D) {
3257   for (const auto *PID : D->property_impls()) {
3258     // Dynamic is just for type-checking.
3259     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3260       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3261 
3262       // Determine which methods need to be implemented, some may have
3263       // been overridden. Note that ::isPropertyAccessor is not the method
3264       // we want, that just indicates if the decl came from a
3265       // property. What we want to know is if the method is defined in
3266       // this implementation.
3267       if (!D->getInstanceMethod(PD->getGetterName()))
3268         CodeGenFunction(*this).GenerateObjCGetter(
3269                                  const_cast<ObjCImplementationDecl *>(D), PID);
3270       if (!PD->isReadOnly() &&
3271           !D->getInstanceMethod(PD->getSetterName()))
3272         CodeGenFunction(*this).GenerateObjCSetter(
3273                                  const_cast<ObjCImplementationDecl *>(D), PID);
3274     }
3275   }
3276 }
3277 
3278 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3279   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3280   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3281        ivar; ivar = ivar->getNextIvar())
3282     if (ivar->getType().isDestructedType())
3283       return true;
3284 
3285   return false;
3286 }
3287 
3288 static bool AllTrivialInitializers(CodeGenModule &CGM,
3289                                    ObjCImplementationDecl *D) {
3290   CodeGenFunction CGF(CGM);
3291   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3292        E = D->init_end(); B != E; ++B) {
3293     CXXCtorInitializer *CtorInitExp = *B;
3294     Expr *Init = CtorInitExp->getInit();
3295     if (!CGF.isTrivialInitializer(Init))
3296       return false;
3297   }
3298   return true;
3299 }
3300 
3301 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3302 /// for an implementation.
3303 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3304   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3305   if (needsDestructMethod(D)) {
3306     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3307     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3308     ObjCMethodDecl *DTORMethod =
3309       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3310                              cxxSelector, getContext().VoidTy, nullptr, D,
3311                              /*isInstance=*/true, /*isVariadic=*/false,
3312                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3313                              /*isDefined=*/false, ObjCMethodDecl::Required);
3314     D->addInstanceMethod(DTORMethod);
3315     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3316     D->setHasDestructors(true);
3317   }
3318 
3319   // If the implementation doesn't have any ivar initializers, we don't need
3320   // a .cxx_construct.
3321   if (D->getNumIvarInitializers() == 0 ||
3322       AllTrivialInitializers(*this, D))
3323     return;
3324 
3325   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3326   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3327   // The constructor returns 'self'.
3328   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3329                                                 D->getLocation(),
3330                                                 D->getLocation(),
3331                                                 cxxSelector,
3332                                                 getContext().getObjCIdType(),
3333                                                 nullptr, D, /*isInstance=*/true,
3334                                                 /*isVariadic=*/false,
3335                                                 /*isPropertyAccessor=*/true,
3336                                                 /*isImplicitlyDeclared=*/true,
3337                                                 /*isDefined=*/false,
3338                                                 ObjCMethodDecl::Required);
3339   D->addInstanceMethod(CTORMethod);
3340   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3341   D->setHasNonZeroConstructors(true);
3342 }
3343 
3344 /// EmitNamespace - Emit all declarations in a namespace.
3345 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3346   for (auto *I : ND->decls()) {
3347     if (const auto *VD = dyn_cast<VarDecl>(I))
3348       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3349           VD->getTemplateSpecializationKind() != TSK_Undeclared)
3350         continue;
3351     EmitTopLevelDecl(I);
3352   }
3353 }
3354 
3355 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3356 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3357   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3358       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3359     ErrorUnsupported(LSD, "linkage spec");
3360     return;
3361   }
3362 
3363   for (auto *I : LSD->decls()) {
3364     // Meta-data for ObjC class includes references to implemented methods.
3365     // Generate class's method definitions first.
3366     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3367       for (auto *M : OID->methods())
3368         EmitTopLevelDecl(M);
3369     }
3370     EmitTopLevelDecl(I);
3371   }
3372 }
3373 
3374 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3375 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3376   // Ignore dependent declarations.
3377   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3378     return;
3379 
3380   switch (D->getKind()) {
3381   case Decl::CXXConversion:
3382   case Decl::CXXMethod:
3383   case Decl::Function:
3384     // Skip function templates
3385     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3386         cast<FunctionDecl>(D)->isLateTemplateParsed())
3387       return;
3388 
3389     EmitGlobal(cast<FunctionDecl>(D));
3390     // Always provide some coverage mapping
3391     // even for the functions that aren't emitted.
3392     AddDeferredUnusedCoverageMapping(D);
3393     break;
3394 
3395   case Decl::Var:
3396     // Skip variable templates
3397     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3398       return;
3399   case Decl::VarTemplateSpecialization:
3400     EmitGlobal(cast<VarDecl>(D));
3401     break;
3402 
3403   // Indirect fields from global anonymous structs and unions can be
3404   // ignored; only the actual variable requires IR gen support.
3405   case Decl::IndirectField:
3406     break;
3407 
3408   // C++ Decls
3409   case Decl::Namespace:
3410     EmitNamespace(cast<NamespaceDecl>(D));
3411     break;
3412     // No code generation needed.
3413   case Decl::UsingShadow:
3414   case Decl::ClassTemplate:
3415   case Decl::VarTemplate:
3416   case Decl::VarTemplatePartialSpecialization:
3417   case Decl::FunctionTemplate:
3418   case Decl::TypeAliasTemplate:
3419   case Decl::Block:
3420   case Decl::Empty:
3421     break;
3422   case Decl::Using:          // using X; [C++]
3423     if (CGDebugInfo *DI = getModuleDebugInfo())
3424         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3425     return;
3426   case Decl::NamespaceAlias:
3427     if (CGDebugInfo *DI = getModuleDebugInfo())
3428         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3429     return;
3430   case Decl::UsingDirective: // using namespace X; [C++]
3431     if (CGDebugInfo *DI = getModuleDebugInfo())
3432       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3433     return;
3434   case Decl::CXXConstructor:
3435     // Skip function templates
3436     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3437         cast<FunctionDecl>(D)->isLateTemplateParsed())
3438       return;
3439 
3440     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3441     break;
3442   case Decl::CXXDestructor:
3443     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3444       return;
3445     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3446     break;
3447 
3448   case Decl::StaticAssert:
3449     // Nothing to do.
3450     break;
3451 
3452   // Objective-C Decls
3453 
3454   // Forward declarations, no (immediate) code generation.
3455   case Decl::ObjCInterface:
3456   case Decl::ObjCCategory:
3457     break;
3458 
3459   case Decl::ObjCProtocol: {
3460     auto *Proto = cast<ObjCProtocolDecl>(D);
3461     if (Proto->isThisDeclarationADefinition())
3462       ObjCRuntime->GenerateProtocol(Proto);
3463     break;
3464   }
3465 
3466   case Decl::ObjCCategoryImpl:
3467     // Categories have properties but don't support synthesize so we
3468     // can ignore them here.
3469     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3470     break;
3471 
3472   case Decl::ObjCImplementation: {
3473     auto *OMD = cast<ObjCImplementationDecl>(D);
3474     EmitObjCPropertyImplementations(OMD);
3475     EmitObjCIvarInitializations(OMD);
3476     ObjCRuntime->GenerateClass(OMD);
3477     // Emit global variable debug information.
3478     if (CGDebugInfo *DI = getModuleDebugInfo())
3479       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3480         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3481             OMD->getClassInterface()), OMD->getLocation());
3482     break;
3483   }
3484   case Decl::ObjCMethod: {
3485     auto *OMD = cast<ObjCMethodDecl>(D);
3486     // If this is not a prototype, emit the body.
3487     if (OMD->getBody())
3488       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3489     break;
3490   }
3491   case Decl::ObjCCompatibleAlias:
3492     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3493     break;
3494 
3495   case Decl::LinkageSpec:
3496     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3497     break;
3498 
3499   case Decl::FileScopeAsm: {
3500     // File-scope asm is ignored during device-side CUDA compilation.
3501     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3502       break;
3503     auto *AD = cast<FileScopeAsmDecl>(D);
3504     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3505     break;
3506   }
3507 
3508   case Decl::Import: {
3509     auto *Import = cast<ImportDecl>(D);
3510 
3511     // Ignore import declarations that come from imported modules.
3512     if (Import->getImportedOwningModule())
3513       break;
3514     if (CGDebugInfo *DI = getModuleDebugInfo())
3515       DI->EmitImportDecl(*Import);
3516 
3517     ImportedModules.insert(Import->getImportedModule());
3518     break;
3519   }
3520 
3521   case Decl::OMPThreadPrivate:
3522     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3523     break;
3524 
3525   case Decl::ClassTemplateSpecialization: {
3526     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3527     if (DebugInfo &&
3528         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3529         Spec->hasDefinition())
3530       DebugInfo->completeTemplateDefinition(*Spec);
3531     break;
3532   }
3533 
3534   default:
3535     // Make sure we handled everything we should, every other kind is a
3536     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3537     // function. Need to recode Decl::Kind to do that easily.
3538     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3539     break;
3540   }
3541 }
3542 
3543 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3544   // Do we need to generate coverage mapping?
3545   if (!CodeGenOpts.CoverageMapping)
3546     return;
3547   switch (D->getKind()) {
3548   case Decl::CXXConversion:
3549   case Decl::CXXMethod:
3550   case Decl::Function:
3551   case Decl::ObjCMethod:
3552   case Decl::CXXConstructor:
3553   case Decl::CXXDestructor: {
3554     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3555       return;
3556     auto I = DeferredEmptyCoverageMappingDecls.find(D);
3557     if (I == DeferredEmptyCoverageMappingDecls.end())
3558       DeferredEmptyCoverageMappingDecls[D] = true;
3559     break;
3560   }
3561   default:
3562     break;
3563   };
3564 }
3565 
3566 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3567   // Do we need to generate coverage mapping?
3568   if (!CodeGenOpts.CoverageMapping)
3569     return;
3570   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3571     if (Fn->isTemplateInstantiation())
3572       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3573   }
3574   auto I = DeferredEmptyCoverageMappingDecls.find(D);
3575   if (I == DeferredEmptyCoverageMappingDecls.end())
3576     DeferredEmptyCoverageMappingDecls[D] = false;
3577   else
3578     I->second = false;
3579 }
3580 
3581 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3582   std::vector<const Decl *> DeferredDecls;
3583   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
3584     if (!I.second)
3585       continue;
3586     DeferredDecls.push_back(I.first);
3587   }
3588   // Sort the declarations by their location to make sure that the tests get a
3589   // predictable order for the coverage mapping for the unused declarations.
3590   if (CodeGenOpts.DumpCoverageMapping)
3591     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3592               [] (const Decl *LHS, const Decl *RHS) {
3593       return LHS->getLocStart() < RHS->getLocStart();
3594     });
3595   for (const auto *D : DeferredDecls) {
3596     switch (D->getKind()) {
3597     case Decl::CXXConversion:
3598     case Decl::CXXMethod:
3599     case Decl::Function:
3600     case Decl::ObjCMethod: {
3601       CodeGenPGO PGO(*this);
3602       GlobalDecl GD(cast<FunctionDecl>(D));
3603       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3604                                   getFunctionLinkage(GD));
3605       break;
3606     }
3607     case Decl::CXXConstructor: {
3608       CodeGenPGO PGO(*this);
3609       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3610       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3611                                   getFunctionLinkage(GD));
3612       break;
3613     }
3614     case Decl::CXXDestructor: {
3615       CodeGenPGO PGO(*this);
3616       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3617       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3618                                   getFunctionLinkage(GD));
3619       break;
3620     }
3621     default:
3622       break;
3623     };
3624   }
3625 }
3626 
3627 /// Turns the given pointer into a constant.
3628 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3629                                           const void *Ptr) {
3630   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3631   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3632   return llvm::ConstantInt::get(i64, PtrInt);
3633 }
3634 
3635 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3636                                    llvm::NamedMDNode *&GlobalMetadata,
3637                                    GlobalDecl D,
3638                                    llvm::GlobalValue *Addr) {
3639   if (!GlobalMetadata)
3640     GlobalMetadata =
3641       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3642 
3643   // TODO: should we report variant information for ctors/dtors?
3644   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3645                            llvm::ConstantAsMetadata::get(GetPointerConstant(
3646                                CGM.getLLVMContext(), D.getDecl()))};
3647   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3648 }
3649 
3650 /// For each function which is declared within an extern "C" region and marked
3651 /// as 'used', but has internal linkage, create an alias from the unmangled
3652 /// name to the mangled name if possible. People expect to be able to refer
3653 /// to such functions with an unmangled name from inline assembly within the
3654 /// same translation unit.
3655 void CodeGenModule::EmitStaticExternCAliases() {
3656   for (auto &I : StaticExternCValues) {
3657     IdentifierInfo *Name = I.first;
3658     llvm::GlobalValue *Val = I.second;
3659     if (Val && !getModule().getNamedValue(Name->getName()))
3660       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3661   }
3662 }
3663 
3664 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3665                                              GlobalDecl &Result) const {
3666   auto Res = Manglings.find(MangledName);
3667   if (Res == Manglings.end())
3668     return false;
3669   Result = Res->getValue();
3670   return true;
3671 }
3672 
3673 /// Emits metadata nodes associating all the global values in the
3674 /// current module with the Decls they came from.  This is useful for
3675 /// projects using IR gen as a subroutine.
3676 ///
3677 /// Since there's currently no way to associate an MDNode directly
3678 /// with an llvm::GlobalValue, we create a global named metadata
3679 /// with the name 'clang.global.decl.ptrs'.
3680 void CodeGenModule::EmitDeclMetadata() {
3681   llvm::NamedMDNode *GlobalMetadata = nullptr;
3682 
3683   // StaticLocalDeclMap
3684   for (auto &I : MangledDeclNames) {
3685     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3686     EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3687   }
3688 }
3689 
3690 /// Emits metadata nodes for all the local variables in the current
3691 /// function.
3692 void CodeGenFunction::EmitDeclMetadata() {
3693   if (LocalDeclMap.empty()) return;
3694 
3695   llvm::LLVMContext &Context = getLLVMContext();
3696 
3697   // Find the unique metadata ID for this name.
3698   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3699 
3700   llvm::NamedMDNode *GlobalMetadata = nullptr;
3701 
3702   for (auto &I : LocalDeclMap) {
3703     const Decl *D = I.first;
3704     llvm::Value *Addr = I.second.getPointer();
3705     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3706       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3707       Alloca->setMetadata(
3708           DeclPtrKind, llvm::MDNode::get(
3709                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3710     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3711       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3712       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3713     }
3714   }
3715 }
3716 
3717 void CodeGenModule::EmitVersionIdentMetadata() {
3718   llvm::NamedMDNode *IdentMetadata =
3719     TheModule.getOrInsertNamedMetadata("llvm.ident");
3720   std::string Version = getClangFullVersion();
3721   llvm::LLVMContext &Ctx = TheModule.getContext();
3722 
3723   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3724   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3725 }
3726 
3727 void CodeGenModule::EmitTargetMetadata() {
3728   // Warning, new MangledDeclNames may be appended within this loop.
3729   // We rely on MapVector insertions adding new elements to the end
3730   // of the container.
3731   // FIXME: Move this loop into the one target that needs it, and only
3732   // loop over those declarations for which we couldn't emit the target
3733   // metadata when we emitted the declaration.
3734   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3735     auto Val = *(MangledDeclNames.begin() + I);
3736     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3737     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3738     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3739   }
3740 }
3741 
3742 void CodeGenModule::EmitCoverageFile() {
3743   if (!getCodeGenOpts().CoverageFile.empty()) {
3744     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3745       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3746       llvm::LLVMContext &Ctx = TheModule.getContext();
3747       llvm::MDString *CoverageFile =
3748           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3749       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3750         llvm::MDNode *CU = CUNode->getOperand(i);
3751         llvm::Metadata *Elts[] = {CoverageFile, CU};
3752         GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3753       }
3754     }
3755   }
3756 }
3757 
3758 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3759   // Sema has checked that all uuid strings are of the form
3760   // "12345678-1234-1234-1234-1234567890ab".
3761   assert(Uuid.size() == 36);
3762   for (unsigned i = 0; i < 36; ++i) {
3763     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3764     else                                         assert(isHexDigit(Uuid[i]));
3765   }
3766 
3767   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3768   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3769 
3770   llvm::Constant *Field3[8];
3771   for (unsigned Idx = 0; Idx < 8; ++Idx)
3772     Field3[Idx] = llvm::ConstantInt::get(
3773         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3774 
3775   llvm::Constant *Fields[4] = {
3776     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3777     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3778     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3779     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3780   };
3781 
3782   return llvm::ConstantStruct::getAnon(Fields);
3783 }
3784 
3785 llvm::Constant *
3786 CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
3787                                             QualType CatchHandlerType) {
3788   return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
3789 }
3790 
3791 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3792                                                        bool ForEH) {
3793   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3794   // FIXME: should we even be calling this method if RTTI is disabled
3795   // and it's not for EH?
3796   if (!ForEH && !getLangOpts().RTTI)
3797     return llvm::Constant::getNullValue(Int8PtrTy);
3798 
3799   if (ForEH && Ty->isObjCObjectPointerType() &&
3800       LangOpts.ObjCRuntime.isGNUFamily())
3801     return ObjCRuntime->GetEHType(Ty);
3802 
3803   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3804 }
3805 
3806 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3807   for (auto RefExpr : D->varlists()) {
3808     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3809     bool PerformInit =
3810         VD->getAnyInitializer() &&
3811         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3812                                                         /*ForRef=*/false);
3813 
3814     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
3815     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
3816             VD, Addr, RefExpr->getLocStart(), PerformInit))
3817       CXXGlobalInits.push_back(InitFunction);
3818   }
3819 }
3820 
3821 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
3822   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
3823   if (InternalId)
3824     return InternalId;
3825 
3826   if (isExternallyVisible(T->getLinkage())) {
3827     std::string OutName;
3828     llvm::raw_string_ostream Out(OutName);
3829     getCXXABI().getMangleContext().mangleTypeName(T, Out);
3830 
3831     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
3832   } else {
3833     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
3834                                            llvm::ArrayRef<llvm::Metadata *>());
3835   }
3836 
3837   return InternalId;
3838 }
3839 
3840 llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry(
3841     llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) {
3842   llvm::Metadata *BitsetOps[] = {
3843       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)),
3844       llvm::ConstantAsMetadata::get(VTable),
3845       llvm::ConstantAsMetadata::get(
3846           llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
3847   return llvm::MDTuple::get(getLLVMContext(), BitsetOps);
3848 }
3849