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