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