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