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