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