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