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