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