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