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