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