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