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