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