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