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