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