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