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