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