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