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