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