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