xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 6622029d5ee15bfddacbda4825804ee89f8c30e6)
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       if (!Global->hasAttr<CUDAHostAttr>() && (
1532             Global->hasAttr<CUDADeviceAttr>() ||
1533             Global->hasAttr<CUDAConstantAttr>() ||
1534             Global->hasAttr<CUDASharedAttr>()))
1535         return;
1536     }
1537   }
1538 
1539   // If this is OpenMP device, check if it is legal to emit this global
1540   // normally.
1541   if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1542     return;
1543 
1544   // Ignore declarations, they will be emitted on their first use.
1545   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1546     // Forward declarations are emitted lazily on first use.
1547     if (!FD->doesThisDeclarationHaveABody()) {
1548       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1549         return;
1550 
1551       StringRef MangledName = getMangledName(GD);
1552 
1553       // Compute the function info and LLVM type.
1554       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1555       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1556 
1557       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1558                               /*DontDefer=*/false);
1559       return;
1560     }
1561   } else {
1562     const auto *VD = cast<VarDecl>(Global);
1563     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1564 
1565     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1566         !Context.isMSStaticDataMemberInlineDefinition(VD))
1567       return;
1568   }
1569 
1570   // Defer code generation to first use when possible, e.g. if this is an inline
1571   // function. If the global must always be emitted, do it eagerly if possible
1572   // to benefit from cache locality.
1573   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1574     // Emit the definition if it can't be deferred.
1575     EmitGlobalDefinition(GD);
1576     return;
1577   }
1578 
1579   // If we're deferring emission of a C++ variable with an
1580   // initializer, remember the order in which it appeared in the file.
1581   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1582       cast<VarDecl>(Global)->hasInit()) {
1583     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1584     CXXGlobalInits.push_back(nullptr);
1585   }
1586 
1587   StringRef MangledName = getMangledName(GD);
1588   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1589     // The value has already been used and should therefore be emitted.
1590     addDeferredDeclToEmit(GV, GD);
1591   } else if (MustBeEmitted(Global)) {
1592     // The value must be emitted, but cannot be emitted eagerly.
1593     assert(!MayBeEmittedEagerly(Global));
1594     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1595   } else {
1596     // Otherwise, remember that we saw a deferred decl with this name.  The
1597     // first use of the mangled name will cause it to move into
1598     // DeferredDeclsToEmit.
1599     DeferredDecls[MangledName] = GD;
1600   }
1601 }
1602 
1603 namespace {
1604   struct FunctionIsDirectlyRecursive :
1605     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1606     const StringRef Name;
1607     const Builtin::Context &BI;
1608     bool Result;
1609     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1610       Name(N), BI(C), Result(false) {
1611     }
1612     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1613 
1614     bool TraverseCallExpr(CallExpr *E) {
1615       const FunctionDecl *FD = E->getDirectCallee();
1616       if (!FD)
1617         return true;
1618       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1619       if (Attr && Name == Attr->getLabel()) {
1620         Result = true;
1621         return false;
1622       }
1623       unsigned BuiltinID = FD->getBuiltinID();
1624       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1625         return true;
1626       StringRef BuiltinName = BI.getName(BuiltinID);
1627       if (BuiltinName.startswith("__builtin_") &&
1628           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1629         Result = true;
1630         return false;
1631       }
1632       return true;
1633     }
1634   };
1635 
1636   struct DLLImportFunctionVisitor
1637       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1638     bool SafeToInline = true;
1639 
1640     bool VisitVarDecl(VarDecl *VD) {
1641       // A thread-local variable cannot be imported.
1642       SafeToInline = !VD->getTLSKind();
1643       return SafeToInline;
1644     }
1645 
1646     // Make sure we're not referencing non-imported vars or functions.
1647     bool VisitDeclRefExpr(DeclRefExpr *E) {
1648       ValueDecl *VD = E->getDecl();
1649       if (isa<FunctionDecl>(VD))
1650         SafeToInline = VD->hasAttr<DLLImportAttr>();
1651       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1652         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1653       return SafeToInline;
1654     }
1655     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1656       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1657       return SafeToInline;
1658     }
1659     bool VisitCXXNewExpr(CXXNewExpr *E) {
1660       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1661       return SafeToInline;
1662     }
1663   };
1664 }
1665 
1666 // isTriviallyRecursive - Check if this function calls another
1667 // decl that, because of the asm attribute or the other decl being a builtin,
1668 // ends up pointing to itself.
1669 bool
1670 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1671   StringRef Name;
1672   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1673     // asm labels are a special kind of mangling we have to support.
1674     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1675     if (!Attr)
1676       return false;
1677     Name = Attr->getLabel();
1678   } else {
1679     Name = FD->getName();
1680   }
1681 
1682   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1683   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1684   return Walker.Result;
1685 }
1686 
1687 bool
1688 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1689   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1690     return true;
1691   const auto *F = cast<FunctionDecl>(GD.getDecl());
1692   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1693     return false;
1694 
1695   if (F->hasAttr<DLLImportAttr>()) {
1696     // Check whether it would be safe to inline this dllimport function.
1697     DLLImportFunctionVisitor Visitor;
1698     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1699     if (!Visitor.SafeToInline)
1700       return false;
1701   }
1702 
1703   // PR9614. Avoid cases where the source code is lying to us. An available
1704   // externally function should have an equivalent function somewhere else,
1705   // but a function that calls itself is clearly not equivalent to the real
1706   // implementation.
1707   // This happens in glibc's btowc and in some configure checks.
1708   return !isTriviallyRecursive(F);
1709 }
1710 
1711 /// If the type for the method's class was generated by
1712 /// CGDebugInfo::createContextChain(), the cache contains only a
1713 /// limited DIType without any declarations. Since EmitFunctionStart()
1714 /// needs to find the canonical declaration for each method, we need
1715 /// to construct the complete type prior to emitting the method.
1716 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1717   if (!D->isInstance())
1718     return;
1719 
1720   if (CGDebugInfo *DI = getModuleDebugInfo())
1721     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
1722       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1723       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1724     }
1725 }
1726 
1727 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1728   const auto *D = cast<ValueDecl>(GD.getDecl());
1729 
1730   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1731                                  Context.getSourceManager(),
1732                                  "Generating code for declaration");
1733 
1734   if (isa<FunctionDecl>(D)) {
1735     // At -O0, don't generate IR for functions with available_externally
1736     // linkage.
1737     if (!shouldEmitFunction(GD))
1738       return;
1739 
1740     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1741       CompleteDIClassType(Method);
1742       // Make sure to emit the definition(s) before we emit the thunks.
1743       // This is necessary for the generation of certain thunks.
1744       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1745         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1746       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1747         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1748       else
1749         EmitGlobalFunctionDefinition(GD, GV);
1750 
1751       if (Method->isVirtual())
1752         getVTables().EmitThunks(GD);
1753 
1754       return;
1755     }
1756 
1757     return EmitGlobalFunctionDefinition(GD, GV);
1758   }
1759 
1760   if (const auto *VD = dyn_cast<VarDecl>(D))
1761     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1762 
1763   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1764 }
1765 
1766 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1767                                                       llvm::Function *NewFn);
1768 
1769 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1770 /// module, create and return an llvm Function with the specified type. If there
1771 /// is something in the module with the specified name, return it potentially
1772 /// bitcasted to the right type.
1773 ///
1774 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1775 /// to set the attributes on the function when it is first created.
1776 llvm::Constant *
1777 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1778                                        llvm::Type *Ty,
1779                                        GlobalDecl GD, bool ForVTable,
1780                                        bool DontDefer, bool IsThunk,
1781                                        llvm::AttributeSet ExtraAttrs,
1782                                        bool IsForDefinition) {
1783   const Decl *D = GD.getDecl();
1784 
1785   // Lookup the entry, lazily creating it if necessary.
1786   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1787   if (Entry) {
1788     if (WeakRefReferences.erase(Entry)) {
1789       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1790       if (FD && !FD->hasAttr<WeakAttr>())
1791         Entry->setLinkage(llvm::Function::ExternalLinkage);
1792     }
1793 
1794     // Handle dropped DLL attributes.
1795     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1796       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1797 
1798     // If there are two attempts to define the same mangled name, issue an
1799     // error.
1800     if (IsForDefinition && !Entry->isDeclaration()) {
1801       GlobalDecl OtherGD;
1802       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1803       // to make sure that we issue an error only once.
1804       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1805           (GD.getCanonicalDecl().getDecl() !=
1806            OtherGD.getCanonicalDecl().getDecl()) &&
1807           DiagnosedConflictingDefinitions.insert(GD).second) {
1808         getDiags().Report(D->getLocation(),
1809                           diag::err_duplicate_mangled_name);
1810         getDiags().Report(OtherGD.getDecl()->getLocation(),
1811                           diag::note_previous_definition);
1812       }
1813     }
1814 
1815     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1816         (Entry->getType()->getElementType() == Ty)) {
1817       return Entry;
1818     }
1819 
1820     // Make sure the result is of the correct type.
1821     // (If function is requested for a definition, we always need to create a new
1822     // function, not just return a bitcast.)
1823     if (!IsForDefinition)
1824       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1825   }
1826 
1827   // This function doesn't have a complete type (for example, the return
1828   // type is an incomplete struct). Use a fake type instead, and make
1829   // sure not to try to set attributes.
1830   bool IsIncompleteFunction = false;
1831 
1832   llvm::FunctionType *FTy;
1833   if (isa<llvm::FunctionType>(Ty)) {
1834     FTy = cast<llvm::FunctionType>(Ty);
1835   } else {
1836     FTy = llvm::FunctionType::get(VoidTy, false);
1837     IsIncompleteFunction = true;
1838   }
1839 
1840   llvm::Function *F =
1841       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1842                              Entry ? StringRef() : MangledName, &getModule());
1843 
1844   // If we already created a function with the same mangled name (but different
1845   // type) before, take its name and add it to the list of functions to be
1846   // replaced with F at the end of CodeGen.
1847   //
1848   // This happens if there is a prototype for a function (e.g. "int f()") and
1849   // then a definition of a different type (e.g. "int f(int x)").
1850   if (Entry) {
1851     F->takeName(Entry);
1852 
1853     // This might be an implementation of a function without a prototype, in
1854     // which case, try to do special replacement of calls which match the new
1855     // prototype.  The really key thing here is that we also potentially drop
1856     // arguments from the call site so as to make a direct call, which makes the
1857     // inliner happier and suppresses a number of optimizer warnings (!) about
1858     // dropping arguments.
1859     if (!Entry->use_empty()) {
1860       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
1861       Entry->removeDeadConstantUsers();
1862     }
1863 
1864     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1865         F, Entry->getType()->getElementType()->getPointerTo());
1866     addGlobalValReplacement(Entry, BC);
1867   }
1868 
1869   assert(F->getName() == MangledName && "name was uniqued!");
1870   if (D)
1871     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1872   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1873     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1874     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1875                      llvm::AttributeSet::get(VMContext,
1876                                              llvm::AttributeSet::FunctionIndex,
1877                                              B));
1878   }
1879 
1880   if (!DontDefer) {
1881     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1882     // each other bottoming out with the base dtor.  Therefore we emit non-base
1883     // dtors on usage, even if there is no dtor definition in the TU.
1884     if (D && isa<CXXDestructorDecl>(D) &&
1885         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1886                                            GD.getDtorType()))
1887       addDeferredDeclToEmit(F, GD);
1888 
1889     // This is the first use or definition of a mangled name.  If there is a
1890     // deferred decl with this name, remember that we need to emit it at the end
1891     // of the file.
1892     auto DDI = DeferredDecls.find(MangledName);
1893     if (DDI != DeferredDecls.end()) {
1894       // Move the potentially referenced deferred decl to the
1895       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1896       // don't need it anymore).
1897       addDeferredDeclToEmit(F, DDI->second);
1898       DeferredDecls.erase(DDI);
1899 
1900       // Otherwise, there are cases we have to worry about where we're
1901       // using a declaration for which we must emit a definition but where
1902       // we might not find a top-level definition:
1903       //   - member functions defined inline in their classes
1904       //   - friend functions defined inline in some class
1905       //   - special member functions with implicit definitions
1906       // If we ever change our AST traversal to walk into class methods,
1907       // this will be unnecessary.
1908       //
1909       // We also don't emit a definition for a function if it's going to be an
1910       // entry in a vtable, unless it's already marked as used.
1911     } else if (getLangOpts().CPlusPlus && D) {
1912       // Look for a declaration that's lexically in a record.
1913       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1914            FD = FD->getPreviousDecl()) {
1915         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1916           if (FD->doesThisDeclarationHaveABody()) {
1917             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1918             break;
1919           }
1920         }
1921       }
1922     }
1923   }
1924 
1925   // Make sure the result is of the requested type.
1926   if (!IsIncompleteFunction) {
1927     assert(F->getType()->getElementType() == Ty);
1928     return F;
1929   }
1930 
1931   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1932   return llvm::ConstantExpr::getBitCast(F, PTy);
1933 }
1934 
1935 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1936 /// non-null, then this function will use the specified type if it has to
1937 /// create it (this occurs when we see a definition of the function).
1938 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1939                                                  llvm::Type *Ty,
1940                                                  bool ForVTable,
1941                                                  bool DontDefer,
1942                                                  bool IsForDefinition) {
1943   // If there was no specific requested type, just convert it now.
1944   if (!Ty) {
1945     const auto *FD = cast<FunctionDecl>(GD.getDecl());
1946     auto CanonTy = Context.getCanonicalType(FD->getType());
1947     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
1948   }
1949 
1950   StringRef MangledName = getMangledName(GD);
1951   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
1952                                  /*IsThunk=*/false, llvm::AttributeSet(),
1953                                  IsForDefinition);
1954 }
1955 
1956 /// CreateRuntimeFunction - Create a new runtime function with the specified
1957 /// type and name.
1958 llvm::Constant *
1959 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1960                                      StringRef Name,
1961                                      llvm::AttributeSet ExtraAttrs) {
1962   llvm::Constant *C =
1963       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1964                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1965   if (auto *F = dyn_cast<llvm::Function>(C))
1966     if (F->empty())
1967       F->setCallingConv(getRuntimeCC());
1968   return C;
1969 }
1970 
1971 /// CreateBuiltinFunction - Create a new builtin function with the specified
1972 /// type and name.
1973 llvm::Constant *
1974 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1975                                      StringRef Name,
1976                                      llvm::AttributeSet ExtraAttrs) {
1977   llvm::Constant *C =
1978       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1979                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1980   if (auto *F = dyn_cast<llvm::Function>(C))
1981     if (F->empty())
1982       F->setCallingConv(getBuiltinCC());
1983   return C;
1984 }
1985 
1986 /// isTypeConstant - Determine whether an object of this type can be emitted
1987 /// as a constant.
1988 ///
1989 /// If ExcludeCtor is true, the duration when the object's constructor runs
1990 /// will not be considered. The caller will need to verify that the object is
1991 /// not written to during its construction.
1992 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1993   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1994     return false;
1995 
1996   if (Context.getLangOpts().CPlusPlus) {
1997     if (const CXXRecordDecl *Record
1998           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1999       return ExcludeCtor && !Record->hasMutableFields() &&
2000              Record->hasTrivialDestructor();
2001   }
2002 
2003   return true;
2004 }
2005 
2006 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2007 /// create and return an llvm GlobalVariable with the specified type.  If there
2008 /// is something in the module with the specified name, return it potentially
2009 /// bitcasted to the right type.
2010 ///
2011 /// If D is non-null, it specifies a decl that correspond to this.  This is used
2012 /// to set the attributes on the global when it is first created.
2013 ///
2014 /// If IsForDefinition is true, it is guranteed that an actual global with
2015 /// type Ty will be returned, not conversion of a variable with the same
2016 /// mangled name but some other type.
2017 llvm::Constant *
2018 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2019                                      llvm::PointerType *Ty,
2020                                      const VarDecl *D,
2021                                      bool IsForDefinition) {
2022   // Lookup the entry, lazily creating it if necessary.
2023   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2024   if (Entry) {
2025     if (WeakRefReferences.erase(Entry)) {
2026       if (D && !D->hasAttr<WeakAttr>())
2027         Entry->setLinkage(llvm::Function::ExternalLinkage);
2028     }
2029 
2030     // Handle dropped DLL attributes.
2031     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2032       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2033 
2034     if (Entry->getType() == Ty)
2035       return Entry;
2036 
2037     // If there are two attempts to define the same mangled name, issue an
2038     // error.
2039     if (IsForDefinition && !Entry->isDeclaration()) {
2040       GlobalDecl OtherGD;
2041       const VarDecl *OtherD;
2042 
2043       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2044       // to make sure that we issue an error only once.
2045       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2046           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2047           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2048           OtherD->hasInit() &&
2049           DiagnosedConflictingDefinitions.insert(D).second) {
2050         getDiags().Report(D->getLocation(),
2051                           diag::err_duplicate_mangled_name);
2052         getDiags().Report(OtherGD.getDecl()->getLocation(),
2053                           diag::note_previous_definition);
2054       }
2055     }
2056 
2057     // Make sure the result is of the correct type.
2058     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2059       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2060 
2061     // (If global is requested for a definition, we always need to create a new
2062     // global, not just return a bitcast.)
2063     if (!IsForDefinition)
2064       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2065   }
2066 
2067   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2068   auto *GV = new llvm::GlobalVariable(
2069       getModule(), Ty->getElementType(), false,
2070       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2071       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2072 
2073   // If we already created a global with the same mangled name (but different
2074   // type) before, take its name and remove it from its parent.
2075   if (Entry) {
2076     GV->takeName(Entry);
2077 
2078     if (!Entry->use_empty()) {
2079       llvm::Constant *NewPtrForOldDecl =
2080           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2081       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2082     }
2083 
2084     Entry->eraseFromParent();
2085   }
2086 
2087   // This is the first use or definition of a mangled name.  If there is a
2088   // deferred decl with this name, remember that we need to emit it at the end
2089   // of the file.
2090   auto DDI = DeferredDecls.find(MangledName);
2091   if (DDI != DeferredDecls.end()) {
2092     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2093     // list, and remove it from DeferredDecls (since we don't need it anymore).
2094     addDeferredDeclToEmit(GV, DDI->second);
2095     DeferredDecls.erase(DDI);
2096   }
2097 
2098   // Handle things which are present even on external declarations.
2099   if (D) {
2100     // FIXME: This code is overly simple and should be merged with other global
2101     // handling.
2102     GV->setConstant(isTypeConstant(D->getType(), false));
2103 
2104     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2105 
2106     setLinkageAndVisibilityForGV(GV, D);
2107 
2108     if (D->getTLSKind()) {
2109       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2110         CXXThreadLocals.push_back(D);
2111       setTLSMode(GV, *D);
2112     }
2113 
2114     // If required by the ABI, treat declarations of static data members with
2115     // inline initializers as definitions.
2116     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2117       EmitGlobalVarDefinition(D);
2118     }
2119 
2120     // Handle XCore specific ABI requirements.
2121     if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
2122         D->getLanguageLinkage() == CLanguageLinkage &&
2123         D->getType().isConstant(Context) &&
2124         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2125       GV->setSection(".cp.rodata");
2126   }
2127 
2128   if (AddrSpace != Ty->getAddressSpace())
2129     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2130 
2131   return GV;
2132 }
2133 
2134 llvm::Constant *
2135 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2136                                bool IsForDefinition) {
2137   if (isa<CXXConstructorDecl>(GD.getDecl()))
2138     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
2139                                 getFromCtorType(GD.getCtorType()),
2140                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2141                                 /*DontDefer=*/false, IsForDefinition);
2142   else if (isa<CXXDestructorDecl>(GD.getDecl()))
2143     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
2144                                 getFromDtorType(GD.getDtorType()),
2145                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2146                                 /*DontDefer=*/false, IsForDefinition);
2147   else if (isa<CXXMethodDecl>(GD.getDecl())) {
2148     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2149         cast<CXXMethodDecl>(GD.getDecl()));
2150     auto Ty = getTypes().GetFunctionType(*FInfo);
2151     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2152                              IsForDefinition);
2153   } else if (isa<FunctionDecl>(GD.getDecl())) {
2154     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2155     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2156     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2157                              IsForDefinition);
2158   } else
2159     return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()), /*Ty=*/nullptr,
2160                               IsForDefinition);
2161 }
2162 
2163 llvm::GlobalVariable *
2164 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2165                                       llvm::Type *Ty,
2166                                       llvm::GlobalValue::LinkageTypes Linkage) {
2167   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2168   llvm::GlobalVariable *OldGV = nullptr;
2169 
2170   if (GV) {
2171     // Check if the variable has the right type.
2172     if (GV->getType()->getElementType() == Ty)
2173       return GV;
2174 
2175     // Because C++ name mangling, the only way we can end up with an already
2176     // existing global with the same name is if it has been declared extern "C".
2177     assert(GV->isDeclaration() && "Declaration has wrong type!");
2178     OldGV = GV;
2179   }
2180 
2181   // Create a new variable.
2182   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2183                                 Linkage, nullptr, Name);
2184 
2185   if (OldGV) {
2186     // Replace occurrences of the old variable if needed.
2187     GV->takeName(OldGV);
2188 
2189     if (!OldGV->use_empty()) {
2190       llvm::Constant *NewPtrForOldDecl =
2191       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2192       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2193     }
2194 
2195     OldGV->eraseFromParent();
2196   }
2197 
2198   if (supportsCOMDAT() && GV->isWeakForLinker() &&
2199       !GV->hasAvailableExternallyLinkage())
2200     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2201 
2202   return GV;
2203 }
2204 
2205 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2206 /// given global variable.  If Ty is non-null and if the global doesn't exist,
2207 /// then it will be created with the specified type instead of whatever the
2208 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2209 /// that an actual global with type Ty will be returned, not conversion of a
2210 /// variable with the same mangled name but some other type.
2211 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2212                                                   llvm::Type *Ty,
2213                                                   bool IsForDefinition) {
2214   assert(D->hasGlobalStorage() && "Not a global variable");
2215   QualType ASTTy = D->getType();
2216   if (!Ty)
2217     Ty = getTypes().ConvertTypeForMem(ASTTy);
2218 
2219   llvm::PointerType *PTy =
2220     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2221 
2222   StringRef MangledName = getMangledName(D);
2223   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2224 }
2225 
2226 /// CreateRuntimeVariable - Create a new runtime global variable with the
2227 /// specified type and name.
2228 llvm::Constant *
2229 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2230                                      StringRef Name) {
2231   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2232 }
2233 
2234 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2235   assert(!D->getInit() && "Cannot emit definite definitions here!");
2236 
2237   StringRef MangledName = getMangledName(D);
2238   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2239 
2240   // We already have a definition, not declaration, with the same mangled name.
2241   // Emitting of declaration is not required (and actually overwrites emitted
2242   // definition).
2243   if (GV && !GV->isDeclaration())
2244     return;
2245 
2246   // If we have not seen a reference to this variable yet, place it into the
2247   // deferred declarations table to be emitted if needed later.
2248   if (!MustBeEmitted(D) && !GV) {
2249       DeferredDecls[MangledName] = D;
2250       return;
2251   }
2252 
2253   // The tentative definition is the only definition.
2254   EmitGlobalVarDefinition(D);
2255 }
2256 
2257 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2258   return Context.toCharUnitsFromBits(
2259       getDataLayout().getTypeStoreSizeInBits(Ty));
2260 }
2261 
2262 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2263                                                  unsigned AddrSpace) {
2264   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2265     if (D->hasAttr<CUDAConstantAttr>())
2266       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2267     else if (D->hasAttr<CUDASharedAttr>())
2268       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2269     else
2270       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2271   }
2272 
2273   return AddrSpace;
2274 }
2275 
2276 template<typename SomeDecl>
2277 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2278                                                llvm::GlobalValue *GV) {
2279   if (!getLangOpts().CPlusPlus)
2280     return;
2281 
2282   // Must have 'used' attribute, or else inline assembly can't rely on
2283   // the name existing.
2284   if (!D->template hasAttr<UsedAttr>())
2285     return;
2286 
2287   // Must have internal linkage and an ordinary name.
2288   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2289     return;
2290 
2291   // Must be in an extern "C" context. Entities declared directly within
2292   // a record are not extern "C" even if the record is in such a context.
2293   const SomeDecl *First = D->getFirstDecl();
2294   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2295     return;
2296 
2297   // OK, this is an internal linkage entity inside an extern "C" linkage
2298   // specification. Make a note of that so we can give it the "expected"
2299   // mangled name if nothing else is using that name.
2300   std::pair<StaticExternCMap::iterator, bool> R =
2301       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2302 
2303   // If we have multiple internal linkage entities with the same name
2304   // in extern "C" regions, none of them gets that name.
2305   if (!R.second)
2306     R.first->second = nullptr;
2307 }
2308 
2309 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2310   if (!CGM.supportsCOMDAT())
2311     return false;
2312 
2313   if (D.hasAttr<SelectAnyAttr>())
2314     return true;
2315 
2316   GVALinkage Linkage;
2317   if (auto *VD = dyn_cast<VarDecl>(&D))
2318     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2319   else
2320     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2321 
2322   switch (Linkage) {
2323   case GVA_Internal:
2324   case GVA_AvailableExternally:
2325   case GVA_StrongExternal:
2326     return false;
2327   case GVA_DiscardableODR:
2328   case GVA_StrongODR:
2329     return true;
2330   }
2331   llvm_unreachable("No such linkage");
2332 }
2333 
2334 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2335                                           llvm::GlobalObject &GO) {
2336   if (!shouldBeInCOMDAT(*this, D))
2337     return;
2338   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2339 }
2340 
2341 /// Pass IsTentative as true if you want to create a tentative definition.
2342 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2343                                             bool IsTentative) {
2344   llvm::Constant *Init = nullptr;
2345   QualType ASTTy = D->getType();
2346   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2347   bool NeedsGlobalCtor = false;
2348   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2349 
2350   const VarDecl *InitDecl;
2351   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2352 
2353   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2354   // as part of their declaration."  Sema has already checked for
2355   // error cases, so we just need to set Init to UndefValue.
2356   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2357       D->hasAttr<CUDASharedAttr>())
2358     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2359   else if (!InitExpr) {
2360     // This is a tentative definition; tentative definitions are
2361     // implicitly initialized with { 0 }.
2362     //
2363     // Note that tentative definitions are only emitted at the end of
2364     // a translation unit, so they should never have incomplete
2365     // type. In addition, EmitTentativeDefinition makes sure that we
2366     // never attempt to emit a tentative definition if a real one
2367     // exists. A use may still exists, however, so we still may need
2368     // to do a RAUW.
2369     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2370     Init = EmitNullConstant(D->getType());
2371   } else {
2372     initializedGlobalDecl = GlobalDecl(D);
2373     Init = EmitConstantInit(*InitDecl);
2374 
2375     if (!Init) {
2376       QualType T = InitExpr->getType();
2377       if (D->getType()->isReferenceType())
2378         T = D->getType();
2379 
2380       if (getLangOpts().CPlusPlus) {
2381         Init = EmitNullConstant(T);
2382         NeedsGlobalCtor = true;
2383       } else {
2384         ErrorUnsupported(D, "static initializer");
2385         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2386       }
2387     } else {
2388       // We don't need an initializer, so remove the entry for the delayed
2389       // initializer position (just in case this entry was delayed) if we
2390       // also don't need to register a destructor.
2391       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2392         DelayedCXXInitPosition.erase(D);
2393     }
2394   }
2395 
2396   llvm::Type* InitType = Init->getType();
2397   llvm::Constant *Entry =
2398       GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative);
2399 
2400   // Strip off a bitcast if we got one back.
2401   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2402     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2403            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2404            // All zero index gep.
2405            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2406     Entry = CE->getOperand(0);
2407   }
2408 
2409   // Entry is now either a Function or GlobalVariable.
2410   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2411 
2412   // We have a definition after a declaration with the wrong type.
2413   // We must make a new GlobalVariable* and update everything that used OldGV
2414   // (a declaration or tentative definition) with the new GlobalVariable*
2415   // (which will be a definition).
2416   //
2417   // This happens if there is a prototype for a global (e.g.
2418   // "extern int x[];") and then a definition of a different type (e.g.
2419   // "int x[10];"). This also happens when an initializer has a different type
2420   // from the type of the global (this happens with unions).
2421   if (!GV ||
2422       GV->getType()->getElementType() != InitType ||
2423       GV->getType()->getAddressSpace() !=
2424        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2425 
2426     // Move the old entry aside so that we'll create a new one.
2427     Entry->setName(StringRef());
2428 
2429     // Make a new global with the correct type, this is now guaranteed to work.
2430     GV = cast<llvm::GlobalVariable>(
2431         GetAddrOfGlobalVar(D, InitType, /*IsForDefinition=*/!IsTentative));
2432 
2433     // Replace all uses of the old global with the new global
2434     llvm::Constant *NewPtrForOldDecl =
2435         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2436     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2437 
2438     // Erase the old global, since it is no longer used.
2439     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2440   }
2441 
2442   MaybeHandleStaticInExternC(D, GV);
2443 
2444   if (D->hasAttr<AnnotateAttr>())
2445     AddGlobalAnnotations(D, GV);
2446 
2447   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2448   // the device. [...]"
2449   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2450   // __device__, declares a variable that: [...]
2451   // Is accessible from all the threads within the grid and from the host
2452   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2453   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2454   if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice &&
2455       (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) {
2456     GV->setExternallyInitialized(true);
2457   }
2458   GV->setInitializer(Init);
2459 
2460   // If it is safe to mark the global 'constant', do so now.
2461   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2462                   isTypeConstant(D->getType(), true));
2463 
2464   // If it is in a read-only section, mark it 'constant'.
2465   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2466     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2467     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2468       GV->setConstant(true);
2469   }
2470 
2471   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2472 
2473   // Set the llvm linkage type as appropriate.
2474   llvm::GlobalValue::LinkageTypes Linkage =
2475       getLLVMLinkageVarDefinition(D, GV->isConstant());
2476 
2477   // On Darwin, if the normal linkage of a C++ thread_local variable is
2478   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2479   // copies within a linkage unit; otherwise, the backing variable has
2480   // internal linkage and all accesses should just be calls to the
2481   // Itanium-specified entry point, which has the normal linkage of the
2482   // variable. This is to preserve the ability to change the implementation
2483   // behind the scenes.
2484   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2485       Context.getTargetInfo().getTriple().isOSDarwin() &&
2486       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2487       !llvm::GlobalVariable::isWeakLinkage(Linkage))
2488     Linkage = llvm::GlobalValue::InternalLinkage;
2489 
2490   GV->setLinkage(Linkage);
2491   if (D->hasAttr<DLLImportAttr>())
2492     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2493   else if (D->hasAttr<DLLExportAttr>())
2494     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2495   else
2496     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2497 
2498   if (Linkage == llvm::GlobalVariable::CommonLinkage)
2499     // common vars aren't constant even if declared const.
2500     GV->setConstant(false);
2501 
2502   setNonAliasAttributes(D, GV);
2503 
2504   if (D->getTLSKind() && !GV->isThreadLocal()) {
2505     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2506       CXXThreadLocals.push_back(D);
2507     setTLSMode(GV, *D);
2508   }
2509 
2510   maybeSetTrivialComdat(*D, *GV);
2511 
2512   // Emit the initializer function if necessary.
2513   if (NeedsGlobalCtor || NeedsGlobalDtor)
2514     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2515 
2516   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2517 
2518   // Emit global variable debug information.
2519   if (CGDebugInfo *DI = getModuleDebugInfo())
2520     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2521       DI->EmitGlobalVariable(GV, D);
2522 }
2523 
2524 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2525                                       CodeGenModule &CGM, const VarDecl *D,
2526                                       bool NoCommon) {
2527   // Don't give variables common linkage if -fno-common was specified unless it
2528   // was overridden by a NoCommon attribute.
2529   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2530     return true;
2531 
2532   // C11 6.9.2/2:
2533   //   A declaration of an identifier for an object that has file scope without
2534   //   an initializer, and without a storage-class specifier or with the
2535   //   storage-class specifier static, constitutes a tentative definition.
2536   if (D->getInit() || D->hasExternalStorage())
2537     return true;
2538 
2539   // A variable cannot be both common and exist in a section.
2540   if (D->hasAttr<SectionAttr>())
2541     return true;
2542 
2543   // Thread local vars aren't considered common linkage.
2544   if (D->getTLSKind())
2545     return true;
2546 
2547   // Tentative definitions marked with WeakImportAttr are true definitions.
2548   if (D->hasAttr<WeakImportAttr>())
2549     return true;
2550 
2551   // A variable cannot be both common and exist in a comdat.
2552   if (shouldBeInCOMDAT(CGM, *D))
2553     return true;
2554 
2555   // Declarations with a required alignment do not have common linakge in MSVC
2556   // mode.
2557   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2558     if (D->hasAttr<AlignedAttr>())
2559       return true;
2560     QualType VarType = D->getType();
2561     if (Context.isAlignmentRequired(VarType))
2562       return true;
2563 
2564     if (const auto *RT = VarType->getAs<RecordType>()) {
2565       const RecordDecl *RD = RT->getDecl();
2566       for (const FieldDecl *FD : RD->fields()) {
2567         if (FD->isBitField())
2568           continue;
2569         if (FD->hasAttr<AlignedAttr>())
2570           return true;
2571         if (Context.isAlignmentRequired(FD->getType()))
2572           return true;
2573       }
2574     }
2575   }
2576 
2577   return false;
2578 }
2579 
2580 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2581     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2582   if (Linkage == GVA_Internal)
2583     return llvm::Function::InternalLinkage;
2584 
2585   if (D->hasAttr<WeakAttr>()) {
2586     if (IsConstantVariable)
2587       return llvm::GlobalVariable::WeakODRLinkage;
2588     else
2589       return llvm::GlobalVariable::WeakAnyLinkage;
2590   }
2591 
2592   // We are guaranteed to have a strong definition somewhere else,
2593   // so we can use available_externally linkage.
2594   if (Linkage == GVA_AvailableExternally)
2595     return llvm::Function::AvailableExternallyLinkage;
2596 
2597   // Note that Apple's kernel linker doesn't support symbol
2598   // coalescing, so we need to avoid linkonce and weak linkages there.
2599   // Normally, this means we just map to internal, but for explicit
2600   // instantiations we'll map to external.
2601 
2602   // In C++, the compiler has to emit a definition in every translation unit
2603   // that references the function.  We should use linkonce_odr because
2604   // a) if all references in this translation unit are optimized away, we
2605   // don't need to codegen it.  b) if the function persists, it needs to be
2606   // merged with other definitions. c) C++ has the ODR, so we know the
2607   // definition is dependable.
2608   if (Linkage == GVA_DiscardableODR)
2609     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2610                                             : llvm::Function::InternalLinkage;
2611 
2612   // An explicit instantiation of a template has weak linkage, since
2613   // explicit instantiations can occur in multiple translation units
2614   // and must all be equivalent. However, we are not allowed to
2615   // throw away these explicit instantiations.
2616   if (Linkage == GVA_StrongODR)
2617     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2618                                             : llvm::Function::ExternalLinkage;
2619 
2620   // C++ doesn't have tentative definitions and thus cannot have common
2621   // linkage.
2622   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2623       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2624                                  CodeGenOpts.NoCommon))
2625     return llvm::GlobalVariable::CommonLinkage;
2626 
2627   // selectany symbols are externally visible, so use weak instead of
2628   // linkonce.  MSVC optimizes away references to const selectany globals, so
2629   // all definitions should be the same and ODR linkage should be used.
2630   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2631   if (D->hasAttr<SelectAnyAttr>())
2632     return llvm::GlobalVariable::WeakODRLinkage;
2633 
2634   // Otherwise, we have strong external linkage.
2635   assert(Linkage == GVA_StrongExternal);
2636   return llvm::GlobalVariable::ExternalLinkage;
2637 }
2638 
2639 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2640     const VarDecl *VD, bool IsConstant) {
2641   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2642   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2643 }
2644 
2645 /// Replace the uses of a function that was declared with a non-proto type.
2646 /// We want to silently drop extra arguments from call sites
2647 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2648                                           llvm::Function *newFn) {
2649   // Fast path.
2650   if (old->use_empty()) return;
2651 
2652   llvm::Type *newRetTy = newFn->getReturnType();
2653   SmallVector<llvm::Value*, 4> newArgs;
2654   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2655 
2656   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2657          ui != ue; ) {
2658     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2659     llvm::User *user = use->getUser();
2660 
2661     // Recognize and replace uses of bitcasts.  Most calls to
2662     // unprototyped functions will use bitcasts.
2663     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2664       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2665         replaceUsesOfNonProtoConstant(bitcast, newFn);
2666       continue;
2667     }
2668 
2669     // Recognize calls to the function.
2670     llvm::CallSite callSite(user);
2671     if (!callSite) continue;
2672     if (!callSite.isCallee(&*use)) continue;
2673 
2674     // If the return types don't match exactly, then we can't
2675     // transform this call unless it's dead.
2676     if (callSite->getType() != newRetTy && !callSite->use_empty())
2677       continue;
2678 
2679     // Get the call site's attribute list.
2680     SmallVector<llvm::AttributeSet, 8> newAttrs;
2681     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2682 
2683     // Collect any return attributes from the call.
2684     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2685       newAttrs.push_back(
2686         llvm::AttributeSet::get(newFn->getContext(),
2687                                 oldAttrs.getRetAttributes()));
2688 
2689     // If the function was passed too few arguments, don't transform.
2690     unsigned newNumArgs = newFn->arg_size();
2691     if (callSite.arg_size() < newNumArgs) continue;
2692 
2693     // If extra arguments were passed, we silently drop them.
2694     // If any of the types mismatch, we don't transform.
2695     unsigned argNo = 0;
2696     bool dontTransform = false;
2697     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2698            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2699       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2700         dontTransform = true;
2701         break;
2702       }
2703 
2704       // Add any parameter attributes.
2705       if (oldAttrs.hasAttributes(argNo + 1))
2706         newAttrs.
2707           push_back(llvm::
2708                     AttributeSet::get(newFn->getContext(),
2709                                       oldAttrs.getParamAttributes(argNo + 1)));
2710     }
2711     if (dontTransform)
2712       continue;
2713 
2714     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2715       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2716                                                  oldAttrs.getFnAttributes()));
2717 
2718     // Okay, we can transform this.  Create the new call instruction and copy
2719     // over the required information.
2720     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2721 
2722     // Copy over any operand bundles.
2723     callSite.getOperandBundlesAsDefs(newBundles);
2724 
2725     llvm::CallSite newCall;
2726     if (callSite.isCall()) {
2727       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2728                                        callSite.getInstruction());
2729     } else {
2730       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2731       newCall = llvm::InvokeInst::Create(newFn,
2732                                          oldInvoke->getNormalDest(),
2733                                          oldInvoke->getUnwindDest(),
2734                                          newArgs, newBundles, "",
2735                                          callSite.getInstruction());
2736     }
2737     newArgs.clear(); // for the next iteration
2738 
2739     if (!newCall->getType()->isVoidTy())
2740       newCall->takeName(callSite.getInstruction());
2741     newCall.setAttributes(
2742                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2743     newCall.setCallingConv(callSite.getCallingConv());
2744 
2745     // Finally, remove the old call, replacing any uses with the new one.
2746     if (!callSite->use_empty())
2747       callSite->replaceAllUsesWith(newCall.getInstruction());
2748 
2749     // Copy debug location attached to CI.
2750     if (callSite->getDebugLoc())
2751       newCall->setDebugLoc(callSite->getDebugLoc());
2752 
2753     callSite->eraseFromParent();
2754   }
2755 }
2756 
2757 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2758 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2759 /// existing call uses of the old function in the module, this adjusts them to
2760 /// call the new function directly.
2761 ///
2762 /// This is not just a cleanup: the always_inline pass requires direct calls to
2763 /// functions to be able to inline them.  If there is a bitcast in the way, it
2764 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2765 /// run at -O0.
2766 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2767                                                       llvm::Function *NewFn) {
2768   // If we're redefining a global as a function, don't transform it.
2769   if (!isa<llvm::Function>(Old)) return;
2770 
2771   replaceUsesOfNonProtoConstant(Old, NewFn);
2772 }
2773 
2774 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2775   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2776   // If we have a definition, this might be a deferred decl. If the
2777   // instantiation is explicit, make sure we emit it at the end.
2778   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2779     GetAddrOfGlobalVar(VD);
2780 
2781   EmitTopLevelDecl(VD);
2782 }
2783 
2784 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2785                                                  llvm::GlobalValue *GV) {
2786   const auto *D = cast<FunctionDecl>(GD.getDecl());
2787 
2788   // Compute the function info and LLVM type.
2789   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2790   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2791 
2792   // Get or create the prototype for the function.
2793   if (!GV || (GV->getType()->getElementType() != Ty))
2794     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
2795                                                    /*DontDefer=*/true,
2796                                                    /*IsForDefinition=*/true));
2797 
2798   // Already emitted.
2799   if (!GV->isDeclaration())
2800     return;
2801 
2802   // We need to set linkage and visibility on the function before
2803   // generating code for it because various parts of IR generation
2804   // want to propagate this information down (e.g. to local static
2805   // declarations).
2806   auto *Fn = cast<llvm::Function>(GV);
2807   setFunctionLinkage(GD, Fn);
2808   setFunctionDLLStorageClass(GD, Fn);
2809 
2810   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2811   setGlobalVisibility(Fn, D);
2812 
2813   MaybeHandleStaticInExternC(D, Fn);
2814 
2815   maybeSetTrivialComdat(*D, *Fn);
2816 
2817   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2818 
2819   setFunctionDefinitionAttributes(D, Fn);
2820   SetLLVMFunctionAttributesForDefinition(D, Fn);
2821 
2822   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2823     AddGlobalCtor(Fn, CA->getPriority());
2824   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2825     AddGlobalDtor(Fn, DA->getPriority());
2826   if (D->hasAttr<AnnotateAttr>())
2827     AddGlobalAnnotations(D, Fn);
2828 }
2829 
2830 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2831   const auto *D = cast<ValueDecl>(GD.getDecl());
2832   const AliasAttr *AA = D->getAttr<AliasAttr>();
2833   assert(AA && "Not an alias?");
2834 
2835   StringRef MangledName = getMangledName(GD);
2836 
2837   if (AA->getAliasee() == MangledName) {
2838     Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2839     return;
2840   }
2841 
2842   // If there is a definition in the module, then it wins over the alias.
2843   // This is dubious, but allow it to be safe.  Just ignore the alias.
2844   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2845   if (Entry && !Entry->isDeclaration())
2846     return;
2847 
2848   Aliases.push_back(GD);
2849 
2850   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2851 
2852   // Create a reference to the named value.  This ensures that it is emitted
2853   // if a deferred decl.
2854   llvm::Constant *Aliasee;
2855   if (isa<llvm::FunctionType>(DeclTy))
2856     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2857                                       /*ForVTable=*/false);
2858   else
2859     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2860                                     llvm::PointerType::getUnqual(DeclTy),
2861                                     /*D=*/nullptr);
2862 
2863   // Create the new alias itself, but don't set a name yet.
2864   auto *GA = llvm::GlobalAlias::create(
2865       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2866 
2867   if (Entry) {
2868     if (GA->getAliasee() == Entry) {
2869       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2870       return;
2871     }
2872 
2873     assert(Entry->isDeclaration());
2874 
2875     // If there is a declaration in the module, then we had an extern followed
2876     // by the alias, as in:
2877     //   extern int test6();
2878     //   ...
2879     //   int test6() __attribute__((alias("test7")));
2880     //
2881     // Remove it and replace uses of it with the alias.
2882     GA->takeName(Entry);
2883 
2884     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2885                                                           Entry->getType()));
2886     Entry->eraseFromParent();
2887   } else {
2888     GA->setName(MangledName);
2889   }
2890 
2891   // Set attributes which are particular to an alias; this is a
2892   // specialization of the attributes which may be set on a global
2893   // variable/function.
2894   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2895       D->isWeakImported()) {
2896     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2897   }
2898 
2899   if (const auto *VD = dyn_cast<VarDecl>(D))
2900     if (VD->getTLSKind())
2901       setTLSMode(GA, *VD);
2902 
2903   setAliasAttributes(D, GA);
2904 }
2905 
2906 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2907                                             ArrayRef<llvm::Type*> Tys) {
2908   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2909                                          Tys);
2910 }
2911 
2912 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2913 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2914                          const StringLiteral *Literal, bool TargetIsLSB,
2915                          bool &IsUTF16, unsigned &StringLength) {
2916   StringRef String = Literal->getString();
2917   unsigned NumBytes = String.size();
2918 
2919   // Check for simple case.
2920   if (!Literal->containsNonAsciiOrNull()) {
2921     StringLength = NumBytes;
2922     return *Map.insert(std::make_pair(String, nullptr)).first;
2923   }
2924 
2925   // Otherwise, convert the UTF8 literals into a string of shorts.
2926   IsUTF16 = true;
2927 
2928   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2929   const UTF8 *FromPtr = (const UTF8 *)String.data();
2930   UTF16 *ToPtr = &ToBuf[0];
2931 
2932   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2933                            &ToPtr, ToPtr + NumBytes,
2934                            strictConversion);
2935 
2936   // ConvertUTF8toUTF16 returns the length in ToPtr.
2937   StringLength = ToPtr - &ToBuf[0];
2938 
2939   // Add an explicit null.
2940   *ToPtr = 0;
2941   return *Map.insert(std::make_pair(
2942                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2943                                    (StringLength + 1) * 2),
2944                          nullptr)).first;
2945 }
2946 
2947 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2948 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2949                        const StringLiteral *Literal, unsigned &StringLength) {
2950   StringRef String = Literal->getString();
2951   StringLength = String.size();
2952   return *Map.insert(std::make_pair(String, nullptr)).first;
2953 }
2954 
2955 ConstantAddress
2956 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2957   unsigned StringLength = 0;
2958   bool isUTF16 = false;
2959   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2960       GetConstantCFStringEntry(CFConstantStringMap, Literal,
2961                                getDataLayout().isLittleEndian(), isUTF16,
2962                                StringLength);
2963 
2964   if (auto *C = Entry.second)
2965     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2966 
2967   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2968   llvm::Constant *Zeros[] = { Zero, Zero };
2969   llvm::Value *V;
2970 
2971   // If we don't already have it, get __CFConstantStringClassReference.
2972   if (!CFConstantStringClassRef) {
2973     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2974     Ty = llvm::ArrayType::get(Ty, 0);
2975     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2976                                            "__CFConstantStringClassReference");
2977     // Decay array -> ptr
2978     V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2979     CFConstantStringClassRef = V;
2980   }
2981   else
2982     V = CFConstantStringClassRef;
2983 
2984   QualType CFTy = getContext().getCFConstantStringType();
2985 
2986   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2987 
2988   llvm::Constant *Fields[4];
2989 
2990   // Class pointer.
2991   Fields[0] = cast<llvm::ConstantExpr>(V);
2992 
2993   // Flags.
2994   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2995   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2996     llvm::ConstantInt::get(Ty, 0x07C8);
2997 
2998   // String pointer.
2999   llvm::Constant *C = nullptr;
3000   if (isUTF16) {
3001     auto Arr = llvm::makeArrayRef(
3002         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3003         Entry.first().size() / 2);
3004     C = llvm::ConstantDataArray::get(VMContext, Arr);
3005   } else {
3006     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3007   }
3008 
3009   // Note: -fwritable-strings doesn't make the backing store strings of
3010   // CFStrings writable. (See <rdar://problem/10657500>)
3011   auto *GV =
3012       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3013                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3014   GV->setUnnamedAddr(true);
3015   // Don't enforce the target's minimum global alignment, since the only use
3016   // of the string is via this class initializer.
3017   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
3018   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
3019   // that changes the section it ends in, which surprises ld64.
3020   if (isUTF16) {
3021     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
3022     GV->setAlignment(Align.getQuantity());
3023     GV->setSection("__TEXT,__ustring");
3024   } else {
3025     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
3026     GV->setAlignment(Align.getQuantity());
3027     GV->setSection("__TEXT,__cstring,cstring_literals");
3028   }
3029 
3030   // String.
3031   Fields[2] =
3032       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3033 
3034   if (isUTF16)
3035     // Cast the UTF16 string to the correct type.
3036     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
3037 
3038   // String length.
3039   Ty = getTypes().ConvertType(getContext().LongTy);
3040   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
3041 
3042   CharUnits Alignment = getPointerAlign();
3043 
3044   // The struct.
3045   C = llvm::ConstantStruct::get(STy, Fields);
3046   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3047                                 llvm::GlobalVariable::PrivateLinkage, C,
3048                                 "_unnamed_cfstring_");
3049   GV->setSection("__DATA,__cfstring");
3050   GV->setAlignment(Alignment.getQuantity());
3051   Entry.second = GV;
3052 
3053   return ConstantAddress(GV, Alignment);
3054 }
3055 
3056 ConstantAddress
3057 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
3058   unsigned StringLength = 0;
3059   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3060       GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
3061 
3062   if (auto *C = Entry.second)
3063     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3064 
3065   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3066   llvm::Constant *Zeros[] = { Zero, Zero };
3067   llvm::Value *V;
3068   // If we don't already have it, get _NSConstantStringClassReference.
3069   if (!ConstantStringClassRef) {
3070     std::string StringClass(getLangOpts().ObjCConstantStringClass);
3071     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3072     llvm::Constant *GV;
3073     if (LangOpts.ObjCRuntime.isNonFragile()) {
3074       std::string str =
3075         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
3076                             : "OBJC_CLASS_$_" + StringClass;
3077       GV = getObjCRuntime().GetClassGlobal(str);
3078       // Make sure the result is of the correct type.
3079       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3080       V = llvm::ConstantExpr::getBitCast(GV, PTy);
3081       ConstantStringClassRef = V;
3082     } else {
3083       std::string str =
3084         StringClass.empty() ? "_NSConstantStringClassReference"
3085                             : "_" + StringClass + "ClassReference";
3086       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
3087       GV = CreateRuntimeVariable(PTy, str);
3088       // Decay array -> ptr
3089       V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
3090       ConstantStringClassRef = V;
3091     }
3092   } else
3093     V = ConstantStringClassRef;
3094 
3095   if (!NSConstantStringType) {
3096     // Construct the type for a constant NSString.
3097     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
3098     D->startDefinition();
3099 
3100     QualType FieldTypes[3];
3101 
3102     // const int *isa;
3103     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
3104     // const char *str;
3105     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
3106     // unsigned int length;
3107     FieldTypes[2] = Context.UnsignedIntTy;
3108 
3109     // Create fields
3110     for (unsigned i = 0; i < 3; ++i) {
3111       FieldDecl *Field = FieldDecl::Create(Context, D,
3112                                            SourceLocation(),
3113                                            SourceLocation(), nullptr,
3114                                            FieldTypes[i], /*TInfo=*/nullptr,
3115                                            /*BitWidth=*/nullptr,
3116                                            /*Mutable=*/false,
3117                                            ICIS_NoInit);
3118       Field->setAccess(AS_public);
3119       D->addDecl(Field);
3120     }
3121 
3122     D->completeDefinition();
3123     QualType NSTy = Context.getTagDeclType(D);
3124     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
3125   }
3126 
3127   llvm::Constant *Fields[3];
3128 
3129   // Class pointer.
3130   Fields[0] = cast<llvm::ConstantExpr>(V);
3131 
3132   // String pointer.
3133   llvm::Constant *C =
3134       llvm::ConstantDataArray::getString(VMContext, Entry.first());
3135 
3136   llvm::GlobalValue::LinkageTypes Linkage;
3137   bool isConstant;
3138   Linkage = llvm::GlobalValue::PrivateLinkage;
3139   isConstant = !LangOpts.WritableStrings;
3140 
3141   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
3142                                       Linkage, C, ".str");
3143   GV->setUnnamedAddr(true);
3144   // Don't enforce the target's minimum global alignment, since the only use
3145   // of the string is via this class initializer.
3146   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
3147   GV->setAlignment(Align.getQuantity());
3148   Fields[1] =
3149       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3150 
3151   // String length.
3152   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
3153   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
3154 
3155   // The struct.
3156   CharUnits Alignment = getPointerAlign();
3157   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
3158   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3159                                 llvm::GlobalVariable::PrivateLinkage, C,
3160                                 "_unnamed_nsstring_");
3161   GV->setAlignment(Alignment.getQuantity());
3162   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
3163   const char *NSStringNonFragileABISection =
3164       "__DATA,__objc_stringobj,regular,no_dead_strip";
3165   // FIXME. Fix section.
3166   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
3167                      ? NSStringNonFragileABISection
3168                      : NSStringSection);
3169   Entry.second = GV;
3170 
3171   return ConstantAddress(GV, Alignment);
3172 }
3173 
3174 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3175   if (ObjCFastEnumerationStateType.isNull()) {
3176     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3177     D->startDefinition();
3178 
3179     QualType FieldTypes[] = {
3180       Context.UnsignedLongTy,
3181       Context.getPointerType(Context.getObjCIdType()),
3182       Context.getPointerType(Context.UnsignedLongTy),
3183       Context.getConstantArrayType(Context.UnsignedLongTy,
3184                            llvm::APInt(32, 5), ArrayType::Normal, 0)
3185     };
3186 
3187     for (size_t i = 0; i < 4; ++i) {
3188       FieldDecl *Field = FieldDecl::Create(Context,
3189                                            D,
3190                                            SourceLocation(),
3191                                            SourceLocation(), nullptr,
3192                                            FieldTypes[i], /*TInfo=*/nullptr,
3193                                            /*BitWidth=*/nullptr,
3194                                            /*Mutable=*/false,
3195                                            ICIS_NoInit);
3196       Field->setAccess(AS_public);
3197       D->addDecl(Field);
3198     }
3199 
3200     D->completeDefinition();
3201     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3202   }
3203 
3204   return ObjCFastEnumerationStateType;
3205 }
3206 
3207 llvm::Constant *
3208 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3209   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3210 
3211   // Don't emit it as the address of the string, emit the string data itself
3212   // as an inline array.
3213   if (E->getCharByteWidth() == 1) {
3214     SmallString<64> Str(E->getString());
3215 
3216     // Resize the string to the right size, which is indicated by its type.
3217     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3218     Str.resize(CAT->getSize().getZExtValue());
3219     return llvm::ConstantDataArray::getString(VMContext, Str, false);
3220   }
3221 
3222   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3223   llvm::Type *ElemTy = AType->getElementType();
3224   unsigned NumElements = AType->getNumElements();
3225 
3226   // Wide strings have either 2-byte or 4-byte elements.
3227   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3228     SmallVector<uint16_t, 32> Elements;
3229     Elements.reserve(NumElements);
3230 
3231     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3232       Elements.push_back(E->getCodeUnit(i));
3233     Elements.resize(NumElements);
3234     return llvm::ConstantDataArray::get(VMContext, Elements);
3235   }
3236 
3237   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3238   SmallVector<uint32_t, 32> Elements;
3239   Elements.reserve(NumElements);
3240 
3241   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3242     Elements.push_back(E->getCodeUnit(i));
3243   Elements.resize(NumElements);
3244   return llvm::ConstantDataArray::get(VMContext, Elements);
3245 }
3246 
3247 static llvm::GlobalVariable *
3248 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3249                       CodeGenModule &CGM, StringRef GlobalName,
3250                       CharUnits Alignment) {
3251   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3252   unsigned AddrSpace = 0;
3253   if (CGM.getLangOpts().OpenCL)
3254     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3255 
3256   llvm::Module &M = CGM.getModule();
3257   // Create a global variable for this string
3258   auto *GV = new llvm::GlobalVariable(
3259       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3260       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3261   GV->setAlignment(Alignment.getQuantity());
3262   GV->setUnnamedAddr(true);
3263   if (GV->isWeakForLinker()) {
3264     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3265     GV->setComdat(M.getOrInsertComdat(GV->getName()));
3266   }
3267 
3268   return GV;
3269 }
3270 
3271 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3272 /// constant array for the given string literal.
3273 ConstantAddress
3274 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3275                                                   StringRef Name) {
3276   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3277 
3278   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3279   llvm::GlobalVariable **Entry = nullptr;
3280   if (!LangOpts.WritableStrings) {
3281     Entry = &ConstantStringMap[C];
3282     if (auto GV = *Entry) {
3283       if (Alignment.getQuantity() > GV->getAlignment())
3284         GV->setAlignment(Alignment.getQuantity());
3285       return ConstantAddress(GV, Alignment);
3286     }
3287   }
3288 
3289   SmallString<256> MangledNameBuffer;
3290   StringRef GlobalVariableName;
3291   llvm::GlobalValue::LinkageTypes LT;
3292 
3293   // Mangle the string literal if the ABI allows for it.  However, we cannot
3294   // do this if  we are compiling with ASan or -fwritable-strings because they
3295   // rely on strings having normal linkage.
3296   if (!LangOpts.WritableStrings &&
3297       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3298       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3299     llvm::raw_svector_ostream Out(MangledNameBuffer);
3300     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3301 
3302     LT = llvm::GlobalValue::LinkOnceODRLinkage;
3303     GlobalVariableName = MangledNameBuffer;
3304   } else {
3305     LT = llvm::GlobalValue::PrivateLinkage;
3306     GlobalVariableName = Name;
3307   }
3308 
3309   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3310   if (Entry)
3311     *Entry = GV;
3312 
3313   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3314                                   QualType());
3315   return ConstantAddress(GV, Alignment);
3316 }
3317 
3318 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3319 /// array for the given ObjCEncodeExpr node.
3320 ConstantAddress
3321 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3322   std::string Str;
3323   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3324 
3325   return GetAddrOfConstantCString(Str);
3326 }
3327 
3328 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3329 /// the literal and a terminating '\0' character.
3330 /// The result has pointer to array type.
3331 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3332     const std::string &Str, const char *GlobalName) {
3333   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3334   CharUnits Alignment =
3335     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3336 
3337   llvm::Constant *C =
3338       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3339 
3340   // Don't share any string literals if strings aren't constant.
3341   llvm::GlobalVariable **Entry = nullptr;
3342   if (!LangOpts.WritableStrings) {
3343     Entry = &ConstantStringMap[C];
3344     if (auto GV = *Entry) {
3345       if (Alignment.getQuantity() > GV->getAlignment())
3346         GV->setAlignment(Alignment.getQuantity());
3347       return ConstantAddress(GV, Alignment);
3348     }
3349   }
3350 
3351   // Get the default prefix if a name wasn't specified.
3352   if (!GlobalName)
3353     GlobalName = ".str";
3354   // Create a global variable for this.
3355   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3356                                   GlobalName, Alignment);
3357   if (Entry)
3358     *Entry = GV;
3359   return ConstantAddress(GV, Alignment);
3360 }
3361 
3362 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3363     const MaterializeTemporaryExpr *E, const Expr *Init) {
3364   assert((E->getStorageDuration() == SD_Static ||
3365           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3366   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3367 
3368   // If we're not materializing a subobject of the temporary, keep the
3369   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3370   QualType MaterializedType = Init->getType();
3371   if (Init == E->GetTemporaryExpr())
3372     MaterializedType = E->getType();
3373 
3374   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3375 
3376   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3377     return ConstantAddress(Slot, Align);
3378 
3379   // FIXME: If an externally-visible declaration extends multiple temporaries,
3380   // we need to give each temporary the same name in every translation unit (and
3381   // we also need to make the temporaries externally-visible).
3382   SmallString<256> Name;
3383   llvm::raw_svector_ostream Out(Name);
3384   getCXXABI().getMangleContext().mangleReferenceTemporary(
3385       VD, E->getManglingNumber(), Out);
3386 
3387   APValue *Value = nullptr;
3388   if (E->getStorageDuration() == SD_Static) {
3389     // We might have a cached constant initializer for this temporary. Note
3390     // that this might have a different value from the value computed by
3391     // evaluating the initializer if the surrounding constant expression
3392     // modifies the temporary.
3393     Value = getContext().getMaterializedTemporaryValue(E, false);
3394     if (Value && Value->isUninit())
3395       Value = nullptr;
3396   }
3397 
3398   // Try evaluating it now, it might have a constant initializer.
3399   Expr::EvalResult EvalResult;
3400   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3401       !EvalResult.hasSideEffects())
3402     Value = &EvalResult.Val;
3403 
3404   llvm::Constant *InitialValue = nullptr;
3405   bool Constant = false;
3406   llvm::Type *Type;
3407   if (Value) {
3408     // The temporary has a constant initializer, use it.
3409     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3410     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3411     Type = InitialValue->getType();
3412   } else {
3413     // No initializer, the initialization will be provided when we
3414     // initialize the declaration which performed lifetime extension.
3415     Type = getTypes().ConvertTypeForMem(MaterializedType);
3416   }
3417 
3418   // Create a global variable for this lifetime-extended temporary.
3419   llvm::GlobalValue::LinkageTypes Linkage =
3420       getLLVMLinkageVarDefinition(VD, Constant);
3421   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3422     const VarDecl *InitVD;
3423     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3424         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3425       // Temporaries defined inside a class get linkonce_odr linkage because the
3426       // class can be defined in multipe translation units.
3427       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3428     } else {
3429       // There is no need for this temporary to have external linkage if the
3430       // VarDecl has external linkage.
3431       Linkage = llvm::GlobalVariable::InternalLinkage;
3432     }
3433   }
3434   unsigned AddrSpace = GetGlobalVarAddressSpace(
3435       VD, getContext().getTargetAddressSpace(MaterializedType));
3436   auto *GV = new llvm::GlobalVariable(
3437       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3438       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3439       AddrSpace);
3440   setGlobalVisibility(GV, VD);
3441   GV->setAlignment(Align.getQuantity());
3442   if (supportsCOMDAT() && GV->isWeakForLinker())
3443     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3444   if (VD->getTLSKind())
3445     setTLSMode(GV, *VD);
3446   MaterializedGlobalTemporaryMap[E] = GV;
3447   return ConstantAddress(GV, Align);
3448 }
3449 
3450 /// EmitObjCPropertyImplementations - Emit information for synthesized
3451 /// properties for an implementation.
3452 void CodeGenModule::EmitObjCPropertyImplementations(const
3453                                                     ObjCImplementationDecl *D) {
3454   for (const auto *PID : D->property_impls()) {
3455     // Dynamic is just for type-checking.
3456     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3457       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3458 
3459       // Determine which methods need to be implemented, some may have
3460       // been overridden. Note that ::isPropertyAccessor is not the method
3461       // we want, that just indicates if the decl came from a
3462       // property. What we want to know is if the method is defined in
3463       // this implementation.
3464       if (!D->getInstanceMethod(PD->getGetterName()))
3465         CodeGenFunction(*this).GenerateObjCGetter(
3466                                  const_cast<ObjCImplementationDecl *>(D), PID);
3467       if (!PD->isReadOnly() &&
3468           !D->getInstanceMethod(PD->getSetterName()))
3469         CodeGenFunction(*this).GenerateObjCSetter(
3470                                  const_cast<ObjCImplementationDecl *>(D), PID);
3471     }
3472   }
3473 }
3474 
3475 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3476   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3477   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3478        ivar; ivar = ivar->getNextIvar())
3479     if (ivar->getType().isDestructedType())
3480       return true;
3481 
3482   return false;
3483 }
3484 
3485 static bool AllTrivialInitializers(CodeGenModule &CGM,
3486                                    ObjCImplementationDecl *D) {
3487   CodeGenFunction CGF(CGM);
3488   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3489        E = D->init_end(); B != E; ++B) {
3490     CXXCtorInitializer *CtorInitExp = *B;
3491     Expr *Init = CtorInitExp->getInit();
3492     if (!CGF.isTrivialInitializer(Init))
3493       return false;
3494   }
3495   return true;
3496 }
3497 
3498 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3499 /// for an implementation.
3500 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3501   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3502   if (needsDestructMethod(D)) {
3503     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3504     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3505     ObjCMethodDecl *DTORMethod =
3506       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3507                              cxxSelector, getContext().VoidTy, nullptr, D,
3508                              /*isInstance=*/true, /*isVariadic=*/false,
3509                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3510                              /*isDefined=*/false, ObjCMethodDecl::Required);
3511     D->addInstanceMethod(DTORMethod);
3512     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3513     D->setHasDestructors(true);
3514   }
3515 
3516   // If the implementation doesn't have any ivar initializers, we don't need
3517   // a .cxx_construct.
3518   if (D->getNumIvarInitializers() == 0 ||
3519       AllTrivialInitializers(*this, D))
3520     return;
3521 
3522   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3523   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3524   // The constructor returns 'self'.
3525   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3526                                                 D->getLocation(),
3527                                                 D->getLocation(),
3528                                                 cxxSelector,
3529                                                 getContext().getObjCIdType(),
3530                                                 nullptr, D, /*isInstance=*/true,
3531                                                 /*isVariadic=*/false,
3532                                                 /*isPropertyAccessor=*/true,
3533                                                 /*isImplicitlyDeclared=*/true,
3534                                                 /*isDefined=*/false,
3535                                                 ObjCMethodDecl::Required);
3536   D->addInstanceMethod(CTORMethod);
3537   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3538   D->setHasNonZeroConstructors(true);
3539 }
3540 
3541 /// EmitNamespace - Emit all declarations in a namespace.
3542 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3543   for (auto *I : ND->decls()) {
3544     if (const auto *VD = dyn_cast<VarDecl>(I))
3545       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3546           VD->getTemplateSpecializationKind() != TSK_Undeclared)
3547         continue;
3548     EmitTopLevelDecl(I);
3549   }
3550 }
3551 
3552 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3553 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3554   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3555       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3556     ErrorUnsupported(LSD, "linkage spec");
3557     return;
3558   }
3559 
3560   for (auto *I : LSD->decls()) {
3561     // Meta-data for ObjC class includes references to implemented methods.
3562     // Generate class's method definitions first.
3563     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3564       for (auto *M : OID->methods())
3565         EmitTopLevelDecl(M);
3566     }
3567     EmitTopLevelDecl(I);
3568   }
3569 }
3570 
3571 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3572 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3573   // Ignore dependent declarations.
3574   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3575     return;
3576 
3577   switch (D->getKind()) {
3578   case Decl::CXXConversion:
3579   case Decl::CXXMethod:
3580   case Decl::Function:
3581     // Skip function templates
3582     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3583         cast<FunctionDecl>(D)->isLateTemplateParsed())
3584       return;
3585 
3586     EmitGlobal(cast<FunctionDecl>(D));
3587     // Always provide some coverage mapping
3588     // even for the functions that aren't emitted.
3589     AddDeferredUnusedCoverageMapping(D);
3590     break;
3591 
3592   case Decl::Var:
3593     // Skip variable templates
3594     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3595       return;
3596   case Decl::VarTemplateSpecialization:
3597     EmitGlobal(cast<VarDecl>(D));
3598     break;
3599 
3600   // Indirect fields from global anonymous structs and unions can be
3601   // ignored; only the actual variable requires IR gen support.
3602   case Decl::IndirectField:
3603     break;
3604 
3605   // C++ Decls
3606   case Decl::Namespace:
3607     EmitNamespace(cast<NamespaceDecl>(D));
3608     break;
3609     // No code generation needed.
3610   case Decl::UsingShadow:
3611   case Decl::ClassTemplate:
3612   case Decl::VarTemplate:
3613   case Decl::VarTemplatePartialSpecialization:
3614   case Decl::FunctionTemplate:
3615   case Decl::TypeAliasTemplate:
3616   case Decl::Block:
3617   case Decl::Empty:
3618     break;
3619   case Decl::Using:          // using X; [C++]
3620     if (CGDebugInfo *DI = getModuleDebugInfo())
3621         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3622     return;
3623   case Decl::NamespaceAlias:
3624     if (CGDebugInfo *DI = getModuleDebugInfo())
3625         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3626     return;
3627   case Decl::UsingDirective: // using namespace X; [C++]
3628     if (CGDebugInfo *DI = getModuleDebugInfo())
3629       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3630     return;
3631   case Decl::CXXConstructor:
3632     // Skip function templates
3633     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3634         cast<FunctionDecl>(D)->isLateTemplateParsed())
3635       return;
3636 
3637     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3638     break;
3639   case Decl::CXXDestructor:
3640     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3641       return;
3642     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3643     break;
3644 
3645   case Decl::StaticAssert:
3646     // Nothing to do.
3647     break;
3648 
3649   // Objective-C Decls
3650 
3651   // Forward declarations, no (immediate) code generation.
3652   case Decl::ObjCInterface:
3653   case Decl::ObjCCategory:
3654     break;
3655 
3656   case Decl::ObjCProtocol: {
3657     auto *Proto = cast<ObjCProtocolDecl>(D);
3658     if (Proto->isThisDeclarationADefinition())
3659       ObjCRuntime->GenerateProtocol(Proto);
3660     break;
3661   }
3662 
3663   case Decl::ObjCCategoryImpl:
3664     // Categories have properties but don't support synthesize so we
3665     // can ignore them here.
3666     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3667     break;
3668 
3669   case Decl::ObjCImplementation: {
3670     auto *OMD = cast<ObjCImplementationDecl>(D);
3671     EmitObjCPropertyImplementations(OMD);
3672     EmitObjCIvarInitializations(OMD);
3673     ObjCRuntime->GenerateClass(OMD);
3674     // Emit global variable debug information.
3675     if (CGDebugInfo *DI = getModuleDebugInfo())
3676       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3677         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3678             OMD->getClassInterface()), OMD->getLocation());
3679     break;
3680   }
3681   case Decl::ObjCMethod: {
3682     auto *OMD = cast<ObjCMethodDecl>(D);
3683     // If this is not a prototype, emit the body.
3684     if (OMD->getBody())
3685       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3686     break;
3687   }
3688   case Decl::ObjCCompatibleAlias:
3689     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3690     break;
3691 
3692   case Decl::PragmaComment: {
3693     const auto *PCD = cast<PragmaCommentDecl>(D);
3694     switch (PCD->getCommentKind()) {
3695     case PCK_Unknown:
3696       llvm_unreachable("unexpected pragma comment kind");
3697     case PCK_Linker:
3698       AppendLinkerOptions(PCD->getArg());
3699       break;
3700     case PCK_Lib:
3701       AddDependentLib(PCD->getArg());
3702       break;
3703     case PCK_Compiler:
3704     case PCK_ExeStr:
3705     case PCK_User:
3706       break; // We ignore all of these.
3707     }
3708     break;
3709   }
3710 
3711   case Decl::LinkageSpec:
3712     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3713     break;
3714 
3715   case Decl::FileScopeAsm: {
3716     // File-scope asm is ignored during device-side CUDA compilation.
3717     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3718       break;
3719     // File-scope asm is ignored during device-side OpenMP compilation.
3720     if (LangOpts.OpenMPIsDevice)
3721       break;
3722     auto *AD = cast<FileScopeAsmDecl>(D);
3723     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3724     break;
3725   }
3726 
3727   case Decl::Import: {
3728     auto *Import = cast<ImportDecl>(D);
3729 
3730     // Ignore import declarations that come from imported modules.
3731     if (Import->getImportedOwningModule())
3732       break;
3733     if (CGDebugInfo *DI = getModuleDebugInfo())
3734       DI->EmitImportDecl(*Import);
3735 
3736     ImportedModules.insert(Import->getImportedModule());
3737     break;
3738   }
3739 
3740   case Decl::OMPThreadPrivate:
3741     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3742     break;
3743 
3744   case Decl::ClassTemplateSpecialization: {
3745     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3746     if (DebugInfo &&
3747         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3748         Spec->hasDefinition())
3749       DebugInfo->completeTemplateDefinition(*Spec);
3750     break;
3751   }
3752 
3753   default:
3754     // Make sure we handled everything we should, every other kind is a
3755     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3756     // function. Need to recode Decl::Kind to do that easily.
3757     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3758     break;
3759   }
3760 }
3761 
3762 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3763   // Do we need to generate coverage mapping?
3764   if (!CodeGenOpts.CoverageMapping)
3765     return;
3766   switch (D->getKind()) {
3767   case Decl::CXXConversion:
3768   case Decl::CXXMethod:
3769   case Decl::Function:
3770   case Decl::ObjCMethod:
3771   case Decl::CXXConstructor:
3772   case Decl::CXXDestructor: {
3773     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3774       return;
3775     auto I = DeferredEmptyCoverageMappingDecls.find(D);
3776     if (I == DeferredEmptyCoverageMappingDecls.end())
3777       DeferredEmptyCoverageMappingDecls[D] = true;
3778     break;
3779   }
3780   default:
3781     break;
3782   };
3783 }
3784 
3785 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3786   // Do we need to generate coverage mapping?
3787   if (!CodeGenOpts.CoverageMapping)
3788     return;
3789   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3790     if (Fn->isTemplateInstantiation())
3791       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3792   }
3793   auto I = DeferredEmptyCoverageMappingDecls.find(D);
3794   if (I == DeferredEmptyCoverageMappingDecls.end())
3795     DeferredEmptyCoverageMappingDecls[D] = false;
3796   else
3797     I->second = false;
3798 }
3799 
3800 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3801   std::vector<const Decl *> DeferredDecls;
3802   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
3803     if (!I.second)
3804       continue;
3805     DeferredDecls.push_back(I.first);
3806   }
3807   // Sort the declarations by their location to make sure that the tests get a
3808   // predictable order for the coverage mapping for the unused declarations.
3809   if (CodeGenOpts.DumpCoverageMapping)
3810     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3811               [] (const Decl *LHS, const Decl *RHS) {
3812       return LHS->getLocStart() < RHS->getLocStart();
3813     });
3814   for (const auto *D : DeferredDecls) {
3815     switch (D->getKind()) {
3816     case Decl::CXXConversion:
3817     case Decl::CXXMethod:
3818     case Decl::Function:
3819     case Decl::ObjCMethod: {
3820       CodeGenPGO PGO(*this);
3821       GlobalDecl GD(cast<FunctionDecl>(D));
3822       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3823                                   getFunctionLinkage(GD));
3824       break;
3825     }
3826     case Decl::CXXConstructor: {
3827       CodeGenPGO PGO(*this);
3828       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3829       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3830                                   getFunctionLinkage(GD));
3831       break;
3832     }
3833     case Decl::CXXDestructor: {
3834       CodeGenPGO PGO(*this);
3835       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3836       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3837                                   getFunctionLinkage(GD));
3838       break;
3839     }
3840     default:
3841       break;
3842     };
3843   }
3844 }
3845 
3846 /// Turns the given pointer into a constant.
3847 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3848                                           const void *Ptr) {
3849   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3850   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3851   return llvm::ConstantInt::get(i64, PtrInt);
3852 }
3853 
3854 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3855                                    llvm::NamedMDNode *&GlobalMetadata,
3856                                    GlobalDecl D,
3857                                    llvm::GlobalValue *Addr) {
3858   if (!GlobalMetadata)
3859     GlobalMetadata =
3860       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3861 
3862   // TODO: should we report variant information for ctors/dtors?
3863   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3864                            llvm::ConstantAsMetadata::get(GetPointerConstant(
3865                                CGM.getLLVMContext(), D.getDecl()))};
3866   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3867 }
3868 
3869 /// For each function which is declared within an extern "C" region and marked
3870 /// as 'used', but has internal linkage, create an alias from the unmangled
3871 /// name to the mangled name if possible. People expect to be able to refer
3872 /// to such functions with an unmangled name from inline assembly within the
3873 /// same translation unit.
3874 void CodeGenModule::EmitStaticExternCAliases() {
3875   // Don't do anything if we're generating CUDA device code -- the NVPTX
3876   // assembly target doesn't support aliases.
3877   if (Context.getTargetInfo().getTriple().isNVPTX())
3878     return;
3879   for (auto &I : StaticExternCValues) {
3880     IdentifierInfo *Name = I.first;
3881     llvm::GlobalValue *Val = I.second;
3882     if (Val && !getModule().getNamedValue(Name->getName()))
3883       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3884   }
3885 }
3886 
3887 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3888                                              GlobalDecl &Result) const {
3889   auto Res = Manglings.find(MangledName);
3890   if (Res == Manglings.end())
3891     return false;
3892   Result = Res->getValue();
3893   return true;
3894 }
3895 
3896 /// Emits metadata nodes associating all the global values in the
3897 /// current module with the Decls they came from.  This is useful for
3898 /// projects using IR gen as a subroutine.
3899 ///
3900 /// Since there's currently no way to associate an MDNode directly
3901 /// with an llvm::GlobalValue, we create a global named metadata
3902 /// with the name 'clang.global.decl.ptrs'.
3903 void CodeGenModule::EmitDeclMetadata() {
3904   llvm::NamedMDNode *GlobalMetadata = nullptr;
3905 
3906   for (auto &I : MangledDeclNames) {
3907     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3908     // Some mangled names don't necessarily have an associated GlobalValue
3909     // in this module, e.g. if we mangled it for DebugInfo.
3910     if (Addr)
3911       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3912   }
3913 }
3914 
3915 /// Emits metadata nodes for all the local variables in the current
3916 /// function.
3917 void CodeGenFunction::EmitDeclMetadata() {
3918   if (LocalDeclMap.empty()) return;
3919 
3920   llvm::LLVMContext &Context = getLLVMContext();
3921 
3922   // Find the unique metadata ID for this name.
3923   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3924 
3925   llvm::NamedMDNode *GlobalMetadata = nullptr;
3926 
3927   for (auto &I : LocalDeclMap) {
3928     const Decl *D = I.first;
3929     llvm::Value *Addr = I.second.getPointer();
3930     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3931       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3932       Alloca->setMetadata(
3933           DeclPtrKind, llvm::MDNode::get(
3934                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3935     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3936       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3937       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3938     }
3939   }
3940 }
3941 
3942 void CodeGenModule::EmitVersionIdentMetadata() {
3943   llvm::NamedMDNode *IdentMetadata =
3944     TheModule.getOrInsertNamedMetadata("llvm.ident");
3945   std::string Version = getClangFullVersion();
3946   llvm::LLVMContext &Ctx = TheModule.getContext();
3947 
3948   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3949   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3950 }
3951 
3952 void CodeGenModule::EmitTargetMetadata() {
3953   // Warning, new MangledDeclNames may be appended within this loop.
3954   // We rely on MapVector insertions adding new elements to the end
3955   // of the container.
3956   // FIXME: Move this loop into the one target that needs it, and only
3957   // loop over those declarations for which we couldn't emit the target
3958   // metadata when we emitted the declaration.
3959   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3960     auto Val = *(MangledDeclNames.begin() + I);
3961     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3962     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3963     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3964   }
3965 }
3966 
3967 void CodeGenModule::EmitCoverageFile() {
3968   if (!getCodeGenOpts().CoverageFile.empty()) {
3969     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3970       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3971       llvm::LLVMContext &Ctx = TheModule.getContext();
3972       llvm::MDString *CoverageFile =
3973           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3974       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3975         llvm::MDNode *CU = CUNode->getOperand(i);
3976         llvm::Metadata *Elts[] = {CoverageFile, CU};
3977         GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3978       }
3979     }
3980   }
3981 }
3982 
3983 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3984   // Sema has checked that all uuid strings are of the form
3985   // "12345678-1234-1234-1234-1234567890ab".
3986   assert(Uuid.size() == 36);
3987   for (unsigned i = 0; i < 36; ++i) {
3988     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3989     else                                         assert(isHexDigit(Uuid[i]));
3990   }
3991 
3992   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3993   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3994 
3995   llvm::Constant *Field3[8];
3996   for (unsigned Idx = 0; Idx < 8; ++Idx)
3997     Field3[Idx] = llvm::ConstantInt::get(
3998         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3999 
4000   llvm::Constant *Fields[4] = {
4001     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4002     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4003     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4004     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4005   };
4006 
4007   return llvm::ConstantStruct::getAnon(Fields);
4008 }
4009 
4010 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4011                                                        bool ForEH) {
4012   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4013   // FIXME: should we even be calling this method if RTTI is disabled
4014   // and it's not for EH?
4015   if (!ForEH && !getLangOpts().RTTI)
4016     return llvm::Constant::getNullValue(Int8PtrTy);
4017 
4018   if (ForEH && Ty->isObjCObjectPointerType() &&
4019       LangOpts.ObjCRuntime.isGNUFamily())
4020     return ObjCRuntime->GetEHType(Ty);
4021 
4022   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4023 }
4024 
4025 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4026   for (auto RefExpr : D->varlists()) {
4027     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4028     bool PerformInit =
4029         VD->getAnyInitializer() &&
4030         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4031                                                         /*ForRef=*/false);
4032 
4033     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4034     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4035             VD, Addr, RefExpr->getLocStart(), PerformInit))
4036       CXXGlobalInits.push_back(InitFunction);
4037   }
4038 }
4039 
4040 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4041   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4042   if (InternalId)
4043     return InternalId;
4044 
4045   if (isExternallyVisible(T->getLinkage())) {
4046     std::string OutName;
4047     llvm::raw_string_ostream Out(OutName);
4048     getCXXABI().getMangleContext().mangleTypeName(T, Out);
4049 
4050     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4051   } else {
4052     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4053                                            llvm::ArrayRef<llvm::Metadata *>());
4054   }
4055 
4056   return InternalId;
4057 }
4058 
4059 /// Returns whether this module needs the "all-vtables" bitset.
4060 bool CodeGenModule::NeedAllVtablesBitSet() const {
4061   // Returns true if at least one of vtable-based CFI checkers is enabled and
4062   // is not in the trapping mode.
4063   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4064            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4065           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4066            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4067           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4068            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4069           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4070            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4071 }
4072 
4073 void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
4074                                             llvm::GlobalVariable *VTable,
4075                                             CharUnits Offset,
4076                                             const CXXRecordDecl *RD) {
4077   llvm::Metadata *MD =
4078       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4079   llvm::Metadata *BitsetOps[] = {
4080       MD, llvm::ConstantAsMetadata::get(VTable),
4081       llvm::ConstantAsMetadata::get(
4082           llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
4083   BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
4084 
4085   if (CodeGenOpts.SanitizeCfiCrossDso) {
4086     if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) {
4087       llvm::Metadata *BitsetOps2[] = {
4088           llvm::ConstantAsMetadata::get(TypeId),
4089           llvm::ConstantAsMetadata::get(VTable),
4090           llvm::ConstantAsMetadata::get(
4091               llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
4092       BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2));
4093     }
4094   }
4095 
4096   if (NeedAllVtablesBitSet()) {
4097     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4098     llvm::Metadata *BitsetOps[] = {
4099         MD, llvm::ConstantAsMetadata::get(VTable),
4100         llvm::ConstantAsMetadata::get(
4101             llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
4102     // Avoid adding a node to BitsetsMD twice.
4103     if (!llvm::MDTuple::getIfExists(getLLVMContext(), BitsetOps))
4104       BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
4105   }
4106 }
4107 
4108 // Fills in the supplied string map with the set of target features for the
4109 // passed in function.
4110 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4111                                           const FunctionDecl *FD) {
4112   StringRef TargetCPU = Target.getTargetOpts().CPU;
4113   if (const auto *TD = FD->getAttr<TargetAttr>()) {
4114     // If we have a TargetAttr build up the feature map based on that.
4115     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4116 
4117     // Make a copy of the features as passed on the command line into the
4118     // beginning of the additional features from the function to override.
4119     ParsedAttr.first.insert(ParsedAttr.first.begin(),
4120                             Target.getTargetOpts().FeaturesAsWritten.begin(),
4121                             Target.getTargetOpts().FeaturesAsWritten.end());
4122 
4123     if (ParsedAttr.second != "")
4124       TargetCPU = ParsedAttr.second;
4125 
4126     // Now populate the feature map, first with the TargetCPU which is either
4127     // the default or a new one from the target attribute string. Then we'll use
4128     // the passed in features (FeaturesAsWritten) along with the new ones from
4129     // the attribute.
4130     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4131   } else {
4132     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4133                           Target.getTargetOpts().Features);
4134   }
4135 }
4136 
4137 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4138   if (!SanStats)
4139     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4140 
4141   return *SanStats;
4142 }
4143