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