Coverage Report

Created: 2021-06-15 06:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CodeGenModule.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This coordinates the per-module state used while generating code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CodeGenModule.h"
14
#include "CGBlocks.h"
15
#include "CGCUDARuntime.h"
16
#include "CGCXXABI.h"
17
#include "CGCall.h"
18
#include "CGDebugInfo.h"
19
#include "CGObjCRuntime.h"
20
#include "CGOpenCLRuntime.h"
21
#include "CGOpenMPRuntime.h"
22
#include "CGOpenMPRuntimeAMDGCN.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"
36
#include "clang/AST/RecursiveASTVisitor.h"
37
#include "clang/AST/StmtVisitor.h"
38
#include "clang/Basic/Builtins.h"
39
#include "clang/Basic/CharInfo.h"
40
#include "clang/Basic/CodeGenOptions.h"
41
#include "clang/Basic/Diagnostic.h"
42
#include "clang/Basic/FileManager.h"
43
#include "clang/Basic/Module.h"
44
#include "clang/Basic/SourceManager.h"
45
#include "clang/Basic/TargetInfo.h"
46
#include "clang/Basic/Version.h"
47
#include "clang/CodeGen/ConstantInitBuilder.h"
48
#include "clang/Frontend/FrontendDiagnostic.h"
49
#include "llvm/ADT/StringSwitch.h"
50
#include "llvm/ADT/Triple.h"
51
#include "llvm/Analysis/TargetLibraryInfo.h"
52
#include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
53
#include "llvm/IR/CallingConv.h"
54
#include "llvm/IR/DataLayout.h"
55
#include "llvm/IR/Intrinsics.h"
56
#include "llvm/IR/LLVMContext.h"
57
#include "llvm/IR/Module.h"
58
#include "llvm/IR/ProfileSummary.h"
59
#include "llvm/ProfileData/InstrProfReader.h"
60
#include "llvm/Support/CodeGen.h"
61
#include "llvm/Support/CommandLine.h"
62
#include "llvm/Support/ConvertUTF.h"
63
#include "llvm/Support/ErrorHandling.h"
64
#include "llvm/Support/MD5.h"
65
#include "llvm/Support/TimeProfiler.h"
66
67
using namespace clang;
68
using namespace CodeGen;
69
70
static llvm::cl::opt<bool> LimitedCoverage(
71
    "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
72
    llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
73
    llvm::cl::init(false));
74
75
static const char AnnotationSection[] = "llvm.metadata";
76
77
44.9k
static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
78
44.9k
  switch (CGM.getContext().getCXXABIKind()) {
79
94
  case TargetCXXABI::AppleARM64:
80
121
  case TargetCXXABI::Fuchsia:
81
2.39k
  case TargetCXXABI::GenericAArch64:
82
2.86k
  case TargetCXXABI::GenericARM:
83
2.95k
  case TargetCXXABI::iOS:
84
2.97k
  case TargetCXXABI::WatchOS:
85
3.13k
  case TargetCXXABI::GenericMIPS:
86
44.0k
  case TargetCXXABI::GenericItanium:
87
44.1k
  case TargetCXXABI::WebAssembly:
88
44.1k
  case TargetCXXABI::XL:
89
44.1k
    return CreateItaniumCXXABI(CGM);
90
743
  case TargetCXXABI::Microsoft:
91
743
    return CreateMicrosoftCXXABI(CGM);
92
44.9k
  }
93
94
44.9k
  
llvm_unreachable0
("invalid C++ ABI kind");
95
44.9k
}
96
97
CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
98
                             const PreprocessorOptions &PPO,
99
                             const CodeGenOptions &CGO, llvm::Module &M,
100
                             DiagnosticsEngine &diags,
101
                             CoverageSourceInfo *CoverageInfo)
102
    : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
103
      PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
104
      Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
105
      VMContext(M.getContext()), Types(*this), VTables(*this),
106
44.9k
      SanitizerMD(new SanitizerMetadata(*this)) {
107
108
  // Initialize the type cache.
109
44.9k
  llvm::LLVMContext &LLVMContext = M.getContext();
110
44.9k
  VoidTy = llvm::Type::getVoidTy(LLVMContext);
111
44.9k
  Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
112
44.9k
  Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
113
44.9k
  Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
114
44.9k
  Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
115
44.9k
  HalfTy = llvm::Type::getHalfTy(LLVMContext);
116
44.9k
  BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
117
44.9k
  FloatTy = llvm::Type::getFloatTy(LLVMContext);
118
44.9k
  DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
119
44.9k
  PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
120
44.9k
  PointerAlignInBytes =
121
44.9k
    C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
122
44.9k
  SizeSizeInBytes =
123
44.9k
    C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
124
44.9k
  IntAlignInBytes =
125
44.9k
    C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
126
44.9k
  CharTy =
127
44.9k
    llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth());
128
44.9k
  IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
129
44.9k
  IntPtrTy = llvm::IntegerType::get(LLVMContext,
130
44.9k
    C.getTargetInfo().getMaxPointerWidth());
131
44.9k
  Int8PtrTy = Int8Ty->getPointerTo(0);
132
44.9k
  Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
133
44.9k
  AllocaInt8PtrTy = Int8Ty->getPointerTo(
134
44.9k
      M.getDataLayout().getAllocaAddrSpace());
135
44.9k
  ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
136
137
44.9k
  RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
138
139
44.9k
  if (LangOpts.ObjC)
140
25.1k
    createObjCRuntime();
141
44.9k
  if (LangOpts.OpenCL)
142
320
    createOpenCLRuntime();
143
44.9k
  if (LangOpts.OpenMP)
144
5.74k
    createOpenMPRuntime();
145
44.9k
  if (LangOpts.CUDA)
146
221
    createCUDARuntime();
147
148
  // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
149
44.9k
  if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
150
44.9k
      
(44.8k
!CodeGenOpts.RelaxedAliasing44.8k
&&
CodeGenOpts.OptimizationLevel > 044.8k
))
151
3.25k
    TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
152
3.25k
                               getCXXABI().getMangleContext()));
153
154
  // If debug info or coverage generation is enabled, create the CGDebugInfo
155
  // object.
156
44.9k
  if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
157
44.9k
      
CodeGenOpts.EmitGcovArcs34.7k
||
CodeGenOpts.EmitGcovNotes34.7k
)
158
10.2k
    DebugInfo.reset(new CGDebugInfo(*this));
159
160
44.9k
  Block.GlobalUniqueCount = 0;
161
162
44.9k
  if (C.getLangOpts().ObjC)
163
25.1k
    ObjCData.reset(new ObjCEntrypoints());
164
165
44.9k
  if (CodeGenOpts.hasProfileClangUse()) {
166
43
    auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
167
43
        CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
168
43
    if (auto E = ReaderOrErr.takeError()) {
169
1
      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
170
1
                                              "Could not read profile %0: %1");
171
1
      llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
172
1
        getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
173
1
                                  << EI.message();
174
1
      });
175
1
    } else
176
42
      PGOReader = std::move(ReaderOrErr.get());
177
43
  }
178
179
  // If coverage mapping generation is enabled, create the
180
  // CoverageMappingModuleGen object.
181
44.9k
  if (CodeGenOpts.CoverageMapping)
182
80
    CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
183
184
  // Generate the module name hash here if needed.
185
44.9k
  if (CodeGenOpts.UniqueInternalLinkageNames &&
186
44.9k
      
!getModule().getSourceFileName().empty()5
) {
187
5
    std::string Path = getModule().getSourceFileName();
188
    // Check if a path substitution is needed from the MacroPrefixMap.
189
5
    for (const auto &Entry : PPO.MacroPrefixMap)
190
0
      if (Path.rfind(Entry.first, 0) != std::string::npos) {
191
0
        Path = Entry.second + Path.substr(Entry.first.size());
192
0
        break;
193
0
      }
194
5
    llvm::MD5 Md5;
195
5
    Md5.update(Path);
196
5
    llvm::MD5::MD5Result R;
197
5
    Md5.final(R);
198
5
    SmallString<32> Str;
199
5
    llvm::MD5::stringifyResult(R, Str);
200
    // Convert MD5hash to Decimal. Demangler suffixes can either contain
201
    // numbers or characters but not both.
202
5
    llvm::APInt IntHash(128, Str.str(), 16);
203
    // Prepend "__uniq" before the hash for tools like profilers to understand
204
    // that this symbol is of internal linkage type.  The "__uniq" is the
205
    // pre-determined prefix that is used to tell tools that this symbol was
206
    // created with -funique-internal-linakge-symbols and the tools can strip or
207
    // keep the prefix as needed.
208
5
    ModuleNameHash = (Twine(".__uniq.") +
209
5
        Twine(toString(IntHash, /* Radix = */ 10, /* Signed = */false))).str();
210
5
  }
211
44.9k
}
212
213
44.8k
CodeGenModule::~CodeGenModule() {}
214
215
25.1k
void CodeGenModule::createObjCRuntime() {
216
  // This is just isGNUFamily(), but we want to force implementors of
217
  // new ABIs to decide how best to do this.
218
25.1k
  switch (LangOpts.ObjCRuntime.getKind()) {
219
39
  case ObjCRuntime::GNUstep:
220
68
  case ObjCRuntime::GCC:
221
89
  case ObjCRuntime::ObjFW:
222
89
    ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
223
89
    return;
224
225
167
  case ObjCRuntime::FragileMacOSX:
226
25.0k
  case ObjCRuntime::MacOSX:
227
25.0k
  case ObjCRuntime::iOS:
228
25.0k
  case ObjCRuntime::WatchOS:
229
25.0k
    ObjCRuntime.reset(CreateMacObjCRuntime(*this));
230
25.0k
    return;
231
25.1k
  }
232
25.1k
  
llvm_unreachable0
("bad runtime kind");
233
25.1k
}
234
235
320
void CodeGenModule::createOpenCLRuntime() {
236
320
  OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
237
320
}
238
239
5.74k
void CodeGenModule::createOpenMPRuntime() {
240
  // Select a specialized code generation class based on the target, if any.
241
  // If it does not exist use the default implementation.
242
5.74k
  switch (getTriple().getArch()) {
243
82
  case llvm::Triple::nvptx:
244
220
  case llvm::Triple::nvptx64:
245
220
    assert(getLangOpts().OpenMPIsDevice &&
246
220
           "OpenMP NVPTX is only prepared to deal with device code.");
247
0
    OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
248
220
    break;
249
3
  case llvm::Triple::amdgcn:
250
3
    assert(getLangOpts().OpenMPIsDevice &&
251
3
           "OpenMP AMDGCN is only prepared to deal with device code.");
252
0
    OpenMPRuntime.reset(new CGOpenMPRuntimeAMDGCN(*this));
253
3
    break;
254
5.52k
  default:
255
5.52k
    if (LangOpts.OpenMPSimd)
256
2.42k
      OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
257
3.09k
    else
258
3.09k
      OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
259
5.52k
    break;
260
5.74k
  }
261
5.74k
}
262
263
221
void CodeGenModule::createCUDARuntime() {
264
221
  CUDARuntime.reset(CreateNVCUDARuntime(*this));
265
221
}
266
267
139
void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
268
139
  Replacements[Name] = C;
269
139
}
270
271
35.8k
void CodeGenModule::applyReplacements() {
272
35.8k
  for (auto &I : Replacements) {
273
125
    StringRef MangledName = I.first();
274
125
    llvm::Constant *Replacement = I.second;
275
125
    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
276
125
    if (!Entry)
277
0
      continue;
278
125
    auto *OldF = cast<llvm::Function>(Entry);
279
125
    auto *NewF = dyn_cast<llvm::Function>(Replacement);
280
125
    if (!NewF) {
281
22
      if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
282
0
        NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
283
22
      } else {
284
22
        auto *CE = cast<llvm::ConstantExpr>(Replacement);
285
22
        assert(CE->getOpcode() == llvm::Instruction::BitCast ||
286
22
               CE->getOpcode() == llvm::Instruction::GetElementPtr);
287
0
        NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
288
22
      }
289
22
    }
290
291
    // Replace old with new, but keep the old order.
292
0
    OldF->replaceAllUsesWith(Replacement);
293
125
    if (NewF) {
294
123
      NewF->removeFromParent();
295
123
      OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
296
123
                                                       NewF);
297
123
    }
298
125
    OldF->eraseFromParent();
299
125
  }
300
35.8k
}
301
302
102
void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
303
102
  GlobalValReplacements.push_back(std::make_pair(GV, C));
304
102
}
305
306
35.8k
void CodeGenModule::applyGlobalValReplacements() {
307
35.8k
  for (auto &I : GlobalValReplacements) {
308
102
    llvm::GlobalValue *GV = I.first;
309
102
    llvm::Constant *C = I.second;
310
311
102
    GV->replaceAllUsesWith(C);
312
102
    GV->eraseFromParent();
313
102
  }
314
35.8k
}
315
316
// This is only used in aliases that we created and we know they have a
317
// linear structure.
318
static const llvm::GlobalObject *getAliasedGlobal(
319
146
    const llvm::GlobalIndirectSymbol &GIS) {
320
146
  llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
321
146
  const llvm::Constant *C = &GIS;
322
314
  for (;;) {
323
314
    C = C->stripPointerCasts();
324
314
    if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
325
141
      return GO;
326
    // stripPointerCasts will not walk over weak aliases.
327
173
    auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
328
173
    if (!GIS2)
329
0
      return nullptr;
330
173
    if (!Visited.insert(GIS2).second)
331
5
      return nullptr;
332
168
    C = GIS2->getIndirectSymbol();
333
168
  }
334
146
}
335
336
35.8k
void CodeGenModule::checkAliases() {
337
  // Check if the constructed aliases are well formed. It is really unfortunate
338
  // that we have to do this in CodeGen, but we only construct mangled names
339
  // and aliases during codegen.
340
35.8k
  bool Error = false;
341
35.8k
  DiagnosticsEngine &Diags = getDiags();
342
35.8k
  for (const GlobalDecl &GD : Aliases) {
343
146
    const auto *D = cast<ValueDecl>(GD.getDecl());
344
146
    SourceLocation Location;
345
146
    bool IsIFunc = D->hasAttr<IFuncAttr>();
346
146
    if (const Attr *A = D->getDefiningAttr())
347
146
      Location = A->getLocation();
348
0
    else
349
0
      llvm_unreachable("Not an alias or ifunc?");
350
146
    StringRef MangledName = getMangledName(GD);
351
146
    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
352
146
    auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
353
146
    const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
354
146
    if (!GV) {
355
5
      Error = true;
356
5
      Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
357
141
    } else if (GV->isDeclaration()) {
358
6
      Error = true;
359
6
      Diags.Report(Location, diag::err_alias_to_undefined)
360
6
          << IsIFunc << IsIFunc;
361
135
    } else if (IsIFunc) {
362
      // Check resolver function type.
363
10
      llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
364
10
          GV->getType()->getPointerElementType());
365
10
      assert(FTy);
366
10
      if (!FTy->getReturnType()->isPointerTy())
367
1
        Diags.Report(Location, diag::err_ifunc_resolver_return);
368
10
    }
369
370
0
    llvm::Constant *Aliasee = Alias->getIndirectSymbol();
371
146
    llvm::GlobalValue *AliaseeGV;
372
146
    if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
373
53
      AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
374
93
    else
375
93
      AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
376
377
146
    if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
378
6
      StringRef AliasSection = SA->getName();
379
6
      if (AliasSection != AliaseeGV->getSection())
380
5
        Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
381
5
            << AliasSection << IsIFunc << IsIFunc;
382
6
    }
383
384
    // We have to handle alias to weak aliases in here. LLVM itself disallows
385
    // this since the object semantics would not match the IL one. For
386
    // compatibility with gcc we implement it by just pointing the alias
387
    // to its aliasee's aliasee. We also warn, since the user is probably
388
    // expecting the link to be weak.
389
146
    if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
390
21
      if (GA->isInterposable()) {
391
6
        Diags.Report(Location, diag::warn_alias_to_weak_alias)
392
6
            << GV->getName() << GA->getName() << IsIFunc;
393
6
        Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
394
6
            GA->getIndirectSymbol(), Alias->getType());
395
6
        Alias->setIndirectSymbol(Aliasee);
396
6
      }
397
21
    }
398
146
  }
399
35.8k
  if (!Error)
400
35.8k
    return;
401
402
33
  
for (const GlobalDecl &GD : Aliases)2
{
403
33
    StringRef MangledName = getMangledName(GD);
404
33
    llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
405
33
    auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
406
33
    Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
407
33
    Alias->eraseFromParent();
408
33
  }
409
2
}
410
411
9.09k
void CodeGenModule::clear() {
412
9.09k
  DeferredDeclsToEmit.clear();
413
9.09k
  if (OpenMPRuntime)
414
23
    OpenMPRuntime->clear();
415
9.09k
}
416
417
void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
418
7
                                       StringRef MainFile) {
419
7
  if (!hasDiagnostics())
420
0
    return;
421
7
  if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
422
3
    if (MainFile.empty())
423
2
      MainFile = "<stdin>";
424
3
    Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
425
4
  } else {
426
4
    if (Mismatched > 0)
427
4
      Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
428
429
4
    if (Missing > 0)
430
2
      Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
431
4
  }
432
7
}
433
434
static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO,
435
35.8k
                                             llvm::Module &M) {
436
35.8k
  if (!LO.VisibilityFromDLLStorageClass)
437
35.8k
    return;
438
439
5
  llvm::GlobalValue::VisibilityTypes DLLExportVisibility =
440
5
      CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility());
441
5
  llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility =
442
5
      CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility());
443
5
  llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility =
444
5
      CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility());
445
5
  llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility =
446
5
      CodeGenModule::GetLLVMVisibility(
447
5
          LO.getExternDeclNoDLLStorageClassVisibility());
448
449
207
  for (llvm::GlobalValue &GV : M.global_values()) {
450
207
    if (GV.hasAppendingLinkage() || GV.hasLocalLinkage())
451
3
      continue;
452
453
    // Reset DSO locality before setting the visibility. This removes
454
    // any effects that visibility options and annotations may have
455
    // had on the DSO locality. Setting the visibility will implicitly set
456
    // appropriate globals to DSO Local; however, this will be pessimistic
457
    // w.r.t. to the normal compiler IRGen.
458
204
    GV.setDSOLocal(false);
459
460
204
    if (GV.isDeclarationForLinker()) {
461
15
      GV.setVisibility(GV.getDLLStorageClass() ==
462
15
                               llvm::GlobalValue::DLLImportStorageClass
463
15
                           ? 
ExternDeclDLLImportVisibility6
464
15
                           : 
ExternDeclNoDLLStorageClassVisibility9
);
465
189
    } else {
466
189
      GV.setVisibility(GV.getDLLStorageClass() ==
467
189
                               llvm::GlobalValue::DLLExportStorageClass
468
189
                           ? 
DLLExportVisibility9
469
189
                           : 
NoDLLStorageClassVisibility180
);
470
189
    }
471
472
204
    GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
473
204
  }
474
5
}
475
476
35.8k
void CodeGenModule::Release() {
477
35.8k
  EmitDeferred();
478
35.8k
  EmitVTablesOpportunistically();
479
35.8k
  applyGlobalValReplacements();
480
35.8k
  applyReplacements();
481
35.8k
  checkAliases();
482
35.8k
  emitMultiVersionFunctions();
483
35.8k
  EmitCXXGlobalInitFunc();
484
35.8k
  EmitCXXGlobalCleanUpFunc();
485
35.8k
  registerGlobalDtorsWithAtExit();
486
35.8k
  EmitCXXThreadLocalInitFunc();
487
35.8k
  if (ObjCRuntime)
488
16.5k
    if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
489
50
      AddGlobalCtor(ObjCInitFunction);
490
35.8k
  if (Context.getLangOpts().CUDA && 
CUDARuntime204
) {
491
204
    if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule())
492
42
      AddGlobalCtor(CudaCtorFunction);
493
204
  }
494
35.8k
  if (OpenMPRuntime) {
495
5.72k
    if (llvm::Function *OpenMPRequiresDirectiveRegFun =
496
5.72k
            OpenMPRuntime->emitRequiresDirectiveRegFun()) {
497
1.91k
      AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
498
1.91k
    }
499
5.72k
    OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
500
5.72k
    OpenMPRuntime->clear();
501
5.72k
  }
502
35.8k
  if (PGOReader) {
503
42
    getModule().setProfileSummary(
504
42
        PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
505
42
        llvm::ProfileSummary::PSK_Instr);
506
42
    if (PGOStats.hasDiagnostics())
507
7
      PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
508
42
  }
509
35.8k
  EmitCtorList(GlobalCtors, "llvm.global_ctors");
510
35.8k
  EmitCtorList(GlobalDtors, "llvm.global_dtors");
511
35.8k
  EmitGlobalAnnotations();
512
35.8k
  EmitStaticExternCAliases();
513
35.8k
  EmitDeferredUnusedCoverageMappings();
514
35.8k
  CodeGenPGO(*this).setValueProfilingFlag(getModule());
515
35.8k
  if (CoverageMapping)
516
80
    CoverageMapping->emit();
517
35.8k
  if (CodeGenOpts.SanitizeCfiCrossDso) {
518
14
    CodeGenFunction(*this).EmitCfiCheckFail();
519
14
    CodeGenFunction(*this).EmitCfiCheckStub();
520
14
  }
521
35.8k
  emitAtAvailableLinkGuard();
522
35.8k
  if (Context.getTargetInfo().getTriple().isWasm() &&
523
35.8k
      
!Context.getTargetInfo().getTriple().isOSEmscripten()43
) {
524
41
    EmitMainVoidAlias();
525
41
  }
526
35.8k
  emitLLVMUsed();
527
35.8k
  if (SanStats)
528
2
    SanStats->finish();
529
530
35.8k
  if (CodeGenOpts.Autolink &&
531
35.8k
      
(35.8k
Context.getLangOpts().Modules35.8k
||
!LinkerOptionsMetadata.empty()33.8k
)) {
532
2.08k
    EmitModuleLinkOptions();
533
2.08k
  }
534
535
  // On ELF we pass the dependent library specifiers directly to the linker
536
  // without manipulating them. This is in contrast to other platforms where
537
  // they are mapped to a specific linker option by the compiler. This
538
  // difference is a result of the greater variety of ELF linkers and the fact
539
  // that ELF linkers tend to handle libraries in a more complicated fashion
540
  // than on other platforms. This forces us to defer handling the dependent
541
  // libs to the linker.
542
  //
543
  // CUDA/HIP device and host libraries are different. Currently there is no
544
  // way to differentiate dependent libraries for host or device. Existing
545
  // usage of #pragma comment(lib, *) is intended for host libraries on
546
  // Windows. Therefore emit llvm.dependent-libraries only for host.
547
35.8k
  if (!ELFDependentLibraries.empty() && 
!Context.getLangOpts().CUDAIsDevice8
) {
548
5
    auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
549
5
    for (auto *MD : ELFDependentLibraries)
550
14
      NMD->addOperand(MD);
551
5
  }
552
553
  // Record mregparm value now so it is visible through rest of codegen.
554
35.8k
  if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
555
3.03k
    getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
556
3.03k
                              CodeGenOpts.NumRegisterParameters);
557
558
35.8k
  if (CodeGenOpts.DwarfVersion) {
559
3.40k
    getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
560
3.40k
                              CodeGenOpts.DwarfVersion);
561
3.40k
  }
562
563
35.8k
  if (CodeGenOpts.Dwarf64)
564
1
    getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1);
565
566
35.8k
  if (Context.getLangOpts().SemanticInterposition)
567
    // Require various optimization to respect semantic interposition.
568
1
    getModule().setSemanticInterposition(1);
569
570
35.8k
  if (CodeGenOpts.EmitCodeView) {
571
    // Indicate that we want CodeView in the metadata.
572
39
    getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
573
39
  }
574
35.8k
  if (CodeGenOpts.CodeViewGHash) {
575
1
    getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
576
1
  }
577
35.8k
  if (CodeGenOpts.ControlFlowGuard) {
578
    // Function ID tables and checks for Control Flow Guard (cfguard=2).
579
1
    getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
580
35.8k
  } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
581
    // Function ID tables for Control Flow Guard (cfguard=1).
582
1
    getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
583
1
  }
584
35.8k
  if (CodeGenOpts.EHContGuard) {
585
    // Function ID tables for EH Continuation Guard.
586
1
    getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1);
587
1
  }
588
35.8k
  if (CodeGenOpts.OptimizationLevel > 0 && 
CodeGenOpts.StrictVTablePointers3.20k
) {
589
    // We don't support LTO with 2 with different StrictVTablePointers
590
    // FIXME: we could support it by stripping all the information introduced
591
    // by StrictVTablePointers.
592
593
6
    getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
594
595
6
    llvm::Metadata *Ops[2] = {
596
6
              llvm::MDString::get(VMContext, "StrictVTablePointers"),
597
6
              llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
598
6
                  llvm::Type::getInt32Ty(VMContext), 1))};
599
600
6
    getModule().addModuleFlag(llvm::Module::Require,
601
6
                              "StrictVTablePointersRequirement",
602
6
                              llvm::MDNode::get(VMContext, Ops));
603
6
  }
604
35.8k
  if (getModuleDebugInfo())
605
    // We support a single version in the linked module. The LLVM
606
    // parser will drop debug info with a different version number
607
    // (and warn about it, too).
608
10.1k
    getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
609
10.1k
                              llvm::DEBUG_METADATA_VERSION);
610
611
  // We need to record the widths of enums and wchar_t, so that we can generate
612
  // the correct build attributes in the ARM backend. wchar_size is also used by
613
  // TargetLibraryInfo.
614
35.8k
  uint64_t WCharWidth =
615
35.8k
      Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
616
35.8k
  getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
617
618
35.8k
  llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
619
35.8k
  if (   Arch == llvm::Triple::arm
620
35.8k
      || 
Arch == llvm::Triple::armeb35.5k
621
35.8k
      || 
Arch == llvm::Triple::thumb35.5k
622
35.8k
      || 
Arch == llvm::Triple::thumbeb35.2k
) {
623
    // The minimum width of an enum in bytes
624
616
    uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 
11
:
4615
;
625
616
    getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
626
616
  }
627
628
35.8k
  if (Arch == llvm::Triple::riscv32 || 
Arch == llvm::Triple::riscv6435.8k
) {
629
380
    StringRef ABIStr = Target.getABI();
630
380
    llvm::LLVMContext &Ctx = TheModule.getContext();
631
380
    getModule().addModuleFlag(llvm::Module::Error, "target-abi",
632
380
                              llvm::MDString::get(Ctx, ABIStr));
633
380
  }
634
635
35.8k
  if (CodeGenOpts.SanitizeCfiCrossDso) {
636
    // Indicate that we want cross-DSO control flow integrity checks.
637
14
    getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
638
14
  }
639
640
35.8k
  if (CodeGenOpts.WholeProgramVTables) {
641
    // Indicate whether VFE was enabled for this module, so that the
642
    // vcall_visibility metadata added under whole program vtables is handled
643
    // appropriately in the optimizer.
644
20
    getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
645
20
                              CodeGenOpts.VirtualFunctionElimination);
646
20
  }
647
648
35.8k
  if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
649
21
    getModule().addModuleFlag(llvm::Module::Override,
650
21
                              "CFI Canonical Jump Tables",
651
21
                              CodeGenOpts.SanitizeCfiCanonicalJumpTables);
652
21
  }
653
654
35.8k
  if (CodeGenOpts.CFProtectionReturn &&
655
35.8k
      
Target.checkCFProtectionReturnSupported(getDiags())0
) {
656
    // Indicate that we want to instrument return control flow protection.
657
0
    getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
658
0
                              1);
659
0
  }
660
661
35.8k
  if (CodeGenOpts.CFProtectionBranch &&
662
35.8k
      
Target.checkCFProtectionBranchSupported(getDiags())4
) {
663
    // Indicate that we want to instrument branch control flow protection.
664
4
    getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
665
4
                              1);
666
4
  }
667
668
35.8k
  if (Arch == llvm::Triple::aarch64 || 
Arch == llvm::Triple::aarch64_3233.4k
||
669
35.8k
      
Arch == llvm::Triple::aarch64_be33.4k
) {
670
2.41k
    getModule().addModuleFlag(llvm::Module::Error,
671
2.41k
                              "branch-target-enforcement",
672
2.41k
                              LangOpts.BranchTargetEnforcement);
673
674
2.41k
    getModule().addModuleFlag(llvm::Module::Error, "sign-return-address",
675
2.41k
                              LangOpts.hasSignReturnAddress());
676
677
2.41k
    getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all",
678
2.41k
                              LangOpts.isSignReturnAddressScopeAll());
679
680
2.41k
    getModule().addModuleFlag(llvm::Module::Error,
681
2.41k
                              "sign-return-address-with-bkey",
682
2.41k
                              !LangOpts.isSignReturnAddressWithAKey());
683
2.41k
  }
684
685
35.8k
  if (!CodeGenOpts.MemoryProfileOutput.empty()) {
686
4
    llvm::LLVMContext &Ctx = TheModule.getContext();
687
4
    getModule().addModuleFlag(
688
4
        llvm::Module::Error, "MemProfProfileFilename",
689
4
        llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput));
690
4
  }
691
692
35.8k
  if (LangOpts.CUDAIsDevice && 
getTriple().isNVPTX()138
) {
693
    // Indicate whether __nvvm_reflect should be configured to flush denormal
694
    // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
695
    // property.)
696
65
    getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
697
65
                              CodeGenOpts.FP32DenormalMode.Output !=
698
65
                                  llvm::DenormalMode::IEEE);
699
65
  }
700
701
35.8k
  if (LangOpts.EHAsynch)
702
4
    getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1);
703
704
  // Emit OpenCL specific module metadata: OpenCL/SPIR version.
705
35.8k
  if (LangOpts.OpenCL) {
706
300
    EmitOpenCLMetadata();
707
    // Emit SPIR version.
708
300
    if (getTriple().isSPIR()) {
709
      // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
710
      // opencl.spir.version named metadata.
711
      // C++ is backwards compatible with OpenCL v2.0.
712
98
      auto Version = LangOpts.OpenCLCPlusPlus ? 
20028
:
LangOpts.OpenCLVersion70
;
713
98
      llvm::Metadata *SPIRVerElts[] = {
714
98
          llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
715
98
              Int32Ty, Version / 100)),
716
98
          llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
717
98
              Int32Ty, (Version / 100 > 1) ? 
061
:
237
))};
718
98
      llvm::NamedMDNode *SPIRVerMD =
719
98
          TheModule.getOrInsertNamedMetadata("opencl.spir.version");
720
98
      llvm::LLVMContext &Ctx = TheModule.getContext();
721
98
      SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
722
98
    }
723
300
  }
724
725
35.8k
  if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
726
3.88k
    assert(PLevel < 3 && "Invalid PIC Level");
727
0
    getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
728
3.88k
    if (Context.getLangOpts().PIE)
729
51
      getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
730
3.88k
  }
731
732
35.8k
  if (getCodeGenOpts().CodeModel.size() > 0) {
733
19.7k
    unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
734
19.7k
                  .Case("tiny", llvm::CodeModel::Tiny)
735
19.7k
                  .Case("small", llvm::CodeModel::Small)
736
19.7k
                  .Case("kernel", llvm::CodeModel::Kernel)
737
19.7k
                  .Case("medium", llvm::CodeModel::Medium)
738
19.7k
                  .Case("large", llvm::CodeModel::Large)
739
19.7k
                  .Default(~0u);
740
19.7k
    if (CM != ~0u) {
741
11
      llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
742
11
      getModule().setCodeModel(codeModel);
743
11
    }
744
19.7k
  }
745
746
35.8k
  if (CodeGenOpts.NoPLT)
747
5
    getModule().setRtLibUseGOT();
748
35.8k
  if (CodeGenOpts.UnwindTables)
749
3.93k
    getModule().setUwtable();
750
751
35.8k
  switch (CodeGenOpts.getFramePointer()) {
752
15.7k
  case CodeGenOptions::FramePointerKind::None:
753
    // 0 ("none") is the default.
754
15.7k
    break;
755
111
  case CodeGenOptions::FramePointerKind::NonLeaf:
756
111
    getModule().setFramePointer(llvm::FramePointerKind::NonLeaf);
757
111
    break;
758
19.9k
  case CodeGenOptions::FramePointerKind::All:
759
19.9k
    getModule().setFramePointer(llvm::FramePointerKind::All);
760
19.9k
    break;
761
35.8k
  }
762
763
35.8k
  SimplifyPersonality();
764
765
35.8k
  if (getCodeGenOpts().EmitDeclMetadata)
766
16.1k
    EmitDeclMetadata();
767
768
35.8k
  if (getCodeGenOpts().EmitGcovArcs || 
getCodeGenOpts().EmitGcovNotes35.8k
)
769
15
    EmitCoverageFile();
770
771
35.8k
  if (CGDebugInfo *DI = getModuleDebugInfo())
772
10.1k
    DI->finalize();
773
774
35.8k
  if (getCodeGenOpts().EmitVersionIdentMetadata)
775
35.8k
    EmitVersionIdentMetadata();
776
777
35.8k
  if (!getCodeGenOpts().RecordCommandLine.empty())
778
0
    EmitCommandLineMetadata();
779
780
35.8k
  if (!getCodeGenOpts().StackProtectorGuard.empty())
781
1
    getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard);
782
35.8k
  if (!getCodeGenOpts().StackProtectorGuardReg.empty())
783
1
    getModule().setStackProtectorGuardReg(
784
1
        getCodeGenOpts().StackProtectorGuardReg);
785
35.8k
  if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX)
786
1
    getModule().setStackProtectorGuardOffset(
787
1
        getCodeGenOpts().StackProtectorGuardOffset);
788
35.8k
  if (getCodeGenOpts().StackAlignment)
789
1
    getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment);
790
35.8k
  if (getCodeGenOpts().WarnStackSize != UINT_MAX)
791
6
    getModule().setWarnStackSize(getCodeGenOpts().WarnStackSize);
792
793
35.8k
  getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
794
795
35.8k
  EmitBackendOptionsMetadata(getCodeGenOpts());
796
797
  // Set visibility from DLL storage class
798
  // We do this at the end of LLVM IR generation; after any operation
799
  // that might affect the DLL storage class or the visibility, and
800
  // before anything that might act on these.
801
35.8k
  setVisibilityFromDLLStorageClass(LangOpts, getModule());
802
35.8k
}
803
804
300
void CodeGenModule::EmitOpenCLMetadata() {
805
  // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
806
  // opencl.ocl.version named metadata node.
807
  // C++ is backwards compatible with OpenCL v2.0.
808
  // FIXME: We might need to add CXX version at some point too?
809
300
  auto Version = LangOpts.OpenCLCPlusPlus ? 
20036
:
LangOpts.OpenCLVersion264
;
810
300
  llvm::Metadata *OCLVerElts[] = {
811
300
      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
812
300
          Int32Ty, Version / 100)),
813
300
      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
814
300
          Int32Ty, (Version % 100) / 10))};
815
300
  llvm::NamedMDNode *OCLVerMD =
816
300
      TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
817
300
  llvm::LLVMContext &Ctx = TheModule.getContext();
818
300
  OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
819
300
}
820
821
void CodeGenModule::EmitBackendOptionsMetadata(
822
35.8k
    const CodeGenOptions CodeGenOpts) {
823
35.8k
  switch (getTriple().getArch()) {
824
35.4k
  default:
825
35.4k
    break;
826
35.4k
  case llvm::Triple::riscv32:
827
380
  case llvm::Triple::riscv64:
828
380
    getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
829
380
                              CodeGenOpts.SmallDataLimit);
830
380
    break;
831
35.8k
  }
832
35.8k
}
833
834
2.10M
void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
835
  // Make sure that this type is translated.
836
2.10M
  Types.UpdateCompletedType(TD);
837
2.10M
}
838
839
476
void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
840
  // Make sure that this type is translated.
841
476
  Types.RefreshTypeCacheForClass(RD);
842
476
}
843
844
205k
llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
845
205k
  if (!TBAA)
846
203k
    return nullptr;
847
2.38k
  return TBAA->getTypeInfo(QTy);
848
205k
}
849
850
3.09M
TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
851
3.09M
  if (!TBAA)
852
2.85M
    return TBAAAccessInfo();
853
237k
  if (getLangOpts().CUDAIsDevice) {
854
    // As CUDA builtin surface/texture types are replaced, skip generating TBAA
855
    // access info.
856
370
    if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
857
0
      if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
858
0
          nullptr)
859
0
        return TBAAAccessInfo();
860
370
    } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
861
0
      if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
862
0
          nullptr)
863
0
        return TBAAAccessInfo();
864
0
    }
865
370
  }
866
237k
  return TBAA->getAccessInfo(AccessType);
867
237k
}
868
869
TBAAAccessInfo
870
5.01k
CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
871
5.01k
  if (!TBAA)
872
4.38k
    return TBAAAccessInfo();
873
623
  return TBAA->getVTablePtrAccessInfo(VTablePtrType);
874
5.01k
}
875
876
10.6k
llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
877
10.6k
  if (!TBAA)
878
10.2k
    return nullptr;
879
426
  return TBAA->getTBAAStructInfo(QTy);
880
10.6k
}
881
882
205k
llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
883
205k
  if (!TBAA)
884
203k
    return nullptr;
885
2.25k
  return TBAA->getBaseTypeInfo(QTy);
886
205k
}
887
888
2.53M
llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
889
2.53M
  if (!TBAA)
890
2.30M
    return nullptr;
891
226k
  return TBAA->getAccessTagInfo(Info);
892
2.53M
}
893
894
TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
895
2.38k
                                                   TBAAAccessInfo TargetInfo) {
896
2.38k
  if (!TBAA)
897
2.08k
    return TBAAAccessInfo();
898
308
  return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
899
2.38k
}
900
901
TBAAAccessInfo
902
CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
903
511
                                                   TBAAAccessInfo InfoB) {
904
511
  if (!TBAA)
905
502
    return TBAAAccessInfo();
906
9
  return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
907
511
}
908
909
TBAAAccessInfo
910
CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
911
7
                                              TBAAAccessInfo SrcInfo) {
912
7
  if (!TBAA)
913
0
    return TBAAAccessInfo();
914
7
  return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
915
7
}
916
917
void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
918
2.53M
                                                TBAAAccessInfo TBAAInfo) {
919
2.53M
  if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
920
226k
    Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
921
2.53M
}
922
923
void CodeGenModule::DecorateInstructionWithInvariantGroup(
924
172
    llvm::Instruction *I, const CXXRecordDecl *RD) {
925
172
  I->setMetadata(llvm::LLVMContext::MD_invariant_group,
926
172
                 llvm::MDNode::get(getLLVMContext(), {}));
927
172
}
928
929
19
void CodeGenModule::Error(SourceLocation loc, StringRef message) {
930
19
  unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
931
19
  getDiags().Report(Context.getFullLoc(loc), diagID) << message;
932
19
}
933
934
/// ErrorUnsupported - Print out an error that codegen doesn't support the
935
/// specified stmt yet.
936
3
void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
937
3
  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
938
3
                                               "cannot compile this %0 yet");
939
3
  std::string Msg = Type;
940
3
  getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
941
3
      << Msg << S->getSourceRange();
942
3
}
943
944
/// ErrorUnsupported - Print out an error that codegen doesn't support the
945
/// specified decl yet.
946
6
void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
947
6
  unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
948
6
                                               "cannot compile this %0 yet");
949
6
  std::string Msg = Type;
950
6
  getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
951
6
}
952
953
41.6k
llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
954
41.6k
  return llvm::ConstantInt::get(SizeTy, size.getQuantity());
955
41.6k
}
956
957
void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
958
986k
                                        const NamedDecl *D) const {
959
986k
  if (GV->hasDLLImportStorageClass())
960
1.93k
    return;
961
  // Internal definitions always have default visibility.
962
984k
  if (GV->hasLocalLinkage()) {
963
86.0k
    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
964
86.0k
    return;
965
86.0k
  }
966
898k
  if (!D)
967
105
    return;
968
  // Set visibility for definitions, and for declarations if requested globally
969
  // or set explicitly.
970
898k
  LinkageInfo LV = D->getLinkageAndVisibility();
971
898k
  if (LV.isVisibilityExplicit() || 
getLangOpts().SetVisibilityForExternDecls680k
||
972
898k
      
!GV->isDeclarationForLinker()680k
)
973
437k
    GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
974
898k
}
975
976
static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
977
1.50M
                                 llvm::GlobalValue *GV) {
978
1.50M
  if (GV->hasLocalLinkage())
979
150k
    return true;
980
981
1.35M
  if (!GV->hasDefaultVisibility() && 
!GV->hasExternalWeakLinkage()284k
)
982
284k
    return true;
983
984
  // DLLImport explicitly marks the GV as external.
985
1.07M
  if (GV->hasDLLImportStorageClass())
986
2.19k
    return false;
987
988
1.07M
  const llvm::Triple &TT = CGM.getTriple();
989
1.07M
  if (TT.isWindowsGNUEnvironment()) {
990
    // In MinGW, variables without DLLImport can still be automatically
991
    // imported from a DLL by the linker; don't mark variables that
992
    // potentially could come from another DLL as DSO local.
993
994
    // With EmulatedTLS, TLS variables can be autoimported from other DLLs
995
    // (and this actually happens in the public interface of libstdc++), so
996
    // such variables can't be marked as DSO local. (Native TLS variables
997
    // can't be dllimported at all, though.)
998
9.68k
    if (GV->isDeclarationForLinker() && 
isa<llvm::GlobalVariable>(GV)6.51k
&&
999
9.68k
        
(401
!GV->isThreadLocal()401
||
CGM.getCodeGenOpts().EmulatedTLS13
))
1000
390
      return false;
1001
9.68k
  }
1002
1003
  // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
1004
  // remain unresolved in the link, they can be resolved to zero, which is
1005
  // outside the current DSO.
1006
1.07M
  if (TT.isOSBinFormatCOFF() && 
GV->hasExternalWeakLinkage()58.6k
)
1007
4
    return false;
1008
1009
  // Every other GV is local on COFF.
1010
  // Make an exception for windows OS in the triple: Some firmware builds use
1011
  // *-win32-macho triples. This (accidentally?) produced windows relocations
1012
  // without GOT tables in older clang versions; Keep this behaviour.
1013
  // FIXME: even thread local variables?
1014
1.07M
  if (TT.isOSBinFormatCOFF() || 
(1.01M
TT.isOSWindows()1.01M
&&
TT.isOSBinFormatMachO()107
))
1015
58.6k
    return true;
1016
1017
  // Only handle COFF and ELF for now.
1018
1.01M
  if (!TT.isOSBinFormatELF())
1019
503k
    return false;
1020
1021
  // If this is not an executable, don't assume anything is local.
1022
508k
  const auto &CGOpts = CGM.getCodeGenOpts();
1023
508k
  llvm::Reloc::Model RM = CGOpts.RelocationModel;
1024
508k
  const auto &LOpts = CGM.getLangOpts();
1025
508k
  if (RM != llvm::Reloc::Static && 
!LOpts.PIE496k
) {
1026
    // On ELF, if -fno-semantic-interposition is specified and the target
1027
    // supports local aliases, there will be neither CC1
1028
    // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set
1029
    // dso_local on the function if using a local alias is preferable (can avoid
1030
    // PLT indirection).
1031
496k
    if (!(isa<llvm::Function>(GV) && 
GV->canBenefitFromLocalAlias()467k
))
1032
396k
      return false;
1033
99.7k
    return !(CGM.getLangOpts().SemanticInterposition ||
1034
99.7k
             
CGM.getLangOpts().HalfNoSemanticInterposition99.7k
);
1035
496k
  }
1036
1037
  // A definition cannot be preempted from an executable.
1038
11.9k
  if (!GV->isDeclarationForLinker())
1039
1.65k
    return true;
1040
1041
  // Most PIC code sequences that assume that a symbol is local cannot produce a
1042
  // 0 if it turns out the symbol is undefined. While this is ABI and relocation
1043
  // depended, it seems worth it to handle it here.
1044
10.2k
  if (RM == llvm::Reloc::PIC_ && 
GV->hasExternalWeakLinkage()155
)
1045
4
    return false;
1046
1047
  // PowerPC64 prefers TOC indirection to avoid copy relocations.
1048
10.2k
  if (TT.isPPC64())
1049
8.05k
    return false;
1050
1051
2.20k
  if (CGOpts.DirectAccessExternalData) {
1052
    // If -fdirect-access-external-data (default for -fno-pic), set dso_local
1053
    // for non-thread-local variables. If the symbol is not defined in the
1054
    // executable, a copy relocation will be needed at link time. dso_local is
1055
    // excluded for thread-local variables because they generally don't support
1056
    // copy relocations.
1057
2.07k
    if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
1058
400
      if (!Var->isThreadLocal())
1059
390
        return true;
1060
1061
    // -fno-pic sets dso_local on a function declaration to allow direct
1062
    // accesses when taking its address (similar to a data symbol). If the
1063
    // function is not defined in the executable, a canonical PLT entry will be
1064
    // needed at link time. -fno-direct-access-external-data can avoid the
1065
    // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as
1066
    // it could just cause trouble without providing perceptible benefits.
1067
1.68k
    if (isa<llvm::Function>(GV) && 
!CGOpts.NoPLT1.67k
&&
RM == llvm::Reloc::Static1.62k
)
1068
1.61k
      return true;
1069
1.68k
  }
1070
1071
  // If we can use copy relocations we can assume it is local.
1072
1073
  // Otherwise don't assume it is local.
1074
200
  return false;
1075
2.20k
}
1076
1077
1.50M
void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1078
1.50M
  GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1079
1.50M
}
1080
1081
void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1082
587k
                                          GlobalDecl GD) const {
1083
587k
  const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1084
  // C++ destructors have a few C++ ABI specific special cases.
1085
587k
  if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1086
17.2k
    getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1087
17.2k
    return;
1088
17.2k
  }
1089
570k
  setDLLImportDLLExport(GV, D);
1090
570k
}
1091
1092
void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1093
986k
                                          const NamedDecl *D) const {
1094
986k
  if (D && 
D->isExternallyVisible()986k
) {
1095
857k
    if (D->hasAttr<DLLImportAttr>())
1096
1.93k
      GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1097
855k
    else if (D->hasAttr<DLLExportAttr>() && 
!GV->isDeclarationForLinker()6.82k
)
1098
2.69k
      GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1099
857k
  }
1100
986k
}
1101
1102
void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1103
587k
                                    GlobalDecl GD) const {
1104
587k
  setDLLImportDLLExport(GV, GD);
1105
587k
  setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1106
587k
}
1107
1108
void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1109
399k
                                    const NamedDecl *D) const {
1110
399k
  setDLLImportDLLExport(GV, D);
1111
399k
  setGVPropertiesAux(GV, D);
1112
399k
}
1113
1114
void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1115
986k
                                       const NamedDecl *D) const {
1116
986k
  setGlobalVisibility(GV, D);
1117
986k
  setDSOLocal(GV);
1118
986k
  GV->setPartition(CodeGenOpts.SymbolPartition);
1119
986k
}
1120
1121
21
static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1122
21
  return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1123
21
      .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1124
21
      .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1125
21
      .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1126
21
      .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1127
21
}
1128
1129
llvm::GlobalVariable::ThreadLocalMode
1130
592
CodeGenModule::GetDefaultLLVMTLSModel() const {
1131
592
  switch (CodeGenOpts.getDefaultTLSModel()) {
1132
570
  case CodeGenOptions::GeneralDynamicTLSModel:
1133
570
    return llvm::GlobalVariable::GeneralDynamicTLSModel;
1134
10
  case CodeGenOptions::LocalDynamicTLSModel:
1135
10
    return llvm::GlobalVariable::LocalDynamicTLSModel;
1136
6
  case CodeGenOptions::InitialExecTLSModel:
1137
6
    return llvm::GlobalVariable::InitialExecTLSModel;
1138
6
  case CodeGenOptions::LocalExecTLSModel:
1139
6
    return llvm::GlobalVariable::LocalExecTLSModel;
1140
592
  }
1141
592
  
llvm_unreachable0
("Invalid TLS model!");
1142
592
}
1143
1144
543
void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1145
543
  assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
1146
1147
0
  llvm::GlobalValue::ThreadLocalMode TLM;
1148
543
  TLM = GetDefaultLLVMTLSModel();
1149
1150
  // Override the TLS model if it is explicitly specified.
1151
543
  if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1152
21
    TLM = GetLLVMTLSModel(Attr->getModel());
1153
21
  }
1154
1155
543
  GV->setThreadLocalMode(TLM);
1156
543
}
1157
1158
static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1159
112
                                          StringRef Name) {
1160
112
  const TargetInfo &Target = CGM.getTarget();
1161
112
  return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1162
112
}
1163
1164
static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1165
                                                 const CPUSpecificAttr *Attr,
1166
                                                 unsigned CPUIndex,
1167
64
                                                 raw_ostream &Out) {
1168
  // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1169
  // supported.
1170
64
  if (Attr)
1171
38
    Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1172
26
  else if (CGM.getTarget().supportsIFunc())
1173
13
    Out << ".resolver";
1174
64
}
1175
1176
static void AppendTargetMangling(const CodeGenModule &CGM,
1177
381
                                 const TargetAttr *Attr, raw_ostream &Out) {
1178
381
  if (Attr->isDefaultVersion())
1179
242
    return;
1180
1181
139
  Out << '.';
1182
139
  const TargetInfo &Target = CGM.getTarget();
1183
139
  ParsedTargetAttr Info =
1184
139
      Attr->parse([&Target](StringRef LHS, StringRef RHS) {
1185
        // Multiversioning doesn't allow "no-${feature}", so we can
1186
        // only have "+" prefixes here.
1187
10
        assert(LHS.startswith("+") && RHS.startswith("+") &&
1188
10
               "Features should always have a prefix.");
1189
0
        return Target.multiVersionSortPriority(LHS.substr(1)) >
1190
10
               Target.multiVersionSortPriority(RHS.substr(1));
1191
10
      });
1192
1193
139
  bool IsFirst = true;
1194
1195
139
  if (!Info.Architecture.empty()) {
1196
88
    IsFirst = false;
1197
88
    Out << "arch_" << Info.Architecture;
1198
88
  }
1199
1200
139
  for (StringRef Feat : Info.Features) {
1201
63
    if (!IsFirst)
1202
12
      Out << '_';
1203
63
    IsFirst = false;
1204
63
    Out << Feat.substr(1);
1205
63
  }
1206
139
}
1207
1208
// Returns true if GD is a function decl with internal linkage and
1209
// needs a unique suffix after the mangled name.
1210
static bool isUniqueInternalLinkageDecl(GlobalDecl GD,
1211
1.36M
                                        CodeGenModule &CGM) {
1212
1.36M
  const Decl *D = GD.getDecl();
1213
1.36M
  return !CGM.getModuleNameHash().empty() && 
isa<FunctionDecl>(D)36
&&
1214
1.36M
         
(CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage)27
;
1215
1.36M
}
1216
1217
static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD,
1218
                                      const NamedDecl *ND,
1219
2.88M
                                      bool OmitMultiVersionMangling = false) {
1220
2.88M
  SmallString<256> Buffer;
1221
2.88M
  llvm::raw_svector_ostream Out(Buffer);
1222
2.88M
  MangleContext &MC = CGM.getCXXABI().getMangleContext();
1223
2.88M
  if (!CGM.getModuleNameHash().empty())
1224
42
    MC.needsUniqueInternalLinkageNames();
1225
2.88M
  bool ShouldMangle = MC.shouldMangleDeclName(ND);
1226
2.88M
  if (ShouldMangle)
1227
1.36M
    MC.mangleName(GD.getWithDecl(ND), Out);
1228
1.52M
  else {
1229
1.52M
    IdentifierInfo *II = ND->getIdentifier();
1230
1.52M
    assert(II && "Attempt to mangle unnamed decl.");
1231
0
    const auto *FD = dyn_cast<FunctionDecl>(ND);
1232
1233
1.52M
    if (FD &&
1234
1.52M
        
FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall1.49M
) {
1235
61
      Out << "__regcall3__" << II->getName();
1236
1.52M
    } else if (FD && 
FD->hasAttr<CUDAGlobalAttr>()1.49M
&&
1237
1.52M
               
GD.getKernelReferenceKind() == KernelReferenceKind::Stub25
) {
1238
4
      Out << "__device_stub__" << II->getName();
1239
1.52M
    } else {
1240
1.52M
      Out << II->getName();
1241
1.52M
    }
1242
1.52M
  }
1243
1244
  // Check if the module name hash should be appended for internal linkage
1245
  // symbols.   This should come before multi-version target suffixes are
1246
  // appended. This is to keep the name and module hash suffix of the
1247
  // internal linkage function together.  The unique suffix should only be
1248
  // added when name mangling is done to make sure that the final name can
1249
  // be properly demangled.  For example, for C functions without prototypes,
1250
  // name mangling is not done and the unique suffix should not be appeneded
1251
  // then.
1252
2.88M
  if (ShouldMangle && 
isUniqueInternalLinkageDecl(GD, CGM)1.36M
) {
1253
21
    assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames &&
1254
21
           "Hash computed when not explicitly requested");
1255
0
    Out << CGM.getModuleNameHash();
1256
21
  }
1257
1258
2.88M
  if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1259
2.81M
    if (FD->isMultiVersion() && 
!OmitMultiVersionMangling872
) {
1260
445
      switch (FD->getMultiVersionKind()) {
1261
26
      case MultiVersionKind::CPUDispatch:
1262
64
      case MultiVersionKind::CPUSpecific:
1263
64
        AppendCPUSpecificCPUDispatchMangling(CGM,
1264
64
                                             FD->getAttr<CPUSpecificAttr>(),
1265
64
                                             GD.getMultiVersionIndex(), Out);
1266
64
        break;
1267
381
      case MultiVersionKind::Target:
1268
381
        AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1269
381
        break;
1270
0
      case MultiVersionKind::None:
1271
0
        llvm_unreachable("None multiversion type isn't valid here");
1272
445
      }
1273
445
    }
1274
1275
  // Make unique name for device side static file-scope variable for HIP.
1276
2.88M
  if (CGM.getContext().shouldExternalizeStaticVar(ND) &&
1277
2.88M
      
CGM.getLangOpts().GPURelocatableDeviceCode272
&&
1278
2.88M
      
CGM.getLangOpts().CUDAIsDevice54
&&
!CGM.getLangOpts().CUID.empty()52
)
1279
32
    CGM.printPostfixForExternalizedStaticVar(Out);
1280
2.88M
  return std::string(Out.str());
1281
2.88M
}
1282
1283
void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1284
239
                                            const FunctionDecl *FD) {
1285
239
  if (!FD->isMultiVersion())
1286
0
    return;
1287
1288
  // Get the name of what this would be without the 'target' attribute.  This
1289
  // allows us to lookup the version that was emitted when this wasn't a
1290
  // multiversion function.
1291
239
  std::string NonTargetName =
1292
239
      getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1293
239
  GlobalDecl OtherGD;
1294
239
  if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1295
205
    assert(OtherGD.getCanonicalDecl()
1296
205
               .getDecl()
1297
205
               ->getAsFunction()
1298
205
               ->isMultiVersion() &&
1299
205
           "Other GD should now be a multiversioned function");
1300
    // OtherFD is the version of this function that was mangled BEFORE
1301
    // becoming a MultiVersion function.  It potentially needs to be updated.
1302
0
    const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1303
205
                                      .getDecl()
1304
205
                                      ->getAsFunction()
1305
205
                                      ->getMostRecentDecl();
1306
205
    std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1307
    // This is so that if the initial version was already the 'default'
1308
    // version, we don't try to update it.
1309
205
    if (OtherName != NonTargetName) {
1310
      // Remove instead of erase, since others may have stored the StringRef
1311
      // to this.
1312
20
      const auto ExistingRecord = Manglings.find(NonTargetName);
1313
20
      if (ExistingRecord != std::end(Manglings))
1314
20
        Manglings.remove(&(*ExistingRecord));
1315
20
      auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1316
20
      MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1317
20
      if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1318
18
        Entry->setName(OtherName);
1319
20
    }
1320
205
  }
1321
239
}
1322
1323
4.28M
StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1324
4.28M
  GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1325
1326
  // Some ABIs don't have constructor variants.  Make sure that base and
1327
  // complete constructors get mangled the same.
1328
4.28M
  if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1329
276k
    if (!getTarget().getCXXABI().hasConstructorVariants()) {
1330
4.55k
      CXXCtorType OrigCtorType = GD.getCtorType();
1331
4.55k
      assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1332
4.55k
      if (OrigCtorType == Ctor_Base)
1333
1.14k
        CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1334
4.55k
    }
1335
276k
  }
1336
1337
  // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a
1338
  // static device variable depends on whether the variable is referenced by
1339
  // a host or device host function. Therefore the mangled name cannot be
1340
  // cached.
1341
4.28M
  if (!LangOpts.CUDAIsDevice ||
1342
4.28M
      
!getContext().mayExternalizeStaticVar(GD.getDecl())3.51k
) {
1343
4.28M
    auto FoundName = MangledDeclNames.find(CanonicalGD);
1344
4.28M
    if (FoundName != MangledDeclNames.end())
1345
1.39M
      return FoundName->second;
1346
4.28M
  }
1347
1348
  // Keep the first result in the case of a mangling collision.
1349
2.88M
  const auto *ND = cast<NamedDecl>(GD.getDecl());
1350
2.88M
  std::string MangledName = getMangledNameImpl(*this, GD, ND);
1351
1352
  // Ensure either we have different ABIs between host and device compilations,
1353
  // says host compilation following MSVC ABI but device compilation follows
1354
  // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1355
  // mangling should be the same after name stubbing. The later checking is
1356
  // very important as the device kernel name being mangled in host-compilation
1357
  // is used to resolve the device binaries to be executed. Inconsistent naming
1358
  // result in undefined behavior. Even though we cannot check that naming
1359
  // directly between host- and device-compilations, the host- and
1360
  // device-mangling in host compilation could help catching certain ones.
1361
2.88M
  assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1362
2.88M
         getLangOpts().CUDAIsDevice ||
1363
2.88M
         (getContext().getAuxTargetInfo() &&
1364
2.88M
          (getContext().getAuxTargetInfo()->getCXXABI() !=
1365
2.88M
           getContext().getTargetInfo().getCXXABI())) ||
1366
2.88M
         getCUDARuntime().getDeviceSideName(ND) ==
1367
2.88M
             getMangledNameImpl(
1368
2.88M
                 *this,
1369
2.88M
                 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
1370
2.88M
                 ND));
1371
1372
0
  auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1373
2.88M
  return MangledDeclNames[CanonicalGD] = Result.first->first();
1374
4.28M
}
1375
1376
StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1377
1.07k
                                             const BlockDecl *BD) {
1378
1.07k
  MangleContext &MangleCtx = getCXXABI().getMangleContext();
1379
1.07k
  const Decl *D = GD.getDecl();
1380
1381
1.07k
  SmallString<256> Buffer;
1382
1.07k
  llvm::raw_svector_ostream Out(Buffer);
1383
1.07k
  if (!D)
1384
107
    MangleCtx.mangleGlobalBlock(BD,
1385
107
      dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1386
965
  else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1387
32
    MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1388
933
  else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1389
10
    MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1390
923
  else
1391
923
    MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1392
1393
1.07k
  auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1394
1.07k
  return Result.first->first();
1395
1.07k
}
1396
1397
3.67M
llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1398
3.67M
  return getModule().getNamedValue(Name);
1399
3.67M
}
1400
1401
/// AddGlobalCtor - Add a function to the list that will be called before
1402
/// main() runs.
1403
void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1404
4.16k
                                  llvm::Constant *AssociatedData) {
1405
  // FIXME: Type coercion of void()* types.
1406
4.16k
  GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1407
4.16k
}
1408
1409
/// AddGlobalDtor - Add a function to the list that will be called
1410
/// when the module is unloaded.
1411
void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority,
1412
76
                                  bool IsDtorAttrFunc) {
1413
76
  if (CodeGenOpts.RegisterGlobalDtorsWithAtExit &&
1414
76
      
(32
!getContext().getTargetInfo().getTriple().isOSAIX()32
||
IsDtorAttrFunc22
)) {
1415
22
    DtorsUsingAtExit[Priority].push_back(Dtor);
1416
22
    return;
1417
22
  }
1418
1419
  // FIXME: Type coercion of void()* types.
1420
54
  GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1421
54
}
1422
1423
71.6k
void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1424
71.6k
  if (Fns.empty()) 
return68.5k
;
1425
1426
  // Ctor function type is void()*.
1427
3.17k
  llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1428
3.17k
  llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1429
3.17k
      TheModule.getDataLayout().getProgramAddressSpace());
1430
1431
  // Get the type of a ctor entry, { i32, void ()*, i8* }.
1432
3.17k
  llvm::StructType *CtorStructTy = llvm::StructType::get(
1433
3.17k
      Int32Ty, CtorPFTy, VoidPtrTy);
1434
1435
  // Construct the constructor and destructor arrays.
1436
3.17k
  ConstantInitBuilder builder(*this);
1437
3.17k
  auto ctors = builder.beginArray(CtorStructTy);
1438
4.21k
  for (const auto &I : Fns) {
1439
4.21k
    auto ctor = ctors.beginStruct(CtorStructTy);
1440
4.21k
    ctor.addInt(Int32Ty, I.Priority);
1441
4.21k
    ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1442
4.21k
    if (I.AssociatedData)
1443
104
      ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1444
4.11k
    else
1445
4.11k
      ctor.addNullPointer(VoidPtrTy);
1446
4.21k
    ctor.finishAndAddTo(ctors);
1447
4.21k
  }
1448
1449
3.17k
  auto list =
1450
3.17k
    ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1451
3.17k
                                /*constant*/ false,
1452
3.17k
                                llvm::GlobalValue::AppendingLinkage);
1453
1454
  // The LTO linker doesn't seem to like it when we set an alignment
1455
  // on appending variables.  Take it off as a workaround.
1456
3.17k
  list->setAlignment(llvm::None);
1457
1458
3.17k
  Fns.clear();
1459
3.17k
}
1460
1461
llvm::GlobalValue::LinkageTypes
1462
618k
CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1463
618k
  const auto *D = cast<FunctionDecl>(GD.getDecl());
1464
1465
618k
  GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1466
1467
618k
  if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1468
34.6k
    return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1469
1470
583k
  if (isa<CXXConstructorDecl>(D) &&
1471
583k
      
cast<CXXConstructorDecl>(D)->isInheritingConstructor()79.8k
&&
1472
583k
      
Context.getTargetInfo().getCXXABI().isMicrosoft()356
) {
1473
    // Our approach to inheriting constructors is fundamentally different from
1474
    // that used by the MS ABI, so keep our inheriting constructor thunks
1475
    // internal rather than trying to pick an unambiguous mangling for them.
1476
24
    return llvm::GlobalValue::InternalLinkage;
1477
24
  }
1478
1479
583k
  return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1480
583k
}
1481
1482
103
llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1483
103
  llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1484
103
  if (!MDS) 
return nullptr9
;
1485
1486
94
  return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1487
103
}
1488
1489
void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1490
                                              const CGFunctionInfo &Info,
1491
386k
                                              llvm::Function *F, bool IsThunk) {
1492
386k
  unsigned CallingConv;
1493
386k
  llvm::AttributeList PAL;
1494
386k
  ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv,
1495
386k
                         /*AttrOnCallSite=*/false, IsThunk);
1496
386k
  F->setAttributes(PAL);
1497
386k
  F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1498
386k
}
1499
1500
52
static void removeImageAccessQualifier(std::string& TyName) {
1501
52
  std::string ReadOnlyQual("__read_only");
1502
52
  std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1503
52
  if (ReadOnlyPos != std::string::npos)
1504
    // "+ 1" for the space after access qualifier.
1505
24
    TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1506
28
  else {
1507
28
    std::string WriteOnlyQual("__write_only");
1508
28
    std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1509
28
    if (WriteOnlyPos != std::string::npos)
1510
14
      TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1511
14
    else {
1512
14
      std::string ReadWriteQual("__read_write");
1513
14
      std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1514
14
      if (ReadWritePos != std::string::npos)
1515
6
        TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1516
14
    }
1517
28
  }
1518
52
}
1519
1520
// Returns the address space id that should be produced to the
1521
// kernel_arg_addr_space metadata. This is always fixed to the ids
1522
// as specified in the SPIR 2.0 specification in order to differentiate
1523
// for example in clGetKernelArgInfo() implementation between the address
1524
// spaces with targets without unique mapping to the OpenCL address spaces
1525
// (basically all single AS CPUs).
1526
329
static unsigned ArgInfoAddressSpace(LangAS AS) {
1527
329
  switch (AS) {
1528
211
  case LangAS::opencl_global:
1529
211
    return 1;
1530
10
  case LangAS::opencl_constant:
1531
10
    return 2;
1532
108
  case LangAS::opencl_local:
1533
108
    return 3;
1534
0
  case LangAS::opencl_generic:
1535
0
    return 4; // Not in SPIR 2.0 specs.
1536
0
  case LangAS::opencl_global_device:
1537
0
    return 5;
1538
0
  case LangAS::opencl_global_host:
1539
0
    return 6;
1540
0
  default:
1541
0
    return 0; // Assume private.
1542
329
  }
1543
329
}
1544
1545
void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
1546
                                         const FunctionDecl *FD,
1547
458
                                         CodeGenFunction *CGF) {
1548
458
  assert(((FD && CGF) || (!FD && !CGF)) &&
1549
458
         "Incorrect use - FD and CGF should either be both null or not!");
1550
  // Create MDNodes that represent the kernel arg metadata.
1551
  // Each MDNode is a list in the form of "key", N number of values which is
1552
  // the same number of values as their are kernel arguments.
1553
1554
0
  const PrintingPolicy &Policy = Context.getPrintingPolicy();
1555
1556
  // MDNode for the kernel argument address space qualifiers.
1557
458
  SmallVector<llvm::Metadata *, 8> addressQuals;
1558
1559
  // MDNode for the kernel argument access qualifiers (images only).
1560
458
  SmallVector<llvm::Metadata *, 8> accessQuals;
1561
1562
  // MDNode for the kernel argument type names.
1563
458
  SmallVector<llvm::Metadata *, 8> argTypeNames;
1564
1565
  // MDNode for the kernel argument base type names.
1566
458
  SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1567
1568
  // MDNode for the kernel argument type qualifiers.
1569
458
  SmallVector<llvm::Metadata *, 8> argTypeQuals;
1570
1571
  // MDNode for the kernel argument names.
1572
458
  SmallVector<llvm::Metadata *, 8> argNames;
1573
1574
458
  if (FD && 
CGF451
)
1575
1.00k
    
for (unsigned i = 0, e = FD->getNumParams(); 451
i != e;
++i553
) {
1576
553
      const ParmVarDecl *parm = FD->getParamDecl(i);
1577
553
      QualType ty = parm->getType();
1578
553
      std::string typeQuals;
1579
1580
      // Get image and pipe access qualifier:
1581
553
      if (ty->isImageType() || 
ty->isPipeType()527
) {
1582
49
        const Decl *PDecl = parm;
1583
49
        if (auto *TD = dyn_cast<TypedefType>(ty))
1584
13
          PDecl = TD->getDecl();
1585
49
        const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1586
49
        if (A && 
A->isWriteOnly()31
)
1587
12
          accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1588
37
        else if (A && 
A->isReadWrite()19
)
1589
4
          accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1590
33
        else
1591
33
          accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1592
49
      } else
1593
504
        accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1594
1595
      // Get argument name.
1596
553
      argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1597
1598
1.10k
      auto getTypeSpelling = [&](QualType Ty) {
1599
1.10k
        auto typeName = Ty.getUnqualifiedType().getAsString(Policy);
1600
1601
1.10k
        if (Ty.isCanonical()) {
1602
798
          StringRef typeNameRef = typeName;
1603
          // Turn "unsigned type" to "utype"
1604
798
          if (typeNameRef.consume_front("unsigned "))
1605
114
            return std::string("u") + typeNameRef.str();
1606
684
          if (typeNameRef.consume_front("signed "))
1607
8
            return typeNameRef.str();
1608
684
        }
1609
1610
984
        return typeName;
1611
1.10k
      };
1612
1613
553
      if (ty->isPointerType()) {
1614
280
        QualType pointeeTy = ty->getPointeeType();
1615
1616
        // Get address qualifier.
1617
280
        addressQuals.push_back(
1618
280
            llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1619
280
                ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1620
1621
        // Get argument type name.
1622
280
        std::string typeName = getTypeSpelling(pointeeTy) + "*";
1623
280
        std::string baseTypeName =
1624
280
            getTypeSpelling(pointeeTy.getCanonicalType()) + "*";
1625
280
        argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1626
280
        argBaseTypeNames.push_back(
1627
280
            llvm::MDString::get(VMContext, baseTypeName));
1628
1629
        // Get argument type qualifiers:
1630
280
        if (ty.isRestrictQualified())
1631
18
          typeQuals = "restrict";
1632
280
        if (pointeeTy.isConstQualified() ||
1633
280
            
(pointeeTy.getAddressSpace() == LangAS::opencl_constant)262
)
1634
28
          typeQuals += typeQuals.empty() ? 
"const"18
:
" const"10
;
1635
280
        if (pointeeTy.isVolatileQualified())
1636
100
          typeQuals += typeQuals.empty() ? 
"volatile"88
:
" volatile"12
;
1637
280
      } else {
1638
273
        uint32_t AddrSpc = 0;
1639
273
        bool isPipe = ty->isPipeType();
1640
273
        if (ty->isImageType() || 
isPipe247
)
1641
49
          AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1642
1643
273
        addressQuals.push_back(
1644
273
            llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1645
1646
        // Get argument type name.
1647
273
        ty = isPipe ? 
ty->castAs<PipeType>()->getElementType()23
:
ty250
;
1648
273
        std::string typeName = getTypeSpelling(ty);
1649
273
        std::string baseTypeName = getTypeSpelling(ty.getCanonicalType());
1650
1651
        // Remove access qualifiers on images
1652
        // (as they are inseparable from type in clang implementation,
1653
        // but OpenCL spec provides a special query to get access qualifier
1654
        // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1655
273
        if (ty->isImageType()) {
1656
26
          removeImageAccessQualifier(typeName);
1657
26
          removeImageAccessQualifier(baseTypeName);
1658
26
        }
1659
1660
273
        argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1661
273
        argBaseTypeNames.push_back(
1662
273
            llvm::MDString::get(VMContext, baseTypeName));
1663
1664
273
        if (isPipe)
1665
23
          typeQuals = "pipe";
1666
273
      }
1667
553
      argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1668
553
    }
1669
1670
458
  Fn->setMetadata("kernel_arg_addr_space",
1671
458
                  llvm::MDNode::get(VMContext, addressQuals));
1672
458
  Fn->setMetadata("kernel_arg_access_qual",
1673
458
                  llvm::MDNode::get(VMContext, accessQuals));
1674
458
  Fn->setMetadata("kernel_arg_type",
1675
458
                  llvm::MDNode::get(VMContext, argTypeNames));
1676
458
  Fn->setMetadata("kernel_arg_base_type",
1677
458
                  llvm::MDNode::get(VMContext, argBaseTypeNames));
1678
458
  Fn->setMetadata("kernel_arg_type_qual",
1679
458
                  llvm::MDNode::get(VMContext, argTypeQuals));
1680
458
  if (getCodeGenOpts().EmitOpenCLArgMetadata)
1681
10
    Fn->setMetadata("kernel_arg_name",
1682
10
                    llvm::MDNode::get(VMContext, argNames));
1683
458
}
1684
1685
/// Determines whether the language options require us to model
1686
/// unwind exceptions.  We treat -fexceptions as mandating this
1687
/// except under the fragile ObjC ABI with only ObjC exceptions
1688
/// enabled.  This means, for example, that C with -fexceptions
1689
/// enables this.
1690
351k
static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1691
  // If exceptions are completely disabled, obviously this is false.
1692
351k
  if (!LangOpts.Exceptions) 
return false256k
;
1693
1694
  // If C++ exceptions are enabled, this is true.
1695
95.0k
  if (LangOpts.CXXExceptions) 
return true91.9k
;
1696
1697
  // If ObjC exceptions are enabled, this depends on the ABI.
1698
3.10k
  if (LangOpts.ObjCExceptions) {
1699
2.11k
    return LangOpts.ObjCRuntime.hasUnwindExceptions();
1700
2.11k
  }
1701
1702
994
  return true;
1703
3.10k
}
1704
1705
static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1706
110k
                                                      const CXXMethodDecl *MD) {
1707
  // Check that the type metadata can ever actually be used by a call.
1708
110k
  if (!CGM.getCodeGenOpts().LTOUnit ||
1709
110k
      
!CGM.HasHiddenLTOVisibility(MD->getParent())270
)
1710
109k
    return false;
1711
1712
  // Only functions whose address can be taken with a member function pointer
1713
  // need this sort of type metadata.
1714
218
  return !MD->isStatic() && !MD->isVirtual() && 
!isa<CXXConstructorDecl>(MD)128
&&
1715
218
         
!isa<CXXDestructorDecl>(MD)4
;
1716
110k
}
1717
1718
std::vector<const CXXRecordDecl *>
1719
3
CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1720
3
  llvm::SetVector<const CXXRecordDecl *> MostBases;
1721
1722
3
  std::function<void (const CXXRecordDecl *)> CollectMostBases;
1723
8
  CollectMostBases = [&](const CXXRecordDecl *RD) {
1724
8
    if (RD->getNumBases() == 0)
1725
4
      MostBases.insert(RD);
1726
8
    for (const CXXBaseSpecifier &B : RD->bases())
1727
5
      CollectMostBases(B.getType()->getAsCXXRecordDecl());
1728
8
  };
1729
3
  CollectMostBases(RD);
1730
3
  return MostBases.takeVector();
1731
3
}
1732
1733
void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1734
351k
                                                           llvm::Function *F) {
1735
351k
  llvm::AttrBuilder B;
1736
1737
351k
  if (CodeGenOpts.UnwindTables)
1738
92.9k
    B.addAttribute(llvm::Attribute::UWTable);
1739
1740
351k
  if (CodeGenOpts.StackClashProtector)
1741
15
    B.addAttribute("probe-stack", "inline-asm");
1742
1743
351k
  if (!hasUnwindExceptions(LangOpts))
1744
256k
    B.addAttribute(llvm::Attribute::NoUnwind);
1745
1746
351k
  if (!D || 
!D->hasAttr<NoStackProtectorAttr>()336k
) {
1747
351k
    if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1748
91.3k
      B.addAttribute(llvm::Attribute::StackProtect);
1749
260k
    else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1750
49
      B.addAttribute(llvm::Attribute::StackProtectStrong);
1751
260k
    else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1752
2
      B.addAttribute(llvm::Attribute::StackProtectReq);
1753
351k
  }
1754
1755
351k
  if (!D) {
1756
    // If we don't have a declaration to control inlining, the function isn't
1757
    // explicitly marked as alwaysinline for semantic reasons, and inlining is
1758
    // disabled, mark the function as noinline.
1759
15.0k
    if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1760
15.0k
        CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1761
14.5k
      B.addAttribute(llvm::Attribute::NoInline);
1762
1763
15.0k
    F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1764
15.0k
    return;
1765
15.0k
  }
1766
1767
  // Track whether we need to add the optnone LLVM attribute,
1768
  // starting with the default for this optimization level.
1769
336k
  bool ShouldAddOptNone =
1770
336k
      !CodeGenOpts.DisableO0ImplyOptNone && 
CodeGenOpts.OptimizationLevel == 0292k
;
1771
  // We can't add optnone in the following cases, it won't pass the verifier.
1772
336k
  ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1773
336k
  ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1774
1775
  // Add optnone, but do so only if the function isn't always_inline.
1776
336k
  if ((ShouldAddOptNone || 
D->hasAttr<OptimizeNoneAttr>()110k
) &&
1777
336k
      
!F->hasFnAttribute(llvm::Attribute::AlwaysInline)226k
) {
1778
226k
    B.addAttribute(llvm::Attribute::OptimizeNone);
1779
1780
    // OptimizeNone implies noinline; we should not be inlining such functions.
1781
226k
    B.addAttribute(llvm::Attribute::NoInline);
1782
1783
    // We still need to handle naked functions even though optnone subsumes
1784
    // much of their semantics.
1785
226k
    if (D->hasAttr<NakedAttr>())
1786
5
      B.addAttribute(llvm::Attribute::Naked);
1787
1788
    // OptimizeNone wins over OptimizeForSize and MinSize.
1789
226k
    F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1790
226k
    F->removeFnAttr(llvm::Attribute::MinSize);
1791
226k
  } else 
if (110k
D->hasAttr<NakedAttr>()110k
) {
1792
    // Naked implies noinline: we should not be inlining such functions.
1793
2
    B.addAttribute(llvm::Attribute::Naked);
1794
2
    B.addAttribute(llvm::Attribute::NoInline);
1795
110k
  } else if (D->hasAttr<NoDuplicateAttr>()) {
1796
0
    B.addAttribute(llvm::Attribute::NoDuplicate);
1797
110k
  } else if (D->hasAttr<NoInlineAttr>() && 
!F->hasFnAttribute(llvm::Attribute::AlwaysInline)347
) {
1798
    // Add noinline if the function isn't always_inline.
1799
346
    B.addAttribute(llvm::Attribute::NoInline);
1800
110k
  } else if (D->hasAttr<AlwaysInlineAttr>() &&
1801
110k
             
!F->hasFnAttribute(llvm::Attribute::NoInline)29.7k
) {
1802
    // (noinline wins over always_inline, and we can't specify both in IR)
1803
29.7k
    B.addAttribute(llvm::Attribute::AlwaysInline);
1804
80.4k
  } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1805
    // If we're not inlining, then force everything that isn't always_inline to
1806
    // carry an explicit noinline attribute.
1807
40.0k
    if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1808
40.0k
      B.addAttribute(llvm::Attribute::NoInline);
1809
40.4k
  } else {
1810
    // Otherwise, propagate the inline hint attribute and potentially use its
1811
    // absence to mark things as noinline.
1812
40.4k
    if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1813
      // Search function and template pattern redeclarations for inline.
1814
40.1k
      auto CheckForInline = [](const FunctionDecl *FD) {
1815
41.9k
        auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1816
41.9k
          return Redecl->isInlineSpecified();
1817
41.9k
        };
1818
40.1k
        if (any_of(FD->redecls(), CheckRedeclForInline))
1819
1.43k
          return true;
1820
38.7k
        const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1821
38.7k
        if (!Pattern)
1822
37.7k
          return false;
1823
986
        return any_of(Pattern->redecls(), CheckRedeclForInline);
1824
38.7k
      };
1825
40.1k
      if (CheckForInline(FD)) {
1826
1.46k
        B.addAttribute(llvm::Attribute::InlineHint);
1827
38.7k
      } else if (CodeGenOpts.getInlining() ==
1828
38.7k
                     CodeGenOptions::OnlyHintInlining &&
1829
38.7k
                 
!FD->isInlined()21
&&
1830
38.7k
                 
!F->hasFnAttribute(llvm::Attribute::AlwaysInline)11
) {
1831
11
        B.addAttribute(llvm::Attribute::NoInline);
1832
11
      }
1833
40.1k
    }
1834
40.4k
  }
1835
1836
  // Add other optimization related attributes if we are optimizing this
1837
  // function.
1838
336k
  if (!D->hasAttr<OptimizeNoneAttr>()) {
1839
336k
    if (D->hasAttr<ColdAttr>()) {
1840
22
      if (!ShouldAddOptNone)
1841
1
        B.addAttribute(llvm::Attribute::OptimizeForSize);
1842
22
      B.addAttribute(llvm::Attribute::Cold);
1843
22
    }
1844
336k
    if (D->hasAttr<HotAttr>())
1845
4
      B.addAttribute(llvm::Attribute::Hot);
1846
336k
    if (D->hasAttr<MinSizeAttr>())
1847
22
      B.addAttribute(llvm::Attribute::MinSize);
1848
336k
  }
1849
1850
336k
  F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1851
1852
336k
  unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1853
336k
  if (alignment)
1854
9
    F->setAlignment(llvm::Align(alignment));
1855
1856
336k
  if (!D->hasAttr<AlignedAttr>())
1857
336k
    if (LangOpts.FunctionAlignment)
1858
2
      F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
1859
1860
  // Some C++ ABIs require 2-byte alignment for member functions, in order to
1861
  // reserve a bit for differentiating between virtual and non-virtual member
1862
  // functions. If the current target's C++ ABI requires this and this is a
1863
  // member function, set its alignment accordingly.
1864
336k
  if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1865
335k
    if (F->getAlignment() < 2 && 
isa<CXXMethodDecl>(D)335k
)
1866
110k
      F->setAlignment(llvm::Align(2));
1867
335k
  }
1868
1869
  // In the cross-dso CFI mode with canonical jump tables, we want !type
1870
  // attributes on definitions only.
1871
336k
  if (CodeGenOpts.SanitizeCfiCrossDso &&
1872
336k
      
CodeGenOpts.SanitizeCfiCanonicalJumpTables47
) {
1873
26
    if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1874
      // Skip available_externally functions. They won't be codegen'ed in the
1875
      // current module anyway.
1876
26
      if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
1877
24
        CreateFunctionTypeMetadataForIcall(FD, F);
1878
26
    }
1879
26
  }
1880
1881
  // Emit type metadata on member functions for member function pointer checks.
1882
  // These are only ever necessary on definitions; we're guaranteed that the
1883
  // definition will be present in the LTO unit as a result of LTO visibility.
1884
336k
  auto *MD = dyn_cast<CXXMethodDecl>(D);
1885
336k
  if (MD && 
requiresMemberFunctionPointerTypeMetadata(*this, MD)110k
) {
1886
2
    for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1887
2
      llvm::Metadata *Id =
1888
2
          CreateMetadataIdentifierForType(Context.getMemberPointerType(
1889
2
              MD->getType(), Context.getRecordType(Base).getTypePtr()));
1890
2
      F->addTypeMetadata(0, Id);
1891
2
    }
1892
2
  }
1893
336k
}
1894
1895
void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D,
1896
251k
                                                  llvm::Function *F) {
1897
251k
  if (D->hasAttr<StrictFPAttr>()) {
1898
1.76k
    llvm::AttrBuilder FuncAttrs;
1899
1.76k
    FuncAttrs.addAttribute("strictfp");
1900
1.76k
    F->addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs);
1901
1.76k
  }
1902
251k
}
1903
1904
374k
void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1905
374k
  const Decl *D = GD.getDecl();
1906
374k
  if (dyn_cast_or_null<NamedDecl>(D))
1907
334k
    setGVProperties(GV, GD);
1908
39.4k
  else
1909
39.4k
    GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1910
1911
374k
  if (D && 
D->hasAttr<UsedAttr>()360k
)
1912
1.00k
    addUsedOrCompilerUsedGlobal(GV);
1913
1914
374k
  if (CodeGenOpts.KeepStaticConsts && 
D4
&&
isa<VarDecl>(D)4
) {
1915
4
    const auto *VD = cast<VarDecl>(D);
1916
4
    if (VD->getType().isConstQualified() &&
1917
4
        VD->getStorageDuration() == SD_Static)
1918
4
      addUsedOrCompilerUsedGlobal(GV);
1919
4
  }
1920
374k
}
1921
1922
bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
1923
722k
                                                llvm::AttrBuilder &Attrs) {
1924
  // Add target-cpu and target-features attributes to functions. If
1925
  // we have a decl for the function and it has a target attribute then
1926
  // parse that and add it to the feature set.
1927
722k
  StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1928
722k
  StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU;
1929
722k
  std::vector<std::string> Features;
1930
722k
  const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
1931
722k
  FD = FD ? 
FD->getMostRecentDecl()651k
:
FD71.1k
;
1932
722k
  const auto *TD = FD ? 
FD->getAttr<TargetAttr>()651k
:
nullptr71.1k
;
1933
722k
  const auto *SD = FD ? 
FD->getAttr<CPUSpecificAttr>()651k
:
nullptr71.1k
;
1934
722k
  bool AddedAttr = false;
1935
722k
  if (TD || 
SD706k
) {
1936
16.6k
    llvm::StringMap<bool> FeatureMap;
1937
16.6k
    getContext().getFunctionFeatureMap(FeatureMap, GD);
1938
1939
    // Produce the canonical string for this set of features.
1940
16.6k
    for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1941
232k
      Features.push_back((Entry.getValue() ? 
"+"232k
:
"-"306
) + Entry.getKey().str());
1942
1943
    // Now add the target-cpu and target-features to the function.
1944
    // While we populated the feature map above, we still need to
1945
    // get and parse the target attribute so we can get the cpu for
1946
    // the function.
1947
16.6k
    if (TD) {
1948
16.5k
      ParsedTargetAttr ParsedAttr = TD->parse();
1949
16.5k
      if (!ParsedAttr.Architecture.empty() &&
1950
16.5k
          
getTarget().isValidCPUName(ParsedAttr.Architecture)163
) {
1951
163
        TargetCPU = ParsedAttr.Architecture;
1952
163
        TuneCPU = ""; // Clear the tune CPU.
1953
163
      }
1954
16.5k
      if (!ParsedAttr.Tune.empty() &&
1955
16.5k
          
getTarget().isValidCPUName(ParsedAttr.Tune)2
)
1956
2
        TuneCPU = ParsedAttr.Tune;
1957
16.5k
    }
1958
705k
  } else {
1959
    // Otherwise just add the existing target cpu and target features to the
1960
    // function.
1961
705k
    Features = getTarget().getTargetOpts().Features;
1962
705k
  }
1963
1964
722k
  if (!TargetCPU.empty()) {
1965
223k
    Attrs.addAttribute("target-cpu", TargetCPU);
1966
223k
    AddedAttr = true;
1967
223k
  }
1968
722k
  if (!TuneCPU.empty()) {
1969
193k
    Attrs.addAttribute("tune-cpu", TuneCPU);
1970
193k
    AddedAttr = true;
1971
193k
  }
1972
722k
  if (!Features.empty()) {
1973
709k
    llvm::sort(Features);
1974
709k
    Attrs.addAttribute("target-features", llvm::join(Features, ","));
1975
709k
    AddedAttr = true;
1976
709k
  }
1977
1978
722k
  return AddedAttr;
1979
722k
}
1980
1981
void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1982
374k
                                          llvm::GlobalObject *GO) {
1983
374k
  const Decl *D = GD.getDecl();
1984
374k
  SetCommonAttributes(GD, GO);
1985
1986
374k
  if (D) {
1987
360k
    if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1988
24.1k
      if (D->hasAttr<RetainAttr>())
1989
5
        addUsedGlobal(GV);
1990
24.1k
      if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1991
31
        GV->addAttribute("bss-section", SA->getName());
1992
24.1k
      if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1993
22
        GV->addAttribute("data-section", SA->getName());
1994
24.1k
      if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1995
30
        GV->addAttribute("rodata-section", SA->getName());
1996
24.1k
      if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
1997
12
        GV->addAttribute("relro-section", SA->getName());
1998
24.1k
    }
1999
2000
360k
    if (auto *F = dyn_cast<llvm::Function>(GO)) {
2001
336k
      if (D->hasAttr<RetainAttr>())
2002
9
        addUsedGlobal(F);
2003
336k
      if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
2004
8
        if (!D->getAttr<SectionAttr>())
2005
4
          F->addFnAttr("implicit-section-name", SA->getName());
2006
2007
336k
      llvm::AttrBuilder Attrs;
2008
336k
      if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
2009
        // We know that GetCPUAndFeaturesAttributes will always have the
2010
        // newest set, since it has the newest possible FunctionDecl, so the
2011
        // new ones should replace the old.
2012
330k
        llvm::AttrBuilder RemoveAttrs;
2013
330k
        RemoveAttrs.addAttribute("target-cpu");
2014
330k
        RemoveAttrs.addAttribute("target-features");
2015
330k
        RemoveAttrs.addAttribute("tune-cpu");
2016
330k
        F->removeAttributes(llvm::AttributeList::FunctionIndex, RemoveAttrs);
2017
330k
        F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
2018
330k
      }
2019
336k
    }
2020
2021
360k
    if (const auto *CSA = D->getAttr<CodeSegAttr>())
2022
28
      GO->setSection(CSA->getName());
2023
360k
    else if (const auto *SA = D->getAttr<SectionAttr>())
2024
108
      GO->setSection(SA->getName());
2025
360k
  }
2026
2027
374k
  getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
2028
374k
}
2029
2030
void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
2031
                                                  llvm::Function *F,
2032
41.9k
                                                  const CGFunctionInfo &FI) {
2033
41.9k
  const Decl *D = GD.getDecl();
2034
41.9k
  SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false);
2035
41.9k
  SetLLVMFunctionAttributesForDefinition(D, F);
2036
2037
41.9k
  F->setLinkage(llvm::Function::InternalLinkage);
2038
2039
41.9k
  setNonAliasAttributes(GD, F);
2040
41.9k
}
2041
2042
378k
static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
2043
  // Set linkage and visibility in case we never see a definition.
2044
378k
  LinkageInfo LV = ND->getLinkageAndVisibility();
2045
  // Don't set internal linkage on declarations.
2046
  // "extern_weak" is overloaded in LLVM; we probably should have
2047
  // separate linkage types for this.
2048
378k
  if (isExternallyVisible(LV.getLinkage()) &&
2049
378k
      
(332k
ND->hasAttr<WeakAttr>()332k
||
ND->isWeakImported()332k
))
2050
106
    GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
2051
378k
}
2052
2053
void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
2054
343k
                                                       llvm::Function *F) {
2055
  // Only if we are checking indirect calls.
2056
343k
  if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
2057
343k
    return;
2058
2059
  // Non-static class methods are handled via vtable or member function pointer
2060
  // checks elsewhere.
2061
65
  if (isa<CXXMethodDecl>(FD) && 
!cast<CXXMethodDecl>(FD)->isStatic()2
)
2062
2
    return;
2063
2064
63
  llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
2065
63
  F->addTypeMetadata(0, MD);
2066
63
  F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
2067
2068
  // Emit a hash-based bit set entry for cross-DSO calls.
2069
63
  if (CodeGenOpts.SanitizeCfiCrossDso)
2070
29
    if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
2071
29
      F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
2072
63
}
2073
2074
void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
2075
                                          bool IsIncompleteFunction,
2076
343k
                                          bool IsThunk) {
2077
2078
343k
  if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
2079
    // If this is an intrinsic function, set the function's attributes
2080
    // to the intrinsic's attributes.
2081
3
    F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
2082
3
    return;
2083
3
  }
2084
2085
343k
  const auto *FD = cast<FunctionDecl>(GD.getDecl());
2086
2087
343k
  if (!IsIncompleteFunction)
2088
343k
    SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F,
2089
343k
                              IsThunk);
2090
2091
  // Add the Returned attribute for "this", except for iOS 5 and earlier
2092
  // where substantial code, including the libstdc++ dylib, was compiled with
2093
  // GCC and does not actually return "this".
2094
343k
  if (!IsThunk && 
getCXXABI().HasThisReturn(GD)342k
&&
2095
343k
      
!(2.02k
getTriple().isiOS()2.02k
&&
getTriple().isOSVersionLT(6)212
)) {
2096
1.99k
    assert(!F->arg_empty() &&
2097
1.99k
           F->arg_begin()->getType()
2098
1.99k
             ->canLosslesslyBitCastTo(F->getReturnType()) &&
2099
1.99k
           "unexpected this return");
2100
0
    F->addAttribute(1, llvm::Attribute::Returned);
2101
1.99k
  }
2102
2103
  // Only a few attributes are set on declarations; these may later be
2104
  // overridden by a definition.
2105
2106
0
  setLinkageForGV(F, FD);
2107
343k
  setGVProperties(F, FD);
2108
2109
  // Setup target-specific attributes.
2110
343k
  if (!IsIncompleteFunction && 
F->isDeclaration()343k
)
2111
343k
    getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2112
2113
343k
  if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2114
28
    F->setSection(CSA->getName());
2115
343k
  else if (const auto *SA = FD->getAttr<SectionAttr>())
2116
47
     F->setSection(SA->getName());
2117
2118
  // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2119
343k
  if (FD->isInlineBuiltinDeclaration()) {
2120
18
    const FunctionDecl *FDBody;
2121
18
    bool HasBody = FD->hasBody(FDBody);
2122
18
    (void)HasBody;
2123
18
    assert(HasBody && "Inline builtin declarations should always have an "
2124
18
                      "available body!");
2125
18
    if (shouldEmitFunction(FDBody))
2126
15
      F->addAttribute(llvm::AttributeList::FunctionIndex,
2127
15
                      llvm::Attribute::NoBuiltin);
2128
18
  }
2129
2130
343k
  if (FD->isReplaceableGlobalAllocationFunction()) {
2131
    // A replaceable global allocation function does not act like a builtin by
2132
    // default, only if it is invoked by a new-expression or delete-expression.
2133
1.81k
    F->addAttribute(llvm::AttributeList::FunctionIndex,
2134
1.81k
                    llvm::Attribute::NoBuiltin);
2135
1.81k
  }
2136
2137
343k
  if (isa<CXXConstructorDecl>(FD) || 
isa<CXXDestructorDecl>(FD)301k
)
2138
61.6k
    F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2139
281k
  else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2140
57.4k
    if (MD->isVirtual())
2141
2.95k
      F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2142
2143
  // Don't emit entries for function declarations in the cross-DSO mode. This
2144
  // is handled with better precision by the receiving DSO. But if jump tables
2145
  // are non-canonical then we need type metadata in order to produce the local
2146
  // jump table.
2147
343k
  if (!CodeGenOpts.SanitizeCfiCrossDso ||
2148
343k
      
!CodeGenOpts.SanitizeCfiCanonicalJumpTables58
)
2149
343k
    CreateFunctionTypeMetadataForIcall(FD, F);
2150
2151
343k
  if (getLangOpts().OpenMP && 
FD->hasAttr<OMPDeclareSimdDeclAttr>()35.8k
)
2152
162
    getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2153
2154
343k
  if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2155
    // Annotate the callback behavior as metadata:
2156
    //  - The callback callee (as argument number).
2157
    //  - The callback payloads (as argument numbers).
2158
17
    llvm::LLVMContext &Ctx = F->getContext();
2159
17
    llvm::MDBuilder MDB(Ctx);
2160
2161
    // The payload indices are all but the first one in the encoding. The first
2162
    // identifies the callback callee.
2163
17
    int CalleeIdx = *CB->encoding_begin();
2164
17
    ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2165
17
    F->addMetadata(llvm::LLVMContext::MD_callback,
2166
17
                   *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2167
17
                                               CalleeIdx, PayloadIndices,
2168
17
                                               /* VarArgsArePassed */ false)}));
2169
17
  }
2170
343k
}
2171
2172
798
void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2173
798
  assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2174
798
         "Only globals with definition can force usage.");
2175
0
  LLVMUsed.emplace_back(GV);
2176
798
}
2177
2178
26.0k
void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2179
26.0k
  assert(!GV->isDeclaration() &&
2180
26.0k
         "Only globals with definition can force usage.");
2181
0
  LLVMCompilerUsed.emplace_back(GV);
2182
26.0k
}
2183
2184
1.00k
void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) {
2185
1.00k
  assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) &&
2186
1.00k
         "Only globals with definition can force usage.");
2187
1.00k
  if (getTriple().isOSBinFormatELF())
2188
60
    LLVMCompilerUsed.emplace_back(GV);
2189
948
  else
2190
948
    LLVMUsed.emplace_back(GV);
2191
1.00k
}
2192
2193
static void emitUsed(CodeGenModule &CGM, StringRef Name,
2194
71.6k
                     std::vector<llvm::WeakTrackingVH> &List) {
2195
  // Don't create llvm.used if there is no need.
2196
71.6k
  if (List.empty())
2197
68.4k
    return;
2198
2199
  // Convert List to what ConstantArray needs.
2200
3.24k
  SmallVector<llvm::Constant*, 8> UsedArray;
2201
3.24k
  UsedArray.resize(List.size());
2202
31.0k
  for (unsigned i = 0, e = List.size(); i != e; 
++i27.8k
) {
2203
27.8k
    UsedArray[i] =
2204
27.8k
        llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2205
27.8k
            cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
2206
27.8k
  }
2207
2208
3.24k
  if (UsedArray.empty())
2209
0
    return;
2210
3.24k
  llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
2211
2212
3.24k
  auto *GV = new llvm::GlobalVariable(
2213
3.24k
      CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2214
3.24k
      llvm::ConstantArray::get(ATy, UsedArray), Name);
2215
2216
3.24k
  GV->setSection("llvm.metadata");
2217
3.24k
}
2218
2219
35.8k
void CodeGenModule::emitLLVMUsed() {
2220
35.8k
  emitUsed(*this, "llvm.used", LLVMUsed);
2221
35.8k
  emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2222
35.8k
}
2223
2224
13
void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2225
13
  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2226
13
  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2227
13
}
2228
2229
14
void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2230
14
  llvm::SmallString<32> Opt;
2231
14
  getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2232
14
  if (Opt.empty())
2233
4
    return;
2234
10
  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2235
10
  LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2236
10
}
2237
2238
90
void CodeGenModule::AddDependentLib(StringRef Lib) {
2239
90
  auto &C = getLLVMContext();
2240
90
  if (getTarget().getTriple().isOSBinFormatELF()) {
2241
17
      ELFDependentLibraries.push_back(
2242
17
        llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2243
17
    return;
2244
17
  }
2245
2246
73
  llvm::SmallString<24> Opt;
2247
73
  getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2248
73
  auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2249
73
  LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2250
73
}
2251
2252
/// Add link options implied by the given module, including modules
2253
/// it depends on, using a postorder walk.
2254
static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2255
                                    SmallVectorImpl<llvm::MDNode *> &Metadata,
2256
436k
                                    llvm::SmallPtrSet<Module *, 16> &Visited) {
2257
  // Import this module's parent.
2258
436k
  if (Mod->Parent && 
Visited.insert(Mod->Parent).second430k
) {
2259
22.9k
    addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2260
22.9k
  }
2261
2262
  // Import this module's dependencies.
2263
1.97M
  for (unsigned I = Mod->Imports.size(); I > 0; 
--I1.54M
) {
2264
1.54M
    if (Visited.insert(Mod->Imports[I - 1]).second)
2265
362k
      addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
2266
1.54M
  }
2267
2268
  // Add linker options to link against the libraries/frameworks
2269
  // described by this module.
2270
436k
  llvm::LLVMContext &Context = CGM.getLLVMContext();
2271
436k
  bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2272
2273
  // For modules that use export_as for linking, use that module
2274
  // name instead.
2275
436k
  if (Mod->UseExportAsModuleLinkName)
2276
4
    return;
2277
2278
438k
  
for (unsigned I = Mod->LinkLibraries.size(); 436k
I > 0;
--I1.25k
) {
2279
    // Link against a framework.  Frameworks are currently Darwin only, so we
2280
    // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2281
1.25k
    if (Mod->LinkLibraries[I-1].IsFramework) {
2282
1.25k
      llvm::Metadata *Args[2] = {
2283
1.25k
          llvm::MDString::get(Context, "-framework"),
2284
1.25k
          llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
2285
2286
1.25k
      Metadata.push_back(llvm::MDNode::get(Context, Args));
2287
1.25k
      continue;
2288
1.25k
    }
2289
2290
    // Link against a library.
2291
2
    if (IsELF) {
2292
0
      llvm::Metadata *Args[2] = {
2293
0
          llvm::MDString::get(Context, "lib"),
2294
0
          llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
2295
0
      };
2296
0
      Metadata.push_back(llvm::MDNode::get(Context, Args));
2297
2
    } else {
2298
2
      llvm::SmallString<24> Opt;
2299
2
      CGM.getTargetCodeGenInfo().getDependentLibraryOption(
2300
2
          Mod->LinkLibraries[I - 1].Library, Opt);
2301
2
      auto *OptString = llvm::MDString::get(Context, Opt);
2302
2
      Metadata.push_back(llvm::MDNode::get(Context, OptString));
2303
2
    }
2304
2
  }
2305
436k
}
2306
2307
2.08k
void CodeGenModule::EmitModuleLinkOptions() {
2308
  // Collect the set of all of the modules we want to visit to emit link
2309
  // options, which is essentially the imported modules and all of their
2310
  // non-explicit child modules.
2311
2.08k
  llvm::SetVector<clang::Module *> LinkModules;
2312
2.08k
  llvm::SmallPtrSet<clang::Module *, 16> Visited;
2313
2.08k
  SmallVector<clang::Module *, 16> Stack;
2314
2315
  // Seed the stack with imported modules.
2316
2.08k
  for (Module *M : ImportedModules) {
2317
    // Do not add any link flags when an implementation TU of a module imports
2318
    // a header of that same module.
2319
1.98k
    if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2320
1.98k
        
!getLangOpts().isCompilingModule()1
)
2321
1
      continue;
2322
1.98k
    if (Visited.insert(M).second)
2323
1.98k
      Stack.push_back(M);
2324
1.98k
  }
2325
2326
  // Find all of the modules to import, making a little effort to prune
2327
  // non-leaf modules.
2328
140k
  while (!Stack.empty()) {
2329
138k
    clang::Module *Mod = Stack.pop_back_val();
2330
2331
138k
    bool AnyChildren = false;
2332
2333
    // Visit the submodules of this module.
2334
138k
    for (const auto &SM : Mod->submodules()) {
2335
      // Skip explicit children; they need to be explicitly imported to be
2336
      // linked against.
2337
136k
      if (SM->IsExplicit)
2338
121
        continue;
2339
2340
136k
      if (Visited.insert(SM).second) {
2341
136k
        Stack.push_back(SM);
2342
136k
        AnyChildren = true;
2343
136k
      }
2344
136k
    }
2345
2346
    // We didn't find any children, so add this module to the list of
2347
    // modules to link against.
2348
138k
    if (!AnyChildren) {
2349
135k
      LinkModules.insert(Mod);
2350
135k
    }
2351
138k
  }
2352
2353
  // Add link options for all of the imported modules in reverse topological
2354
  // order.  We don't do anything to try to order import link flags with respect
2355
  // to linker options inserted by things like #pragma comment().
2356
2.08k
  SmallVector<llvm::MDNode *, 16> MetadataArgs;
2357
2.08k
  Visited.clear();
2358
2.08k
  for (Module *M : LinkModules)
2359
135k
    if (Visited.insert(M).second)
2360
50.8k
      addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2361
2.08k
  std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2362
2.08k
  LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2363
2364
  // Add the linker options metadata flag.
2365
2.08k
  auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2366
2.08k
  for (auto *MD : LinkerOptionsMetadata)
2367
1.35k
    NMD->addOperand(MD);
2368
2.08k
}
2369
2370
107k
void CodeGenModule::EmitDeferred() {
2371
  // Emit deferred declare target declarations.
2372
107k
  if (getLangOpts().OpenMP && 
!getLangOpts().OpenMPSimd18.2k
)
2373
10.6k
    getOpenMPRuntime().emitDeferredTargetDecls();
2374
2375
  // Emit code for any potentially referenced deferred decls.  Since a
2376
  // previously unused static decl may become used during the generation of code
2377
  // for a static function, iterate until no changes are made.
2378
2379
107k
  if (!DeferredVTables.empty()) {
2380
2.33k
    EmitDeferredVTables();
2381
2382
    // Emitting a vtable doesn't directly cause more vtables to
2383
    // become deferred, although it can cause functions to be
2384
    // emitted that then need those vtables.
2385
2.33k
    assert(DeferredVTables.empty());
2386
2.33k
  }
2387
2388
  // Emit CUDA/HIP static device variables referenced by host code only.
2389
  // Note we should not clear CUDADeviceVarODRUsedByHost since it is still
2390
  // needed for further handling.
2391
107k
  if (getLangOpts().CUDA && 
getLangOpts().CUDAIsDevice364
)
2392
240
    for (const auto *V : getContext().CUDADeviceVarODRUsedByHost)
2393
166
      DeferredDeclsToEmit.push_back(V);
2394
2395
  // Stop if we're out of both deferred vtables and deferred declarations.
2396
107k
  if (DeferredDeclsToEmit.empty())
2397
28.4k
    return;
2398
2399
  // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2400
  // work, it will not interfere with this.
2401
78.6k
  std::vector<GlobalDecl> CurDeclsToEmit;
2402
78.6k
  CurDeclsToEmit.swap(DeferredDeclsToEmit);
2403
2404
164k
  for (GlobalDecl &D : CurDeclsToEmit) {
2405
    // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2406
    // to get GlobalValue with exactly the type we need, not something that
2407
    // might had been created for another decl with the same mangled name but
2408
    // different type.
2409
164k
    llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2410
164k
        GetAddrOfGlobal(D, ForDefinition));
2411
2412
    // In case of different address spaces, we may still get a cast, even with
2413
    // IsForDefinition equal to true. Query mangled names table to get
2414
    // GlobalValue.
2415
164k
    if (!GV)
2416
253
      GV = GetGlobalValue(getMangledName(D));
2417
2418
    // Make sure GetGlobalValue returned non-null.
2419
164k
    assert(GV);
2420
2421
    // Check to see if we've already emitted this.  This is necessary
2422
    // for a couple of reasons: first, decls can end up in the
2423
    // deferred-decls queue multiple times, and second, decls can end
2424
    // up with definitions in unusual ways (e.g. by an extern inline
2425
    // function acquiring a strong function redefinition).  Just
2426
    // ignore these cases.
2427
164k
    if (!GV->isDeclaration())
2428
2.12k
      continue;
2429
2430
    // If this is OpenMP, check if it is legal to emit this global normally.
2431
162k
    if (LangOpts.OpenMP && 
OpenMPRuntime31.9k
&&
OpenMPRuntime->emitTargetGlobal(D)31.9k
)
2432
25
      continue;
2433
2434
    // Otherwise, emit the definition and move on to the next one.
2435
162k
    EmitGlobalDefinition(D, GV);
2436
2437
    // If we found out that we need to emit more decls, do that recursively.
2438
    // This has the advantage that the decls are emitted in a DFS and related
2439
    // ones are close together, which is convenient for testing.
2440
162k
    if (!DeferredVTables.empty() || 
!DeferredDeclsToEmit.empty()160k
) {
2441
71.1k
      EmitDeferred();
2442
71.1k
      assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2443
71.1k
    }
2444
162k
  }
2445
78.6k
}
2446
2447
35.8k
void CodeGenModule::EmitVTablesOpportunistically() {
2448
  // Try to emit external vtables as available_externally if they have emitted
2449
  // all inlined virtual functions.  It runs after EmitDeferred() and therefore
2450
  // is not allowed to create new references to things that need to be emitted
2451
  // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2452
2453
35.8k
  assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2454
35.8k
         && "Only emit opportunistic vtables with optimizations");
2455
2456
24
  for (const CXXRecordDecl *RD : OpportunisticVTables) {
2457
24
    assert(getVTables().isVTableExternal(RD) &&
2458
24
           "This queue should only contain external vtables");
2459
24
    if (getCXXABI().canSpeculativelyEmitVTable(RD))
2460
4
      VTables.GenerateClassData(RD);
2461
24
  }
2462
35.8k
  OpportunisticVTables.clear();
2463
35.8k
}
2464
2465
35.8k
void CodeGenModule::EmitGlobalAnnotations() {
2466
35.8k
  if (Annotations.empty())
2467
35.8k
    return;
2468
2469
  // Create a new global variable for the ConstantStruct in the Module.
2470
5
  llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2471
5
    Annotations[0]->getType(), Annotations.size()), Annotations);
2472
5
  auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2473
5
                                      llvm::GlobalValue::AppendingLinkage,
2474
5
                                      Array, "llvm.global.annotations");
2475
5
  gv->setSection(AnnotationSection);
2476
5
}
2477
2478
94
llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2479
94
  llvm::Constant *&AStr = AnnotationStrings[Str];
2480
94
  if (AStr)
2481
55
    return AStr;
2482
2483
  // Not found yet, create a new global.
2484
39
  llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2485
39
  auto *gv =
2486
39
      new llvm::GlobalVariable(getModule(), s->getType(), true,
2487
39
                               llvm::GlobalValue::PrivateLinkage, s, ".str");
2488
39
  gv->setSection(AnnotationSection);
2489
39
  gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2490
39
  AStr = gv;
2491
39
  return gv;
2492
94
}
2493
2494
47
llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2495
47
  SourceManager &SM = getContext().getSourceManager();
2496
47
  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2497
47
  if (PLoc.isValid())
2498
47
    return EmitAnnotationString(PLoc.getFilename());
2499
0
  return EmitAnnotationString(SM.getBufferName(Loc));
2500
47
}
2501
2502
47
llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2503
47
  SourceManager &SM = getContext().getSourceManager();
2504
47
  PresumedLoc PLoc = SM.getPresumedLoc(L);
2505
47
  unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2506
47
    
SM.getExpansionLineNumber(L)0
;
2507
47
  return llvm::ConstantInt::get(Int32Ty, LineNo);
2508
47
}
2509
2510
40
llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) {
2511
40
  ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()};
2512
40
  if (Exprs.empty())
2513
33
    return llvm::ConstantPointerNull::get(Int8PtrTy);
2514
2515
7
  llvm::FoldingSetNodeID ID;
2516
13
  for (Expr *E : Exprs) {
2517
13
    ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult());
2518
13
  }
2519
7
  llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()];
2520
7
  if (Lookup)
2521
1
    return Lookup;
2522
2523
6
  llvm::SmallVector<llvm::Constant *, 4> LLVMArgs;
2524
6
  LLVMArgs.reserve(Exprs.size());
2525
6
  ConstantEmitter ConstEmiter(*this);
2526
12
  llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) {
2527
12
    const auto *CE = cast<clang::ConstantExpr>(E);
2528
12
    return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(),
2529
12
                                    CE->getType());
2530
12
  });
2531
6
  auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs);
2532
6
  auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true,
2533
6
                                      llvm::GlobalValue::PrivateLinkage, Struct,
2534
6
                                      ".args");
2535
6
  GV->setSection(AnnotationSection);
2536
6
  GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2537
6
  auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy);
2538
2539
6
  Lookup = Bitcasted;
2540
6
  return Bitcasted;
2541
7
}
2542
2543
llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2544
                                                const AnnotateAttr *AA,
2545
20
                                                SourceLocation L) {
2546
  // Get the globals for file name, annotation, and the line number.
2547
20
  llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2548
20
                 *UnitGV = EmitAnnotationUnit(L),
2549
20
                 *LineNoCst = EmitAnnotationLineNo(L),
2550
20
                 *Args = EmitAnnotationArgs(AA);
2551
2552
20
  llvm::Constant *ASZeroGV = GV;
2553
20
  if (GV->getAddressSpace() != 0) {
2554
1
    ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2555
1
                   GV, GV->getValueType()->getPointerTo(0));
2556
1
  }
2557
2558
  // Create the ConstantStruct for the global annotation.
2559
20
  llvm::Constant *Fields[] = {
2560
20
      llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
2561
20
      llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2562
20
      llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2563
20
      LineNoCst,
2564
20
      Args,
2565
20
  };
2566
20
  return llvm::ConstantStruct::getAnon(Fields);
2567
20
}
2568
2569
void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2570
14
                                         llvm::GlobalValue *GV) {
2571
14
  assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2572
  // Get the struct elements for these annotations.
2573
0
  for (const auto *I : D->specific_attrs<AnnotateAttr>())
2574
20
    Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2575
14
}
2576
2577
bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn,
2578
8.07k
                                       SourceLocation Loc) const {
2579
8.07k
  const auto &NoSanitizeL = getContext().getNoSanitizeList();
2580
  // NoSanitize by function name.
2581
8.07k
  if (NoSanitizeL.containsFunction(Kind, Fn->getName()))
2582
18
    return true;
2583
  // NoSanitize by location.
2584
8.05k
  if (Loc.isValid())
2585
7.78k
    return NoSanitizeL.containsLocation(Kind, Loc);
2586
  // If location is unknown, this may be a compiler-generated function. Assume
2587
  // it's located in the main file.
2588
277
  auto &SM = Context.getSourceManager();
2589
277
  if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2590
277
    return NoSanitizeL.containsFile(Kind, MainFile->getName());
2591
277
  }
2592
0
  return false;
2593
277
}
2594
2595
bool CodeGenModule::isInNoSanitizeList(llvm::GlobalVariable *GV,
2596
                                       SourceLocation Loc, QualType Ty,
2597
490
                                       StringRef Category) const {
2598
  // For now globals can be ignored only in ASan and KASan.
2599
490
  const SanitizerMask EnabledAsanMask =
2600
490
      LangOpts.Sanitize.Mask &
2601
490
      (SanitizerKind::Address | SanitizerKind::KernelAddress |
2602
490
       SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2603
490
       SanitizerKind::MemTag);
2604
490
  if (!EnabledAsanMask)
2605
0
    return false;
2606
490
  const auto &NoSanitizeL = getContext().getNoSanitizeList();
2607
490
  if (NoSanitizeL.containsGlobal(EnabledAsanMask, GV->getName(), Category))
2608
2
    return true;
2609
488
  if (NoSanitizeL.containsLocation(EnabledAsanMask, Loc, Category))
2610
23
    return true;
2611
  // Check global type.
2612
465
  if (!Ty.isNull()) {
2613
    // Drill down the array types: if global variable of a fixed type is
2614
    // not sanitized, we also don't instrument arrays of them.
2615
419
    while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2616
32
      Ty = AT->getElementType();
2617
387
    Ty = Ty.getCanonicalType().getUnqualifiedType();
2618
    // Only record types (classes, structs etc.) are ignored.
2619
387
    if (Ty->isRecordType()) {
2620
164
      std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2621
164
      if (NoSanitizeL.containsType(EnabledAsanMask, TypeStr, Category))
2622
2
        return true;
2623
164
    }
2624
387
  }
2625
463
  return false;
2626
465
}
2627
2628
bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2629
31
                                   StringRef Category) const {
2630
31
  const auto &XRayFilter = getContext().getXRayFilter();
2631
31
  using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2632
31
  auto Attr = ImbueAttr::NONE;
2633
31
  if (Loc.isValid())
2634
29
    Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2635
31
  if (Attr == ImbueAttr::NONE)
2636
23
    Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2637
31
  switch (Attr) {
2638
19
  case ImbueAttr::NONE:
2639
19
    return false;
2640
5
  case ImbueAttr::ALWAYS:
2641
5
    Fn->addFnAttr("function-instrument", "xray-always");
2642
5
    break;
2643
2
  case ImbueAttr::ALWAYS_ARG1:
2644
2
    Fn->addFnAttr("function-instrument", "xray-always");
2645
2
    Fn->addFnAttr("xray-log-args", "1");
2646
2
    break;
2647
5
  case ImbueAttr::NEVER:
2648
5
    Fn->addFnAttr("function-instrument", "xray-never");
2649
5
    break;
2650
31
  }
2651
12
  return true;
2652
31
}
2653
2654
bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn,
2655
470
                                           SourceLocation Loc) const {
2656
470
  const auto &ProfileList = getContext().getProfileList();
2657
  // If the profile list is empty, then instrument everything.
2658
470
  if (ProfileList.isEmpty())
2659
460
    return false;
2660
10
  CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr();
2661
  // First, check the function name.
2662
10
  Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind);
2663
10
  if (V.hasValue())
2664
5
    return *V;
2665
  // Next, check the source location.
2666
5
  if (Loc.isValid()) {
2667
5
    Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind);
2668
5
    if (V.hasValue())
2669
2
      return *V;
2670
5
  }
2671
  // If location is unknown, this may be a compiler-generated function. Assume
2672
  // it's located in the main file.
2673
3
  auto &SM = Context.getSourceManager();
2674
3
  if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2675
3
    Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind);
2676
3
    if (V.hasValue())
2677
0
      return *V;
2678
3
  }
2679
3
  return ProfileList.getDefault();
2680
3
}
2681
2682
5.61M
bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2683
  // Never defer when EmitAllDecls is specified.
2684
5.61M
  if (LangOpts.EmitAllDecls)
2685
527
    return true;
2686
2687
5.61M
  if (CodeGenOpts.KeepStaticConsts) {
2688
4
    const auto *VD = dyn_cast<VarDecl>(Global);
2689
4
    if (VD && VD->getType().isConstQualified() &&
2690
4
        VD->getStorageDuration() == SD_Static)
2691
4
      return true;
2692
4
  }
2693
2694
5.61M
  return getContext().DeclMustBeEmitted(Global);
2695
5.61M
}
2696
2697
180k
bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2698
  // In OpenMP 5.0 variables and function may be marked as
2699
  // device_type(host/nohost) and we should not emit them eagerly unless we sure
2700
  // that they must be emitted on the host/device. To be sure we need to have
2701
  // seen a declare target with an explicit mentioning of the function, we know
2702
  // we have if the level of the declare target attribute is -1. Note that we
2703
  // check somewhere else if we should emit this at all.
2704
180k
  if (LangOpts.OpenMP >= 50 && 
!LangOpts.OpenMPSimd18.5k
) {
2705
13.0k
    llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr =
2706
13.0k
        OMPDeclareTargetDeclAttr::getActiveAttr(Global);
2707
13.0k
    if (!ActiveAttr || 
(*ActiveAttr)->getLevel() != (unsigned)-12.21k
)
2708
12.9k
      return false;
2709
13.0k
  }
2710
2711
167k
  if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2712
151k
    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2713
      // Implicit template instantiations may change linkage if they are later
2714
      // explicitly instantiated, so they should not be emitted eagerly.
2715
208
      return false;
2716
151k
  }
2717
167k
  if (const auto *VD = dyn_cast<VarDecl>(Global))
2718
16.5k
    if (Context.getInlineVariableDefinitionKind(VD) ==
2719
16.5k
        ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2720
      // A definition of an inline constexpr static data member may change
2721
      // linkage later if it's redeclared outside the class.
2722
68
      return false;
2723
  // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2724
  // codegen for global variables, because they may be marked as threadprivate.
2725
167k
  if (LangOpts.OpenMP && 
LangOpts.OpenMPUseTLS10.1k
&&
2726
167k
      
getContext().getTargetInfo().isTLSSupported()3.01k
&&
isa<VarDecl>(Global)2.81k
&&
2727
167k
      
!isTypeConstant(Global->getType(), false)1.50k
&&
2728
167k
      
!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)1.50k
)
2729
1.36k
    return false;
2730
2731
166k
  return true;
2732
167k
}
2733
2734
68
ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2735
68
  StringRef Name = getMangledName(GD);
2736
2737
  // The UUID descriptor should be pointer aligned.
2738
68
  CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2739
2740
  // Look for an existing global.
2741
68
  if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2742
36
    return ConstantAddress(GV, Alignment);
2743
2744
32
  ConstantEmitter Emitter(*this);
2745
32
  llvm::Constant *Init;
2746
2747
32
  APValue &V = GD->getAsAPValue();
2748
32
  if (!V.isAbsent()) {
2749
    // If possible, emit the APValue version of the initializer. In particular,
2750
    // this gets the type of the constant right.
2751
16
    Init = Emitter.emitForInitializer(
2752
16
        GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2753
16
  } else {
2754
    // As a fallback, directly construct the constant.
2755
    // FIXME: This may get padding wrong under esoteric struct layout rules.
2756
    // MSVC appears to create a complete type 'struct __s_GUID' that it
2757
    // presumably uses to represent these constants.
2758
16
    MSGuidDecl::Parts Parts = GD->getParts();
2759
16
    llvm::Constant *Fields[4] = {
2760
16
        llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2761
16
        llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2762
16
        llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2763
16
        llvm::ConstantDataArray::getRaw(
2764
16
            StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2765
16
            Int8Ty)};
2766
16
    Init = llvm::ConstantStruct::getAnon(Fields);
2767
16
  }
2768
2769
32
  auto *GV = new llvm::GlobalVariable(
2770
32
      getModule(), Init->getType(),
2771
32
      /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2772
32
  if (supportsCOMDAT())
2773
31
    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2774
32
  setDSOLocal(GV);
2775
2776
32
  llvm::Constant *Addr = GV;
2777
32
  if (!V.isAbsent()) {
2778
16
    Emitter.finalize(GV);
2779
16
  } else {
2780
16
    llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2781
16
    Addr = llvm::ConstantExpr::getBitCast(
2782
16
        GV, Ty->getPointerTo(GV->getAddressSpace()));
2783
16
  }
2784
32
  return ConstantAddress(Addr, Alignment);
2785
68
}
2786
2787
ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject(
2788
7
    const TemplateParamObjectDecl *TPO) {
2789
7
  StringRef Name = getMangledName(TPO);
2790
7
  CharUnits Alignment = getNaturalTypeAlignment(TPO->getType());
2791
2792
7
  if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2793
2
    return ConstantAddress(GV, Alignment);
2794
2795
5
  ConstantEmitter Emitter(*this);
2796
5
  llvm::Constant *Init = Emitter.emitForInitializer(
2797
5
        TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType());
2798
2799
5
  if (!Init) {
2800
0
    ErrorUnsupported(TPO, "template parameter object");
2801
0
    return ConstantAddress::invalid();
2802
0
  }
2803
2804
5
  auto *GV = new llvm::GlobalVariable(
2805
5
      getModule(), Init->getType(),
2806
5
      /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2807
5
  if (supportsCOMDAT())
2808
5
    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2809
5
  Emitter.finalize(GV);
2810
2811
5
  return ConstantAddress(GV, Alignment);
2812
5
}
2813
2814
36
ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2815
36
  const AliasAttr *AA = VD->getAttr<AliasAttr>();
2816
36
  assert(AA && "No alias?");
2817
2818
0
  CharUnits Alignment = getContext().getDeclAlign(VD);
2819
36
  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2820
2821
  // See if there is already something with the target's name in the module.
2822
36
  llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2823
36
  if (Entry) {
2824
6
    unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2825
6
    auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2826
6
    return ConstantAddress(Ptr, Alignment);
2827
6
  }
2828
2829
30
  llvm::Constant *Aliasee;
2830
30
  if (isa<llvm::FunctionType>(DeclTy))
2831
25
    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2832
25
                                      GlobalDecl(cast<FunctionDecl>(VD)),
2833
25
                                      /*ForVTable=*/false);
2834
5
  else
2835
5
    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, 0, nullptr);
2836
2837
30
  auto *F = cast<llvm::GlobalValue>(Aliasee);
2838
30
  F->setLinkage(llvm::Function::ExternalWeakLinkage);
2839
30
  WeakRefReferences.insert(F);
2840
2841
30
  return ConstantAddress(Aliasee, Alignment);
2842
36
}
2843
2844
26.7M
void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2845
26.7M
  const auto *Global = cast<ValueDecl>(GD.getDecl());
2846
2847
  // Weak references don't produce any output by themselves.
2848
26.7M
  if (Global->hasAttr<WeakRefAttr>())
2849
34
    return;
2850
2851
  // If this is an alias definition (which otherwise looks like a declaration)
2852
  // emit it now.
2853
26.7M
  if (Global->hasAttr<AliasAttr>())
2854
137
    return EmitAliasDefinition(GD);
2855
2856
  // IFunc like an alias whose value is resolved at runtime by calling resolver.
2857
26.7M
  if (Global->hasAttr<IFuncAttr>())
2858
14
    return emitIFuncDefinition(GD);
2859
2860
  // If this is a cpu_dispatch multiversion function, emit the resolver.
2861
26.7M
  if (Global->hasAttr<CPUDispatchAttr>())
2862
26
    return emitCPUDispatchDefinition(GD);
2863
2864
  // If this is CUDA, be selective about which declarations we emit.
2865
26.7M
  if (LangOpts.CUDA) {
2866
4.06k
    if (LangOpts.CUDAIsDevice) {
2867
2.94k
      if (!Global->hasAttr<CUDADeviceAttr>() &&
2868
2.94k
          
!Global->hasAttr<CUDAGlobalAttr>()799
&&
2869
2.94k
          
!Global->hasAttr<CUDAConstantAttr>()687
&&
2870
2.94k
          
!Global->hasAttr<CUDASharedAttr>()567
&&
2871
2.94k
          
!Global->getType()->isCUDADeviceBuiltinSurfaceType()524
&&
2872
2.94k
          
!Global->getType()->isCUDADeviceBuiltinTextureType()523
)
2873
521
        return;
2874
2.94k
    } else {
2875
      // We need to emit host-side 'shadows' for all global
2876
      // device-side variables because the CUDA runtime needs their
2877
      // size and host-side address in order to provide access to
2878
      // their device-side incarnations.
2879
2880
      // So device-only functions are the only things we skip.
2881
1.11k
      if (isa<FunctionDecl>(Global) && 
!Global->hasAttr<CUDAHostAttr>()826
&&
2882
1.11k
          
Global->hasAttr<CUDADeviceAttr>()575
)
2883
206
        return;
2884
2885
909
      assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2886
909
             "Expected Variable or Function");
2887
909
    }
2888
4.06k
  }
2889
2890
26.7M
  if (LangOpts.OpenMP) {
2891
    // If this is OpenMP, check if it is legal to emit this global normally.
2892
105k
    if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2893
50.2k
      return;
2894
55.7k
    if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2895
10
      if (MustBeEmitted(Global))
2896
10
        EmitOMPDeclareReduction(DRD);
2897
10
      return;
2898
55.7k
    } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2899
0
      if (MustBeEmitted(Global))
2900
0
        EmitOMPDeclareMapper(DMD);
2901
0
      return;
2902
0
    }
2903
55.7k
  }
2904
2905
  // Ignore declarations, they will be emitted on their first use.
2906
26.6M
  if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2907
    // Forward declarations are emitted lazily on first use.
2908
25.1M
    if (!FD->doesThisDeclarationHaveABody()) {
2909
22.8M
      if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2910
22.8M
        return;
2911
2912
30
      StringRef MangledName = getMangledName(GD);
2913
2914
      // Compute the function info and LLVM type.
2915
30
      const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2916
30
      llvm::Type *Ty = getTypes().GetFunctionType(FI);
2917
2918
30
      GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2919
30
                              /*DontDefer=*/false);
2920
30
      return;
2921
22.8M
    }
2922
25.1M
  } else {
2923
1.49M
    const auto *VD = cast<VarDecl>(Global);
2924
1.49M
    assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2925
1.49M
    if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2926
1.49M
        
!Context.isMSStaticDataMemberInlineDefinition(VD)912k
) {
2927
912k
      if (LangOpts.OpenMP) {
2928
        // Emit declaration of the must-be-emitted declare target variable.
2929
1.02k
        if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2930
1.02k
                OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2931
137
          bool UnifiedMemoryEnabled =
2932
137
              getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2933
137
          if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2934
137
              
!UnifiedMemoryEnabled103
) {
2935
103
            (void)GetAddrOfGlobalVar(VD);
2936
103
          } else {
2937
34
            assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2938
34
                    (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2939
34
                     UnifiedMemoryEnabled)) &&
2940
34
                   "Link clause or to clause with unified memory expected.");
2941
0
            (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2942
34
          }
2943
2944
0
          return;
2945
137
        }
2946
1.02k
      }
2947
      // If this declaration may have caused an inline variable definition to
2948
      // change linkage, make sure that it's emitted.
2949
911k
      if (Context.getInlineVariableDefinitionKind(VD) ==
2950
911k
          ASTContext::InlineVariableDefinitionKind::Strong)
2951
7
        GetAddrOfGlobalVar(VD);
2952
911k
      return;
2953
912k
    }
2954
1.49M
  }
2955
2956
  // Defer code generation to first use when possible, e.g. if this is an inline
2957
  // function. If the global must always be emitted, do it eagerly if possible
2958
  // to benefit from cache locality.
2959
2.89M
  if (MustBeEmitted(Global) && 
MayBeEmittedEagerly(Global)173k
) {
2960
    // Emit the definition if it can't be deferred.
2961
166k
    EmitGlobalDefinition(GD);
2962
166k
    return;
2963
166k
  }
2964
2965
  // If we're deferring emission of a C++ variable with an
2966
  // initializer, remember the order in which it appeared in the file.
2967
2.73M
  if (getLangOpts().CPlusPlus && 
isa<VarDecl>(Global)1.26M
&&
2968
2.73M
      
cast<VarDecl>(Global)->hasInit()564k
) {
2969
17.7k
    DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2970
17.7k
    CXXGlobalInits.push_back(nullptr);
2971
17.7k
  }
2972
2973
2.73M
  StringRef MangledName = getMangledName(GD);
2974
2.73M
  if (GetGlobalValue(MangledName) != nullptr) {
2975
    // The value has already been used and should therefore be emitted.
2976
12.1k
    addDeferredDeclToEmit(GD);
2977
2.71M
  } else if (MustBeEmitted(Global)) {
2978
    // The value must be emitted, but cannot be emitted eagerly.
2979
7.21k
    assert(!MayBeEmittedEagerly(Global));
2980
0
    addDeferredDeclToEmit(GD);
2981
2.71M
  } else {
2982
    // Otherwise, remember that we saw a deferred decl with this name.  The
2983
    // first use of the mangled name will cause it to move into
2984
    // DeferredDeclsToEmit.
2985
2.71M
    DeferredDecls[MangledName] = GD;
2986
2.71M
  }
2987
2.73M
}
2988
2989
// Check if T is a class type with a destructor that's not dllimport.
2990
48
static bool HasNonDllImportDtor(QualType T) {
2991
48
  if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2992
9
    if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2993
9
      if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2994
6
        return true;
2995
2996
42
  return false;
2997
48
}
2998
2999
namespace {
3000
  struct FunctionIsDirectlyRecursive
3001
      : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
3002
    const StringRef Name;
3003
    const Builtin::Context &BI;
3004
    FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
3005
1.43k
        : Name(N), BI(C) {}
3006
3007
1.90k
    bool VisitCallExpr(const CallExpr *E) {
3008
1.90k
      const FunctionDecl *FD = E->getDirectCallee();
3009
1.90k
      if (!FD)
3010
0
        return false;
3011
1.90k
      AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3012
1.90k
      if (Attr && 
Name == Attr->getLabel()2
)
3013
2
        return true;
3014
1.89k
      unsigned BuiltinID = FD->getBuiltinID();
3015
1.89k
      if (!BuiltinID || 
!BI.isLibFunction(BuiltinID)112
)
3016
1.89k
        return false;
3017
4
      StringRef BuiltinName = BI.getName(BuiltinID);
3018
4
      if (BuiltinName.startswith("__builtin_") &&
3019
4
          Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
3020
4
        return true;
3021
4
      }
3022
0
      return false;
3023
4
    }
3024
3025
21.1k
    bool VisitStmt(const Stmt *S) {
3026
21.1k
      for (const Stmt *Child : S->children())
3027
21.5k
        if (Child && 
this->Visit(Child)21.5k
)
3028
12
          return true;
3029
21.1k
      return false;
3030
21.1k
    }
3031
  };
3032
3033
  // Make sure we're not referencing non-imported vars or functions.
3034
  struct DLLImportFunctionVisitor
3035
      : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
3036
    bool SafeToInline = true;
3037
3038
128
    bool shouldVisitImplicitCode() const { return true; }
3039
3040
43
    bool VisitVarDecl(VarDecl *VD) {
3041
43
      if (VD->getTLSKind()) {
3042
        // A thread-local variable cannot be imported.
3043
2
        SafeToInline = false;
3044
2
        return SafeToInline;
3045
2
      }
3046
3047
      // A variable definition might imply a destructor call.
3048
41
      if (VD->isThisDeclarationADefinition())
3049
41
        SafeToInline = !HasNonDllImportDtor(VD->getType());
3050
3051
41
      return SafeToInline;
3052
43
    }
3053
3054
2
    bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
3055
2
      if (const auto *D = E->getTemporary()->getDestructor())
3056
2
        SafeToInline = D->hasAttr<DLLImportAttr>();
3057
2
      return SafeToInline;
3058
2
    }
3059
3060
33
    bool VisitDeclRefExpr(DeclRefExpr *E) {
3061
33
      ValueDecl *VD = E->getDecl();
3062
33
      if (isa<FunctionDecl>(VD))
3063
6
        SafeToInline = VD->hasAttr<DLLImportAttr>();
3064
27
      else if (VarDecl *V = dyn_cast<VarDecl>(VD))
3065
27
        SafeToInline = !V->hasGlobalStorage() || 
V->hasAttr<DLLImportAttr>()17
;
3066
33
      return SafeToInline;
3067
33
    }
3068
3069
11
    bool VisitCXXConstructExpr(CXXConstructExpr *E) {
3070
11
      SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
3071
11
      return SafeToInline;
3072
11
    }
3073
3074
7
    bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3075
7
      CXXMethodDecl *M = E->getMethodDecl();
3076
7
      if (!M) {
3077
        // Call through a pointer to member function. This is safe to inline.
3078
2
        SafeToInline = true;
3079
5
      } else {
3080
5
        SafeToInline = M->hasAttr<DLLImportAttr>();
3081
5
      }
3082
7
      return SafeToInline;
3083
7
    }
3084
3085
4
    bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
3086
4
      SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
3087
4
      return SafeToInline;
3088
4
    }
3089
3090
4
    bool VisitCXXNewExpr(CXXNewExpr *E) {
3091
4
      SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
3092
4
      return SafeToInline;
3093
4
    }
3094
  };
3095
}
3096
3097
// isTriviallyRecursive - Check if this function calls another
3098
// decl that, because of the asm attribute or the other decl being a builtin,
3099
// ends up pointing to itself.
3100
bool
3101
1.69k
CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
3102
1.69k
  StringRef Name;
3103
1.69k
  if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
3104
    // asm labels are a special kind of mangling we have to support.
3105
260
    AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
3106
260
    if (!Attr)
3107
259
      return false;
3108
1
    Name = Attr->getLabel();
3109
1.43k
  } else {
3110
1.43k
    Name = FD->getName();
3111
1.43k
  }
3112
3113
1.43k
  FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
3114
1.43k
  const Stmt *Body = FD->getBody();
3115
1.43k
  return Body ? Walker.Visit(Body) : 
false0
;
3116
1.69k
}
3117
3118
309k
bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
3119
309k
  if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
3120
306k
    return true;
3121
2.55k
  const auto *F = cast<FunctionDecl>(GD.getDecl());
3122
2.55k
  if (CodeGenOpts.OptimizationLevel == 0 && 
!F->hasAttr<AlwaysInlineAttr>()2.24k
)
3123
843
    return false;
3124
3125
1.71k
  if (F->hasAttr<DLLImportAttr>() && 
!F->hasAttr<AlwaysInlineAttr>()223
) {
3126
    // Check whether it would be safe to inline this dllimport function.
3127
205
    DLLImportFunctionVisitor Visitor;
3128
205
    Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
3129
205
    if (!Visitor.SafeToInline)
3130
18
      return false;
3131
3132
187
    if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
3133
      // Implicit destructor invocations aren't captured in the AST, so the
3134
      // check above can't see them. Check for them manually here.
3135
18
      for (const Decl *Member : Dtor->getParent()->decls())
3136
97
        if (isa<FieldDecl>(Member))
3137
3
          if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
3138
2
            return false;
3139
16
      for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
3140
4
        if (HasNonDllImportDtor(B.getType()))
3141
2
          return false;
3142
16
    }
3143
187
  }
3144
3145
  // PR9614. Avoid cases where the source code is lying to us. An available
3146
  // externally function should have an equivalent function somewhere else,
3147
  // but a function that calls itself through asm label/`__builtin_` trickery is
3148
  // clearly not equivalent to the real implementation.
3149
  // This happens in glibc's btowc and in some configure checks.
3150
1.69k
  return !isTriviallyRecursive(F);
3151
1.71k
}
3152
3153
590
bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
3154
590
  return CodeGenOpts.OptimizationLevel > 0;
3155
590
}
3156
3157
void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
3158
110
                                                       llvm::GlobalValue *GV) {
3159
110
  const auto *FD = cast<FunctionDecl>(GD.getDecl());
3160
3161
110
  if (FD->isCPUSpecificMultiVersion()) {
3162
28
    auto *Spec = FD->getAttr<CPUSpecificAttr>();
3163
62
    for (unsigned I = 0; I < Spec->cpus_size(); 
++I34
)
3164
34
      EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
3165
    // Requires multiple emits.
3166
28
  } else
3167
82
    EmitGlobalFunctionDefinition(GD, GV);
3168
110
}
3169
3170
328k
void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
3171
328k
  const auto *D = cast<ValueDecl>(GD.getDecl());
3172
3173
328k
  PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
3174
328k
                                 Context.getSourceManager(),
3175
328k
                                 "Generating code for declaration");
3176
3177
328k
  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3178
    // At -O0, don't generate IR for functions with available_externally
3179
    // linkage.
3180
309k
    if (!shouldEmitFunction(GD))
3181
868
      return;
3182
3183
308k
    llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
3184
3
      std::string Name;
3185
3
      llvm::raw_string_ostream OS(Name);
3186
3
      FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
3187
3
                               /*Qualified=*/true);
3188
3
      return Name;
3189
3
    });
3190
3191
308k
    if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3192
      // Make sure to emit the definition(s) before we emit the thunks.
3193
      // This is necessary for the generation of certain thunks.
3194
109k
      if (isa<CXXConstructorDecl>(Method) || 
isa<CXXDestructorDecl>(Method)69.8k
)
3195
56.7k
        ABI->emitCXXStructor(GD);
3196
52.9k
      else if (FD->isMultiVersion())
3197
24
        EmitMultiVersionFunctionDefinition(GD, GV);
3198
52.9k
      else
3199
52.9k
        EmitGlobalFunctionDefinition(GD, GV);
3200
3201
109k
      if (Method->isVirtual())
3202
4.38k
        getVTables().EmitThunks(GD);
3203
3204
109k
      return;
3205
109k
    }
3206
3207
198k
    if (FD->isMultiVersion())
3208
86
      return EmitMultiVersionFunctionDefinition(GD, GV);
3209
198k
    return EmitGlobalFunctionDefinition(GD, GV);
3210
198k
  }
3211
3212
19.3k
  if (const auto *VD = dyn_cast<VarDecl>(D))
3213
19.3k
    return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
3214
3215
19.3k
  
llvm_unreachable0
("Invalid argument to EmitGlobalDefinition()");
3216
19.3k
}
3217
3218
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3219
                                                      llvm::Function *NewFn);
3220
3221
static unsigned
3222
TargetMVPriority(const TargetInfo &TI,
3223
482
                 const CodeGenFunction::MultiVersionResolverOption &RO) {
3224
482
  unsigned Priority = 0;
3225
482
  for (StringRef Feat : RO.Conditions.Features)
3226
137
    Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3227
3228
482
  if (!RO.Conditions.Architecture.empty())
3229
276
    Priority = std::max(
3230
276
        Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3231
482
  return Priority;
3232
482
}
3233
3234
35.8k
void CodeGenModule::emitMultiVersionFunctions() {
3235
35.8k
  std::vector<GlobalDecl> MVFuncsToEmit;
3236
35.8k
  MultiVersionFuncs.swap(MVFuncsToEmit);
3237
35.8k
  for (GlobalDecl GD : MVFuncsToEmit) {
3238
53
    SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3239
53
    const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3240
53
    getContext().forEachMultiversionedFunctionVersion(
3241
184
        FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3242
184
          GlobalDecl CurGD{
3243
184
              (CurFD->isDefined() ? 
CurFD->getDefinition()152
:
CurFD32
)};
3244
184
          StringRef MangledName = getMangledName(CurGD);
3245
184
          llvm::Constant *Func = GetGlobalValue(MangledName);
3246
184
          if (!Func) {
3247
92
            if (CurFD->isDefined()) {
3248
60
              EmitGlobalFunctionDefinition(CurGD, nullptr);
3249
60
              Func = GetGlobalValue(MangledName);
3250
60
            } else {
3251
32
              const CGFunctionInfo &FI =
3252
32
                  getTypes().arrangeGlobalDeclaration(GD);
3253
32
              llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3254
32
              Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3255
32
                                       /*DontDefer=*/false, ForDefinition);
3256
32
            }
3257
92
            assert(Func && "This should have just been created");
3258
92
          }
3259
3260
0
          const auto *TA = CurFD->getAttr<TargetAttr>();
3261
184
          llvm::SmallVector<StringRef, 8> Feats;
3262
184
          TA->getAddedFeatures(Feats);
3263
3264
184
          Options.emplace_back(cast<llvm::Function>(Func),
3265
184
                               TA->getArchitecture(), Feats);
3266
184
        });
3267
3268
53
    llvm::Function *ResolverFunc;
3269
53
    const TargetInfo &TI = getTarget();
3270
3271
53
    if (TI.supportsIFunc() || 
FD->isTargetMultiVersion()26
) {
3272
53
      ResolverFunc = cast<llvm::Function>(
3273
53
          GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3274
53
      ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3275
53
    } else {
3276
0
      ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3277
0
    }
3278
3279
53
    if (supportsCOMDAT())
3280
53
      ResolverFunc->setComdat(
3281
53
          getModule().getOrInsertComdat(ResolverFunc->getName()));
3282
3283
53
    llvm::stable_sort(
3284
53
        Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3285
241
                       const CodeGenFunction::MultiVersionResolverOption &RHS) {
3286
241
          return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3287
241
        });
3288
53
    CodeGenFunction CGF(*this);
3289
53
    CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3290
53
  }
3291
3292
  // Ensure that any additions to the deferred decls list caused by emitting a
3293
  // variant are emitted.  This can happen when the variant itself is inline and
3294
  // calls a function without linkage.
3295
35.8k
  if (!MVFuncsToEmit.empty())
3296
23
    EmitDeferred();
3297
3298
  // Ensure that any additions to the multiversion funcs list from either the
3299
  // deferred decls or the multiversion functions themselves are emitted.
3300
35.8k
  if (!MultiVersionFuncs.empty())
3301
2
    emitMultiVersionFunctions();
3302
35.8k
}
3303
3304
26
void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3305
26
  const auto *FD = cast<FunctionDecl>(GD.getDecl());
3306
26
  assert(FD && "Not a FunctionDecl?");
3307
0
  const auto *DD = FD->getAttr<CPUDispatchAttr>();
3308
26
  assert(DD && "Not a cpu_dispatch Function?");
3309
0
  llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
3310
3311
26
  if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
3312
8
    const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
3313
8
    DeclTy = getTypes().GetFunctionType(FInfo);
3314
8
  }
3315
3316
26
  StringRef ResolverName = getMangledName(GD);
3317
3318
26
  llvm::Type *ResolverType;
3319
26
  GlobalDecl ResolverGD;
3320
26
  if (getTarget().supportsIFunc())
3321
13
    ResolverType = llvm::FunctionType::get(
3322
13
        llvm::PointerType::get(DeclTy,
3323
13
                               Context.getTargetAddressSpace(FD->getType())),
3324
13
        false);
3325
13
  else {
3326
13
    ResolverType = DeclTy;
3327
13
    ResolverGD = GD;
3328
13
  }
3329
3330
26
  auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3331
26
      ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3332
26
  ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3333
26
  if (supportsCOMDAT())
3334
26
    ResolverFunc->setComdat(
3335
26
        getModule().getOrInsertComdat(ResolverFunc->getName()));
3336
3337
26
  SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3338
26
  const TargetInfo &Target = getTarget();
3339
26
  unsigned Index = 0;
3340
74
  for (const IdentifierInfo *II : DD->cpus()) {
3341
    // Get the name of the target function so we can look it up/create it.
3342
74
    std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3343
74
                              getCPUSpecificMangling(*this, II->getName());
3344
3345
74
    llvm::Constant *Func = GetGlobalValue(MangledName);
3346
3347
74
    if (!Func) {
3348
52
      GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3349
52
      if (ExistingDecl.getDecl() &&
3350
52
          
ExistingDecl.getDecl()->getAsFunction()->isDefined()4
) {
3351
4
        EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3352
4
        Func = GetGlobalValue(MangledName);
3353
48
      } else {
3354
48
        if (!ExistingDecl.getDecl())
3355
48
          ExistingDecl = GD.getWithMultiVersionIndex(Index);
3356
3357
48
      Func = GetOrCreateLLVMFunction(
3358
48
          MangledName, DeclTy, ExistingDecl,
3359
48
          /*ForVTable=*/false, /*DontDefer=*/true,
3360
48
          /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3361
48
      }
3362
52
    }
3363
3364
74
    llvm::SmallVector<StringRef, 32> Features;
3365
74
    Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3366
74
    llvm::transform(Features, Features.begin(),
3367
724
                    [](StringRef Str) { return Str.substr(1); });
3368
74
    Features.erase(std::remove_if(
3369
724
        Features.begin(), Features.end(), [&Target](StringRef Feat) {
3370
724
          return !Target.validateCpuSupports(Feat);
3371
724
        }), Features.end());
3372
74
    Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3373
74
    ++Index;
3374
74
  }
3375
3376
26
  llvm::stable_sort(
3377
26
      Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3378
60
                  const CodeGenFunction::MultiVersionResolverOption &RHS) {
3379
60
        return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3380
60
               CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3381
60
      });
3382
3383
  // If the list contains multiple 'default' versions, such as when it contains
3384
  // 'pentium' and 'generic', don't emit the call to the generic one (since we
3385
  // always run on at least a 'pentium'). We do this by deleting the 'least
3386
  // advanced' (read, lowest mangling letter).
3387
28
  while (Options.size() > 1 &&
3388
28
         CodeGenFunction::GetX86CpuSupportsMask(
3389
28
             (Options.end() - 2)->Conditions.Features) == 0) {
3390
2
    StringRef LHSName = (Options.end() - 2)->Function->getName();
3391
2
    StringRef RHSName = (Options.end() - 1)->Function->getName();
3392
2
    if (LHSName.compare(RHSName) < 0)
3393
2
      Options.erase(Options.end() - 2);
3394
0
    else
3395
0
      Options.erase(Options.end() - 1);
3396
2
  }
3397
3398
26
  CodeGenFunction CGF(*this);
3399
26
  CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3400
3401
26
  if (getTarget().supportsIFunc()) {
3402
13
    std::string AliasName = getMangledNameImpl(
3403
13
        *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3404
13
    llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3405
13
    if (!AliasFunc) {
3406
13
      auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3407
13
          AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3408
13
          /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3409
13
      auto *GA = llvm::GlobalAlias::create(
3410
13
         DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3411
13
      GA->setLinkage(llvm::Function::WeakODRLinkage);
3412
13
      SetCommonAttributes(GD, GA);
3413
13
    }
3414
13
  }
3415
26
}
3416
3417
/// If a dispatcher for the specified mangled name is not in the module, create
3418
/// and return an llvm Function with the specified type.
3419
llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3420
101
    GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3421
101
  std::string MangledName =
3422
101
      getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3423
3424
  // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3425
  // a separate resolver).
3426
101
  std::string ResolverName = MangledName;
3427
101
  if (getTarget().supportsIFunc())
3428
51
    ResolverName += ".ifunc";
3429
50
  else if (FD->isTargetMultiVersion())
3430
32
    ResolverName += ".resolver";
3431
3432
  // If this already exists, just return that one.
3433
101
  if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3434
20
    return ResolverGV;
3435
3436
  // Since this is the first time we've created this IFunc, make sure
3437
  // that we put this multiversioned function into the list to be
3438
  // replaced later if necessary (target multiversioning only).
3439
81
  if (!FD->isCPUDispatchMultiVersion() && 
!FD->isCPUSpecificMultiVersion()59
)
3440
53
    MultiVersionFuncs.push_back(GD);
3441
3442
81
  if (getTarget().supportsIFunc()) {
3443
41
    llvm::Type *ResolverType = llvm::FunctionType::get(
3444
41
        llvm::PointerType::get(
3445
41
            DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3446
41
        false);
3447
41
    llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3448
41
        MangledName + ".resolver", ResolverType, GlobalDecl{},
3449
41
        /*ForVTable=*/false);
3450
41
    llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3451
41
        DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3452
41
    GIF->setName(ResolverName);
3453
41
    SetCommonAttributes(FD, GIF);
3454
3455
41
    return GIF;
3456
41
  }
3457
3458
40
  llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3459
40
      ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3460
40
  assert(isa<llvm::GlobalValue>(Resolver) &&
3461
40
         "Resolver should be created for the first time");
3462
0
  SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3463
40
  return Resolver;
3464
81
}
3465
3466
/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3467
/// module, create and return an llvm Function with the specified type. If there
3468
/// is something in the module with the specified name, return it potentially
3469
/// bitcasted to the right type.
3470
///
3471
/// If D is non-null, it specifies a decl that correspond to this.  This is used
3472
/// to set the attributes on the function when it is first created.
3473
llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3474
    StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3475
    bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3476
799k
    ForDefinition_t IsForDefinition) {
3477
799k
  const Decl *D = GD.getDecl();
3478
3479
  // Any attempts to use a MultiVersion function should result in retrieving
3480
  // the iFunc instead. Name Mangling will handle the rest of the changes.
3481
799k
  if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3482
    // For the device mark the function as one that should be emitted.
3483
750k
    if (getLangOpts().OpenMPIsDevice && 
OpenMPRuntime3.28k
&&
3484
750k
        
!OpenMPRuntime->markAsGlobalTarget(GD)3.28k
&&
FD->isDefined()1.22k
&&
3485
750k
        
!DontDefer958
&&
!IsForDefinition707
) {
3486
360
      if (const FunctionDecl *FDDef = FD->getDefinition()) {
3487
360
        GlobalDecl GDDef;
3488
360
        if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3489
40
          GDDef = GlobalDecl(CD, GD.getCtorType());
3490
320
        else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3491
16
          GDDef = GlobalDecl(DD, GD.getDtorType());
3492
304
        else
3493
304
          GDDef = GlobalDecl(FDDef);
3494
360
        EmitGlobal(GDDef);
3495
360
      }
3496
360
    }
3497
3498
750k
    if (FD->isMultiVersion()) {
3499
361
      if (FD->hasAttr<TargetAttr>())
3500
239
        UpdateMultiVersionNames(GD, FD);
3501
361
      if (!IsForDefinition)
3502
101
        return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3503
361
    }
3504
750k
  }
3505
3506
  // Lookup the entry, lazily creating it if necessary.
3507
799k
  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3508
799k
  if (Entry) {
3509
443k
    if (WeakRefReferences.erase(Entry)) {
3510
7
      const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3511
7
      if (FD && !FD->hasAttr<WeakAttr>())
3512
6
        Entry->setLinkage(llvm::Function::ExternalLinkage);
3513
7
    }
3514
3515
    // Handle dropped DLL attributes.
3516
443k
    if (D && 
!D->hasAttr<DLLImportAttr>()406k
&&
!D->hasAttr<DLLExportAttr>()406k
) {
3517
405k
      Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3518
405k
      setDSOLocal(Entry);
3519
405k
    }
3520
3521
    // If there are two attempts to define the same mangled name, issue an
3522
    // error.
3523
443k
    if (IsForDefinition && 
!Entry->isDeclaration()210k
) {
3524
1.86k
      GlobalDecl OtherGD;
3525
      // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3526
      // to make sure that we issue an error only once.
3527
1.86k
      if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3528
1.86k
          (GD.getCanonicalDecl().getDecl() !=
3529
1.86k
           OtherGD.getCanonicalDecl().getDecl()) &&
3530
1.86k
          
DiagnosedConflictingDefinitions.insert(GD).second3
) {
3531
2
        getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3532
2
            << MangledName;
3533
2
        getDiags().Report(OtherGD.getDecl()->getLocation(),
3534
2
                          diag::note_previous_definition);
3535
2
      }
3536
1.86k
    }
3537
3538
443k
    if ((isa<llvm::Function>(Entry) || 
isa<llvm::GlobalAlias>(Entry)58
) &&
3539
443k
        
(Entry->getValueType() == Ty)443k
) {
3540
443k
      return Entry;
3541
443k
    }
3542
3543
    // Make sure the result is of the correct type.
3544
    // (If function is requested for a definition, we always need to create a new
3545
    // function, not just return a bitcast.)
3546
639
    if (!IsForDefinition)
3547
537
      return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3548
639
  }
3549
3550
  // This function doesn't have a complete type (for example, the return
3551
  // type is an incomplete struct). Use a fake type instead, and make
3552
  // sure not to try to set attributes.
3553
356k
  bool IsIncompleteFunction = false;
3554
3555
356k
  llvm::FunctionType *FTy;
3556
356k
  if (isa<llvm::FunctionType>(Ty)) {
3557
356k
    FTy = cast<llvm::FunctionType>(Ty);
3558
356k
  } else {
3559
37
    FTy = llvm::FunctionType::get(VoidTy, false);
3560
37
    IsIncompleteFunction = true;
3561
37
  }
3562
3563
356k
  llvm::Function *F =
3564
356k
      llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3565
356k
                             Entry ? 
StringRef()102
:
MangledName356k
, &getModule());
3566
3567
  // If we already created a function with the same mangled name (but different
3568
  // type) before, take its name and add it to the list of functions to be
3569
  // replaced with F at the end of CodeGen.
3570
  //
3571
  // This happens if there is a prototype for a function (e.g. "int f()") and
3572
  // then a definition of a different type (e.g. "int f(int x)").
3573
356k
  if (Entry) {
3574
102
    F->takeName(Entry);
3575
3576
    // This might be an implementation of a function without a prototype, in
3577
    // which case, try to do special replacement of calls which match the new
3578
    // prototype.  The really key thing here is that we also potentially drop
3579
    // arguments from the call site so as to make a direct call, which makes the
3580
    // inliner happier and suppresses a number of optimizer warnings (!) about
3581
    // dropping arguments.
3582
102
    if (!Entry->use_empty()) {
3583
102
      ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3584
102
      Entry->removeDeadConstantUsers();
3585
102
    }
3586
3587
102
    llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3588
102
        F, Entry->getValueType()->getPointerTo());
3589
102
    addGlobalValReplacement(Entry, BC);
3590
102
  }
3591
3592
356k
  assert(F->getName() == MangledName && "name was uniqued!");
3593
356k
  if (D)
3594
343k
    SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3595
356k
  if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3596
2.11k
    llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3597
2.11k
    F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3598
2.11k
  }
3599
3600
356k
  if (!DontDefer) {
3601
    // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3602
    // each other bottoming out with the base dtor.  Therefore we emit non-base
3603
    // dtors on usage, even if there is no dtor definition in the TU.
3604
204k
    if (D && 
isa<CXXDestructorDecl>(D)192k
&&
3605
204k
        getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3606
18.5k
                                           GD.getDtorType()))
3607
309
      addDeferredDeclToEmit(GD);
3608
3609
    // This is the first use or definition of a mangled name.  If there is a
3610
    // deferred decl with this name, remember that we need to emit it at the end
3611
    // of the file.
3612
204k
    auto DDI = DeferredDecls.find(MangledName);
3613
204k
    if (DDI != DeferredDecls.end()) {
3614
      // Move the potentially referenced deferred decl to the
3615
      // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3616
      // don't need it anymore).
3617
134k
      addDeferredDeclToEmit(DDI->second);
3618
134k
      DeferredDecls.erase(DDI);
3619
3620
      // Otherwise, there are cases we have to worry about where we're
3621
      // using a declaration for which we must emit a definition but where
3622
      // we might not find a top-level definition:
3623
      //   - member functions defined inline in their classes
3624
      //   - friend functions defined inline in some class
3625
      //   - special member functions with implicit definitions
3626
      // If we ever change our AST traversal to walk into class methods,
3627
      // this will be unnecessary.
3628
      //
3629
      // We also don't emit a definition for a function if it's going to be an
3630
      // entry in a vtable, unless it's already marked as used.
3631
134k
    } else 
if (70.7k
getLangOpts().CPlusPlus70.7k
&&
D61.1k
) {
3632
      // Look for a declaration that's lexically in a record.
3633
96.8k
      for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3634
55.1k
           
FD = FD->getPreviousDecl()45.8k
) {
3635
55.1k
        if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3636
25.4k
          if (FD->doesThisDeclarationHaveABody()) {
3637
9.31k
            addDeferredDeclToEmit(GD.getWithDecl(FD));
3638
9.31k
            break;
3639
9.31k
          }
3640
25.4k
        }
3641
55.1k
      }
3642
51.0k
    }
3643
204k
  }
3644
3645
  // Make sure the result is of the requested type.
3646
356k
  if (!IsIncompleteFunction) {
3647
356k
    assert(F->getFunctionType() == Ty);
3648
0
    return F;
3649
356k
  }
3650
3651
37
  llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3652
37
  return llvm::ConstantExpr::getBitCast(F, PTy);
3653
356k
}
3654
3655
/// GetAddrOfFunction - Return the address of the given function.  If Ty is
3656
/// non-null, then this function will use the specified type if it has to
3657
/// create it (this occurs when we see a definition of the function).
3658
llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3659
                                                 llvm::Type *Ty,
3660
                                                 bool ForVTable,
3661
                                                 bool DontDefer,
3662
546k
                                              ForDefinition_t IsForDefinition) {
3663
546k
  assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
3664
546k
         "consteval function should never be emitted");
3665
  // If there was no specific requested type, just convert it now.
3666
546k
  if (!Ty) {
3667
202k
    const auto *FD = cast<FunctionDecl>(GD.getDecl());
3668
202k
    Ty = getTypes().ConvertType(FD->getType());
3669
202k
  }
3670
3671
  // Devirtualized destructor calls may come through here instead of via
3672
  // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3673
  // of the complete destructor when necessary.
3674
546k
  if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3675
1.94k
    if (getTarget().getCXXABI().isMicrosoft() &&
3676
1.94k
        
GD.getDtorType() == Dtor_Complete259
&&
3677
1.94k
        
DD->getParent()->getNumVBases() == 01
)
3678
1
      GD = GlobalDecl(DD, Dtor_Base);
3679
1.94k
  }
3680
3681
546k
  StringRef MangledName = getMangledName(GD);
3682
546k
  auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3683
546k
                                    /*IsThunk=*/false, llvm::AttributeList(),
3684
546k
                                    IsForDefinition);
3685
  // Returns kernel handle for HIP kernel stub function.
3686
546k
  if (LangOpts.CUDA && 
!LangOpts.CUDAIsDevice1.22k
&&
3687
546k
      
cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()451
) {
3688
109
    auto *Handle = getCUDARuntime().getKernelHandle(
3689
109
        cast<llvm::Function>(F->stripPointerCasts()), GD);
3690
109
    if (IsForDefinition)
3691
63
      return F;
3692
46
    return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo());
3693
109
  }
3694
546k
  return F;
3695
546k
}
3696
3697
static const FunctionDecl *
3698
102
GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3699
102
  TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3700
102
  DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3701
3702
102
  IdentifierInfo &CII = C.Idents.get(Name);
3703
102
  for (const auto *Result : DC->lookup(&CII))
3704
0
    if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3705
0
      return FD;
3706
3707
102
  if (!C.getLangOpts().CPlusPlus)
3708
17
    return nullptr;
3709
3710
  // Demangle the premangled name from getTerminateFn()
3711
85
  IdentifierInfo &CXXII =
3712
85
      (Name == "_ZSt9terminatev" || 
Name == "?terminate@@YAXXZ"80
)
3713
85
          ? 
C.Idents.get("terminate")5
3714
85
          : 
C.Idents.get(Name)80
;
3715
3716
160
  for (const auto &N : {"__cxxabiv1", "std"}) {
3717
160
    IdentifierInfo &NS = C.Idents.get(N);
3718
160
    for (const auto *Result : DC->lookup(&NS)) {
3719
113
      const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3720
113
      if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result))
3721
0
        for (const auto *Result : LSD->lookup(&NS))
3722
0
          if ((ND = dyn_cast<NamespaceDecl>(Result)))
3723
0
            break;
3724
3725
113
      if (ND)
3726
113
        for (const auto *Result : ND->lookup(&CXXII))
3727
14
          if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3728
14
            return FD;
3729
113
    }
3730
160
  }
3731
3732
71
  return nullptr;
3733
85
}
3734
3735
/// CreateRuntimeFunction - Create a new runtime function with the specified
3736
/// type and name.
3737
llvm::FunctionCallee
3738
CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3739
                                     llvm::AttributeList ExtraAttrs, bool Local,
3740
49.4k
                                     bool AssumeConvergent) {
3741
49.4k
  if (AssumeConvergent) {
3742
0
    ExtraAttrs =
3743
0
        ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3744
0
                                llvm::Attribute::Convergent);
3745
0
  }
3746
3747
49.4k
  llvm::Constant *C =
3748
49.4k
      GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3749
49.4k
                              /*DontDefer=*/false, /*IsThunk=*/false,
3750
49.4k
                              ExtraAttrs);
3751
3752
49.4k
  if (auto *F = dyn_cast<llvm::Function>(C)) {
3753
49.4k
    if (F->empty()) {
3754
45.6k
      F->setCallingConv(getRuntimeCC());
3755
3756
      // In Windows Itanium environments, try to mark runtime functions
3757
      // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3758
      // will link their standard library statically or dynamically. Marking
3759
      // functions imported when they are not imported can cause linker errors
3760
      // and warnings.
3761
45.6k
      if (!Local && 
getTriple().isWindowsItaniumEnvironment()34.8k
&&
3762
45.6k
          
!getCodeGenOpts().LTOVisibilityPublicStd170
) {
3763
102
        const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3764
102
        if (!FD || 
FD->hasAttr<DLLImportAttr>()14
) {
3765
93
          F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3766
93
          F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3767
93
        }
3768
102
      }
3769
45.6k
      setDSOLocal(F);
3770
45.6k
    }
3771
49.4k
  }
3772
3773
49.4k
  return {FTy, C};
3774
49.4k
}
3775
3776
/// isTypeConstant - Determine whether an object of this type can be emitted
3777
/// as a constant.
3778
///
3779
/// If ExcludeCtor is true, the duration when the object's constructor runs
3780
/// will not be considered. The caller will need to verify that the object is
3781
/// not written to during its construction.
3782
72.5k
bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3783
72.5k
  if (!Ty.isConstant(Context) && 
!Ty->isReferenceType()69.9k
)
3784
59.9k
    return false;
3785
3786
12.6k
  if (Context.getLangOpts().CPlusPlus) {
3787
11.9k
    if (const CXXRecordDecl *Record
3788
11.9k
          = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3789
422
      return ExcludeCtor && 
!Record->hasMutableFields()232
&&
3790
422
             
Record->hasTrivialDestructor()221
;
3791
11.9k
  }
3792
3793
12.1k
  return true;
3794
12.6k
}
3795
3796
/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3797
/// create and return an llvm GlobalVariable with the specified type and address
3798
/// space. If there is something in the module with the specified name, return
3799
/// it potentially bitcasted to the right type.
3800
///
3801
/// If D is non-null, it specifies a decl that correspond to this.  This is used
3802
/// to set the attributes on the global when it is first created.
3803
///
3804
/// If IsForDefinition is true, it is guaranteed that an actual global with
3805
/// type Ty will be returned, not conversion of a variable with the same
3806
/// mangled name but some other type.
3807
llvm::Constant *
3808
CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty,
3809
                                     unsigned AddrSpace, const VarDecl *D,
3810
140k
                                     ForDefinition_t IsForDefinition) {
3811
  // Lookup the entry, lazily creating it if necessary.
3812
140k
  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3813
140k
  if (Entry) {
3814
103k
    if (WeakRefReferences.erase(Entry)) {
3815
4
      if (D && !D->hasAttr<WeakAttr>())
3816
3
        Entry->setLinkage(llvm::Function::ExternalLinkage);
3817
4
    }
3818
3819
    // Handle dropped DLL attributes.
3820
103k
    if (D && 
!D->hasAttr<DLLImportAttr>()99.7k
&&
!D->hasAttr<DLLExportAttr>()99.6k
)
3821
99.3k
      Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3822
3823
103k
    if (LangOpts.OpenMP && 
!LangOpts.OpenMPSimd32.3k
&&
D16.3k
)
3824
15.1k
      getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3825
3826
103k
    if (Entry->getValueType() == Ty && 
Entry->getAddressSpace() == AddrSpace103k
)
3827
102k
      return Entry;
3828
3829
    // If there are two attempts to define the same mangled name, issue an
3830
    // error.
3831
854
    if (IsForDefinition && 
!Entry->isDeclaration()377
) {
3832
164
      GlobalDecl OtherGD;
3833
164
      const VarDecl *OtherD;
3834
3835
      // Check that D is not yet in DiagnosedConflictingDefinitions is required
3836
      // to make sure that we issue an error only once.
3837
164
      if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3838
164
          (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3839
164
          
(OtherD = dyn_cast<VarDecl>(OtherGD.getDecl()))2
&&
3840
164
          
OtherD->hasInit()2
&&
3841
164
          
DiagnosedConflictingDefinitions.insert(D).second1
) {
3842
1
        getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3843
1
            << MangledName;
3844
1
        getDiags().Report(OtherGD.getDecl()->getLocation(),
3845
1
                          diag::note_previous_definition);
3846
1
      }
3847
164
    }
3848
3849
    // Make sure the result is of the correct type.
3850
854
    if (Entry->getType()->getAddressSpace() != AddrSpace) {
3851
766
      return llvm::ConstantExpr::getAddrSpaceCast(Entry,
3852
766
                                                  Ty->getPointerTo(AddrSpace));
3853
766
    }
3854
3855
    // (If global is requested for a definition, we always need to create a new
3856
    // global, not just return a bitcast.)
3857
88
    if (!IsForDefinition)
3858
43
      return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(AddrSpace));
3859
88
  }
3860
3861
36.8k
  auto DAddrSpace = GetGlobalVarAddressSpace(D);
3862
36.8k
  auto TargetAddrSpace = getContext().getTargetAddressSpace(DAddrSpace);
3863
3864
36.8k
  auto *GV = new llvm::GlobalVariable(
3865
36.8k
      getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr,
3866
36.8k
      MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal,
3867
36.8k
      TargetAddrSpace);
3868
3869
  // If we already created a global with the same mangled name (but different
3870
  // type) before, take its name and remove it from its parent.
3871
36.8k
  if (Entry) {
3872
45
    GV->takeName(Entry);
3873
3874
45
    if (!Entry->use_empty()) {
3875
43
      llvm::Constant *NewPtrForOldDecl =
3876
43
          llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3877
43
      Entry->replaceAllUsesWith(NewPtrForOldDecl);
3878
43
    }
3879
3880
45
    Entry->eraseFromParent();
3881
45
  }
3882
3883
  // This is the first use or definition of a mangled name.  If there is a
3884
  // deferred decl with this name, remember that we need to emit it at the end
3885
  // of the file.
3886
36.8k
  auto DDI = DeferredDecls.find(MangledName);
3887
36.8k
  if (DDI != DeferredDecls.end()) {
3888
    // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3889
    // list, and remove it from DeferredDecls (since we don't need it anymore).
3890
1.22k
    addDeferredDeclToEmit(DDI->second);
3891
1.22k
    DeferredDecls.erase(DDI);
3892
1.22k
  }
3893
3894
  // Handle things which are present even on external declarations.
3895
36.8k
  if (D) {
3896
34.9k
    if (LangOpts.OpenMP && 
!LangOpts.OpenMPSimd8.08k
)
3897
3.86k
      getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3898
3899
    // FIXME: This code is overly simple and should be merged with other global
3900
    // handling.
3901
34.9k
    GV->setConstant(isTypeConstant(D->getType(), false));
3902
3903
34.9k
    GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3904
3905
34.9k
    setLinkageForGV(GV, D);
3906
3907
34.9k
    if (D->getTLSKind()) {
3908
400
      if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3909
315
        CXXThreadLocals.push_back(D);
3910
400
      setTLSMode(GV, *D);
3911
400
    }
3912
3913
34.9k
    setGVProperties(GV, D);
3914
3915
    // If required by the ABI, treat declarations of static data members with
3916
    // inline initializers as definitions.
3917
34.9k
    if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3918
98
      EmitGlobalVarDefinition(D);
3919
98
    }
3920
3921
    // Emit section information for extern variables.
3922
34.9k
    if (D->hasExternalStorage()) {
3923
2.09k
      if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3924
3
        GV->setSection(SA->getName());
3925
2.09k
    }
3926
3927
    // Handle XCore specific ABI requirements.
3928
34.9k
    if (getTriple().getArch() == llvm::Triple::xcore &&
3929
34.9k
        
D->getLanguageLinkage() == CLanguageLinkage22
&&
3930
34.9k
        
D->getType().isConstant(Context)18
&&
3931
34.9k
        
isExternallyVisible(D->getLinkageAndVisibility().getLinkage())4
)
3932
4
      GV->setSection(".cp.rodata");
3933
3934
    // Check if we a have a const declaration with an initializer, we may be
3935
    // able to emit it as available_externally to expose it's value to the
3936
    // optimizer.
3937
34.9k
    if (Context.getLangOpts().CPlusPlus && 
GV->hasExternalLinkage()27.0k
&&
3938
34.9k
        
D->getType().isConstQualified()26.9k
&&
!GV->hasInitializer()691
&&
3939
34.9k
        
!D->hasDefinition()691
&&
D->hasInit()154
&&
!D->hasAttr<DLLImportAttr>()61
) {
3940
34
      const auto *Record =
3941
34
          Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3942
34
      bool HasMutableFields = Record && 
Record->hasMutableFields()8
;
3943
34
      if (!HasMutableFields) {
3944
32
        const VarDecl *InitDecl;
3945
32
        const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3946
32
        if (InitExpr) {
3947
32
          ConstantEmitter emitter(*this);
3948
32
          llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3949
32
          if (Init) {
3950
32
            auto *InitType = Init->getType();
3951
32
            if (GV->getValueType() != InitType) {
3952
              // The type of the initializer does not match the definition.
3953
              // This happens when an initializer has a different type from
3954
              // the type of the global (because of padding at the end of a
3955
              // structure for instance).
3956
2
              GV->setName(StringRef());
3957
              // Make a new global with the correct type, this is now guaranteed
3958
              // to work.
3959
2
              auto *NewGV = cast<llvm::GlobalVariable>(
3960
2
                  GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3961
2
                      ->stripPointerCasts());
3962
3963
              // Erase the old global, since it is no longer used.
3964
2
              GV->eraseFromParent();
3965
2
              GV = NewGV;
3966
30
            } else {
3967
30
              GV->setInitializer(Init);
3968
30
              GV->setConstant(true);
3969
30
              GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3970
30
            }
3971
32
            emitter.finalize(GV);
3972
32
          }
3973
32
        }
3974
32
      }
3975
34
    }
3976
34.9k
  }
3977
3978
36.8k
  if (GV->isDeclaration()) {
3979
36.7k
    getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3980
    // External HIP managed variables needed to be recorded for transformation
3981
    // in both device and host compilations.
3982
36.7k
    if (getLangOpts().CUDA && 
D541
&&
D->hasAttr<HIPManagedAttr>()536
&&
3983
36.7k
        
D->hasExternalStorage()34
)
3984
8
      getCUDARuntime().handleVarRegistration(D, *GV);
3985
36.7k
  }
3986
3987
36.8k
  LangAS ExpectedAS =
3988
36.8k
      D ? 
D->getType().getAddressSpace()34.9k
3989
36.8k
        : 
(1.96k
LangOpts.OpenCL1.96k
?
LangAS::opencl_global3
:
LangAS::Default1.96k
);
3990
36.8k
  assert(getContext().getTargetAddressSpace(ExpectedAS) == AddrSpace);
3991
36.8k
  if (DAddrSpace != ExpectedAS) {
3992
341
    return getTargetCodeGenInfo().performAddrSpaceCast(
3993
341
        *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(AddrSpace));
3994
341
  }
3995
3996
36.5k
  return GV;
3997
36.8k
}
3998
3999
llvm::Constant *
4000
178k
CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
4001
178k
  const Decl *D = GD.getDecl();
4002
4003
178k
  if (isa<CXXConstructorDecl>(D) || 
isa<CXXDestructorDecl>(D)139k
)
4004
55.9k
    return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
4005
55.9k
                                /*DontDefer=*/false, IsForDefinition);
4006
4007
122k
  if (isa<CXXMethodDecl>(D)) {
4008
52.1k
    auto FInfo =
4009
52.1k
        &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
4010
52.1k
    auto Ty = getTypes().GetFunctionType(*FInfo);
4011
52.1k
    return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4012
52.1k
                             IsForDefinition);
4013
52.1k
  }
4014
4015
70.0k
  if (isa<FunctionDecl>(D)) {
4016
65.4k
    const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4017
65.4k
    llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4018
65.4k
    return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
4019
65.4k
                             IsForDefinition);
4020
65.4k
  }
4021
4022
4.59k
  return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
4023
70.0k
}
4024
4025
llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
4026
    StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
4027
6.31k
    unsigned Alignment) {
4028
6.31k
  llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
4029
6.31k
  llvm::GlobalVariable *OldGV = nullptr;
4030
4031
6.31k
  if (GV) {
4032
    // Check if the variable has the right type.
4033
428
    if (GV->getValueType() == Ty)
4034
428
      return GV;
4035
4036
    // Because C++ name mangling, the only way we can end up with an already
4037
    // existing global with the same name is if it has been declared extern "C".
4038
0
    assert(GV->isDeclaration() && "Declaration has wrong type!");
4039
0
    OldGV = GV;
4040
0
  }
4041
4042
  // Create a new variable.
4043
5.88k
  GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
4044
5.88k
                                Linkage, nullptr, Name);
4045
4046
5.88k
  if (OldGV) {
4047
    // Replace occurrences of the old variable if needed.
4048
0
    GV->takeName(OldGV);
4049
4050
0
    if (!OldGV->use_empty()) {
4051
0
      llvm::Constant *NewPtrForOldDecl =
4052
0
      llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
4053
0
      OldGV->replaceAllUsesWith(NewPtrForOldDecl);
4054
0
    }
4055
4056
0
    OldGV->eraseFromParent();
4057
0
  }
4058
4059
5.88k
  if (supportsCOMDAT() && 
GV->isWeakForLinker()2.53k
&&
4060
5.88k
      
!GV->hasAvailableExternallyLinkage()1.25k
)
4061
1.25k
    GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4062
4063
5.88k
  GV->setAlignment(llvm::MaybeAlign(Alignment));
4064
4065
5.88k
  return GV;
4066
6.31k
}
4067
4068
/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
4069
/// given global variable.  If Ty is non-null and if the global doesn't exist,
4070
/// then it will be created with the specified type instead of whatever the
4071
/// normal requested type would be. If IsForDefinition is true, it is guaranteed
4072
/// that an actual global with type Ty will be returned, not conversion of a
4073
/// variable with the same mangled name but some other type.
4074
llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
4075
                                                  llvm::Type *Ty,
4076
134k
                                           ForDefinition_t IsForDefinition) {
4077
134k
  assert(D->hasGlobalStorage() && "Not a global variable");
4078
0
  QualType ASTTy = D->getType();
4079
134k
  if (!Ty)
4080
110k
    Ty = getTypes().ConvertTypeForMem(ASTTy);
4081
4082
134k
  StringRef MangledName = getMangledName(D);
4083
134k
  return GetOrCreateLLVMGlobal(MangledName, Ty,
4084
134k
                               getContext().getTargetAddressSpace(ASTTy), D,
4085
134k
                               IsForDefinition);
4086
134k
}
4087
4088
/// CreateRuntimeVariable - Create a new runtime global variable with the
4089
/// specified type and name.
4090
llvm::Constant *
4091
CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
4092
5.38k
                                     StringRef Name) {
4093
5.38k
  auto AddrSpace =
4094
5.38k
      getContext().getLangOpts().OpenCL
4095
5.38k
          ? 
getContext().getTargetAddressSpace(LangAS::opencl_global)7
4096
5.38k
          : 
05.37k
;
4097
5.38k
  auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr);
4098
5.38k
  setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
4099
5.38k
  return Ret;
4100
5.38k
}
4101
4102
4.73k
void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
4103
4.73k
  assert(!D->getInit() && "Cannot emit definite definitions here!");
4104
4105
0
  StringRef MangledName = getMangledName(D);
4106
4.73k
  llvm::GlobalValue *GV = GetGlobalValue(MangledName);
4107
4108
  // We already have a definition, not declaration, with the same mangled name.
4109
  // Emitting of declaration is not required (and actually overwrites emitted
4110
  // definition).
4111
4.73k
  if (GV && 
!GV->isDeclaration()3.12k
)
4112
1
    return;
4113
4114
  // If we have not seen a reference to this variable yet, place it into the
4115
  // deferred declarations table to be emitted if needed later.
4116
4.73k
  if (!MustBeEmitted(D) && 
!GV113
) {
4117
68
      DeferredDecls[MangledName] = D;
4118
68
      return;
4119
68
  }
4120
4121
  // The tentative definition is the only definition.
4122
4.66k
  EmitGlobalVarDefinition(D);
4123
4.66k
}
4124
4125
7
void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
4126
7
  EmitExternalVarDeclaration(D);
4127
7
}
4128
4129
349
CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
4130
349
  return Context.toCharUnitsFromBits(
4131
349
      getDataLayout().getTypeStoreSizeInBits(Ty));
4132
349
}
4133
4134
74.6k
LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
4135
74.6k
  LangAS AddrSpace = LangAS::Default;
4136
74.6k
  if (LangOpts.OpenCL) {
4137
823
    AddrSpace = D ? 
D->getType().getAddressSpace()820
:
LangAS::opencl_global3
;
4138
823
    assert(AddrSpace == LangAS::opencl_global ||
4139
823
           AddrSpace == LangAS::opencl_global_device ||
4140
823
           AddrSpace == LangAS::opencl_global_host ||
4141
823
           AddrSpace == LangAS::opencl_constant ||
4142
823
           AddrSpace == LangAS::opencl_local ||
4143
823
           AddrSpace >= LangAS::FirstTargetAddressSpace);
4144
0
    return AddrSpace;
4145
823
  }
4146
4147
73.8k
  if (LangOpts.SYCLIsDevice &&
4148
73.8k
      
(1
!D1
||
D->getType().getAddressSpace() == LangAS::Default1
))
4149
1
    return LangAS::sycl_global;
4150
4151
73.8k
  if (LangOpts.CUDA && 
LangOpts.CUDAIsDevice1.07k
) {
4152
597
    if (D && D->hasAttr<CUDAConstantAttr>())
4153
197
      return LangAS::cuda_constant;
4154
400
    else if (D && D->hasAttr<CUDASharedAttr>())
4155
113
      return LangAS::cuda_shared;
4156
287
    else if (D && D->hasAttr<CUDADeviceAttr>())
4157
263
      return LangAS::cuda_device;
4158
24
    else if (D && D->getType().isConstQualified())
4159
16
      return LangAS::cuda_constant;
4160
8
    else
4161
8
      return LangAS::cuda_device;
4162
597
  }
4163
4164
73.2k
  if (LangOpts.OpenMP) {
4165
18.3k
    LangAS AS;
4166
18.3k
    if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
4167
135
      return AS;
4168
18.3k
  }
4169
73.0k
  return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
4170
73.2k
}
4171
4172
144k
LangAS CodeGenModule::GetGlobalConstantAddressSpace() const {
4173
  // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
4174
144k
  if (LangOpts.OpenCL)
4175
29
    return LangAS::opencl_constant;
4176
144k
  if (LangOpts.SYCLIsDevice)
4177
8
    return LangAS::sycl_global;
4178
144k
  if (auto AS = getTarget().getConstantAddressSpace())
4179
144k
    return AS.getValue();
4180
0
  return LangAS::Default;
4181
144k
}
4182
4183
// In address space agnostic languages, string literals are in default address
4184
// space in AST. However, certain targets (e.g. amdgcn) request them to be
4185
// emitted in constant address space in LLVM IR. To be consistent with other
4186
// parts of AST, string literal global variables in constant address space
4187
// need to be casted to default address space before being put into address
4188
// map and referenced by other part of CodeGen.
4189
// In OpenCL, string literals are in constant address space in AST, therefore
4190
// they should not be casted to default address space.
4191
static llvm::Constant *
4192
castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
4193
85.4k
                                       llvm::GlobalVariable *GV) {
4194
85.4k
  llvm::Constant *Cast = GV;
4195
85.4k
  if (!CGM.getLangOpts().OpenCL) {
4196
85.3k
    auto AS = CGM.GetGlobalConstantAddressSpace();
4197
85.3k
    if (AS != LangAS::Default)
4198
60
      Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
4199
60
          CGM, GV, AS, LangAS::Default,
4200
60
          GV->getValueType()->getPointerTo(
4201
60
              CGM.getContext().getTargetAddressSpace(LangAS::Default)));
4202
85.3k
  }
4203
85.4k
  return Cast;
4204
85.4k
}
4205
4206
template<typename SomeDecl>
4207
void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
4208
275k
                                               llvm::GlobalValue *GV) {
4209
275k
  if (!getLangOpts().CPlusPlus)
4210
129k
    return;
4211
4212
  // Must have 'used' attribute, or else inline assembly can't rely on
4213
  // the name existing.
4214
145k
  if (!D->template hasAttr<UsedAttr>())
4215
144k
    return;
4216
4217
  // Must have internal linkage and an ordinary name.
4218
941
  if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4219
175
    return;
4220
4221
  // Must be in an extern "C" context. Entities declared directly within
4222
  // a record are not extern "C" even if the record is in such a context.
4223
766
  const SomeDecl *First = D->getFirstDecl();
4224
766
  if (First->getDeclContext()->isRecord() || 
!First->isInExternCContext()28
)
4225
758
    return;
4226
4227
  // OK, this is an internal linkage entity inside an extern "C" linkage
4228
  // specification. Make a note of that so we can give it the "expected"
4229
  // mangled name if nothing else is using that name.
4230
8
  std::pair<StaticExternCMap::iterator, bool> R =
4231
8
      StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4232
4233
  // If we have multiple internal linkage entities with the same name
4234
  // in extern "C" regions, none of them gets that name.
4235
8
  if (!R.second)
4236
2
    R.first->second = nullptr;
4237
8
}
void clang::CodeGen::CodeGenModule::MaybeHandleStaticInExternC<clang::VarDecl>(clang::VarDecl const*, llvm::GlobalValue*)
Line
Count
Source
4208
24.1k
                                               llvm::GlobalValue *GV) {
4209
24.1k
  if (!getLangOpts().CPlusPlus)
4210
7.37k
    return;
4211
4212
  // Must have 'used' attribute, or else inline assembly can't rely on
4213
  // the name existing.
4214
16.7k
  if (!D->template hasAttr<UsedAttr>())
4215
16.7k
    return;
4216
4217
  // Must have internal linkage and an ordinary name.
4218
23
  if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4219
5
    return;
4220
4221
  // Must be in an extern "C" context. Entities declared directly within
4222
  // a record are not extern "C" even if the record is in such a context.
4223
18
  const SomeDecl *First = D->getFirstDecl();
4224
18
  if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4225
15
    return;
4226
4227
  // OK, this is an internal linkage entity inside an extern "C" linkage
4228
  // specification. Make a note of that so we can give it the "expected"
4229
  // mangled name if nothing else is using that name.
4230
3
  std::pair<StaticExternCMap::iterator, bool> R =
4231
3
      StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4232
4233
  // If we have multiple internal linkage entities with the same name
4234
  // in extern "C" regions, none of them gets that name.
4235
3
  if (!R.second)
4236
1
    R.first->second = nullptr;
4237
3
}
void clang::CodeGen::CodeGenModule::MaybeHandleStaticInExternC<clang::FunctionDecl>(clang::FunctionDecl const*, llvm::GlobalValue*)
Line
Count
Source
4208
251k
                                               llvm::GlobalValue *GV) {
4209
251k
  if (!getLangOpts().CPlusPlus)
4210
122k
    return;
4211
4212
  // Must have 'used' attribute, or else inline assembly can't rely on
4213
  // the name existing.
4214
129k
  if (!D->template hasAttr<UsedAttr>())
4215
128k
    return;
4216
4217
  // Must have internal linkage and an ordinary name.
4218
918
  if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
4219
170
    return;
4220
4221
  // Must be in an extern "C" context. Entities declared directly within
4222
  // a record are not extern "C" even if the record is in such a context.
4223
748
  const SomeDecl *First = D->getFirstDecl();
4224
748
  if (First->getDeclContext()->isRecord() || 
!First->isInExternCContext()10
)
4225
743
    return;
4226
4227
  // OK, this is an internal linkage entity inside an extern "C" linkage
4228
  // specification. Make a note of that so we can give it the "expected"
4229
  // mangled name if nothing else is using that name.
4230
5
  std::pair<StaticExternCMap::iterator, bool> R =
4231
5
      StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4232
4233
  // If we have multiple internal linkage entities with the same name
4234
  // in extern "C" regions, none of them gets that name.
4235
5
  if (!R.second)
4236
1
    R.first->second = nullptr;
4237
5
}
4238
4239
331k
static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4240
331k
  if (!CGM.supportsCOMDAT())
4241
158k
    return false;
4242
4243
  // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
4244
  // them being "merged" by the COMDAT Folding linker optimization.
4245
173k
  if (D.hasAttr<CUDAGlobalAttr>())
4246
169
    return false;
4247
4248
173k
  if (D.hasAttr<SelectAnyAttr>())
4249
20
    return true;
4250
4251
173k
  GVALinkage Linkage;
4252
173k
  if (auto *VD = dyn_cast<VarDecl>(&D))
4253
15.7k
    Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4254
157k
  else
4255
157k
    Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4256
4257
173k
  switch (Linkage) {
4258
23.1k
  case GVA_Internal:
4259
24.8k
  case GVA_AvailableExternally:
4260
145k
  case GVA_StrongExternal:
4261
145k
    return false;
4262
25.4k
  case GVA_DiscardableODR:
4263
27.9k
  case GVA_StrongODR:
4264
27.9k
    return true;
4265
173k
  }
4266
173k
  
llvm_unreachable0
("No such linkage");
4267
173k
}
4268
4269
void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4270
331k
                                          llvm::GlobalObject &GO) {
4271
331k
  if (!shouldBeInCOMDAT(*this, D))
4272
303k
    return;
4273
27.9k
  GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4274
27.9k
}
4275
4276
/// Pass IsTentative as true if you want to create a tentative definition.
4277
void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4278
24.1k
                                            bool IsTentative) {
4279
  // OpenCL global variables of sampler type are translated to function calls,
4280
  // therefore no need to be translated.
4281
24.1k
  QualType ASTTy = D->getType();
4282
24.1k
  if (getLangOpts().OpenCL && 
ASTTy->isSamplerT()302
)
4283
7
    return;
4284
4285
  // If this is OpenMP device, check if it is legal to emit this global
4286
  // normally.
4287
24.1k
  if (LangOpts.OpenMPIsDevice && 
OpenMPRuntime141
&&
4288
24.1k
      
OpenMPRuntime->emitTargetGlobalVariable(D)141
)
4289
2
    return;
4290
4291
24.1k
  llvm::TrackingVH<llvm::Constant> Init;
4292
24.1k
  bool NeedsGlobalCtor = false;
4293
24.1k
  bool NeedsGlobalDtor =
4294
24.1k
      D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4295
4296
24.1k
  const VarDecl *InitDecl;
4297
24.1k
  const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4298
4299
24.1k
  Optional<ConstantEmitter> emitter;
4300
4301
  // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4302
  // as part of their declaration."  Sema has already checked for
4303
  // error cases, so we just need to set Init to UndefValue.
4304
24.1k
  bool IsCUDASharedVar =
4305
24.1k
      getLangOpts().CUDAIsDevice && 
D->hasAttr<CUDASharedAttr>()263
;
4306
  // Shadows of initialized device-side global variables are also left
4307
  // undefined.
4308
  // Managed Variables should be initialized on both host side and device side.
4309
24.1k
  bool IsCUDAShadowVar =
4310
24.1k
      !getLangOpts().CUDAIsDevice && 
!D->hasAttr<HIPManagedAttr>()23.8k
&&
4311
24.1k
      
(23.8k
D->hasAttr<CUDAConstantAttr>()23.8k
||
D->hasAttr<CUDADeviceAttr>()23.7k
||
4312
23.8k
       
D->hasAttr<CUDASharedAttr>()23.7k
);
4313
24.1k
  bool IsCUDADeviceShadowVar =
4314
24.1k
      getLangOpts().CUDAIsDevice && 
!D->hasAttr<HIPManagedAttr>()263
&&
4315
24.1k
      
(249
D->getType()->isCUDADeviceBuiltinSurfaceType()249
||
4316
249
       
D->getType()->isCUDADeviceBuiltinTextureType()248
);
4317
24.1k
  if (getLangOpts().CUDA &&
4318
24.1k
      
(471
IsCUDASharedVar471
||
IsCUDAShadowVar427
||
IsCUDADeviceShadowVar272
))
4319
202
    Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4320
23.9k
  else if (D->hasAttr<LoaderUninitializedAttr>())
4321
45
    Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy));
4322
23.8k
  else if (!InitExpr) {
4323
    // This is a tentative definition; tentative definitions are
4324
    // implicitly initialized with { 0 }.
4325
    //
4326
    // Note that tentative definitions are only emitted at the end of
4327
    // a translation unit, so they should never have incomplete
4328
    // type. In addition, EmitTentativeDefinition makes sure that we
4329
    // never attempt to emit a tentative definition if a real one
4330
    // exists. A use may still exists, however, so we still may need
4331
    // to do a RAUW.
4332
7.60k
    assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4333
0
    Init = EmitNullConstant(D->getType());
4334
16.2k
  } else {
4335
16.2k
    initializedGlobalDecl = GlobalDecl(D);
4336
16.2k
    emitter.emplace(*this);
4337
16.2k
    llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl);
4338
16.2k
    if (!Initializer) {
4339
5.41k
      QualType T = InitExpr->getType();
4340
5.41k
      if (D->getType()->isReferenceType())
4341
84
        T = D->getType();
4342
4343
5.41k
      if (getLangOpts().CPlusPlus) {
4344
5.41k
        Init = EmitNullConstant(T);
4345
5.41k
        NeedsGlobalCtor = true;
4346
5.41k
      } else {
4347
0
        ErrorUnsupported(D, "static initializer");
4348
0
        Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4349
0
      }
4350
10.8k
    } else {
4351
10.8k
      Init = Initializer;
4352
      // We don't need an initializer, so remove the entry for the delayed
4353
      // initializer position (just in case this entry was delayed) if we
4354
      // also don't need to register a destructor.
4355
10.8k
      if (getLangOpts().CPlusPlus && 
!NeedsGlobalDtor8.15k
)
4356
7.68k
        DelayedCXXInitPosition.erase(D);
4357
10.8k
    }
4358
16.2k
  }
4359
4360
0
  llvm::Type* InitType = Init->getType();
4361
24.1k
  llvm::Constant *Entry =
4362
24.1k
      GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4363
4364
  // Strip off pointer casts if we got them.
4365
24.1k
  Entry = Entry->stripPointerCasts();
4366
4367
  // Entry is now either a Function or GlobalVariable.
4368
24.1k
  auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4369
4370
  // We have a definition after a declaration with the wrong type.
4371
  // We must make a new GlobalVariable* and update everything that used OldGV
4372
  // (a declaration or tentative definition) with the new GlobalVariable*
4373
  // (which will be a definition).
4374
  //
4375
  // This happens if there is a prototype for a global (e.g.
4376
  // "extern int x[];") and then a definition of a different type (e.g.
4377
  // "int x[10];"). This also happens when an initializer has a different type
4378
  // from the type of the global (this happens with unions).
4379
24.1k
  if (!GV || GV->getValueType() != InitType ||
4380
24.1k
      GV->getType()->getAddressSpace() !=
4381
24.1k
          getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4382
4383
    // Move the old entry aside so that we'll create a new one.
4384
1
    Entry->setName(StringRef());
4385
4386
    // Make a new global with the correct type, this is now guaranteed to work.
4387
1
    GV = cast<llvm::GlobalVariable>(
4388
1
        GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4389
1
            ->stripPointerCasts());
4390
4391
    // Replace all uses of the old global with the new global
4392
1
    llvm::Constant *NewPtrForOldDecl =
4393
1
        llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV,
4394
1
                                                             Entry->getType());
4395
1
    Entry->replaceAllUsesWith(NewPtrForOldDecl);
4396
4397
    // Erase the old global, since it is no longer used.
4398
1
    cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4399
1
  }
4400
4401
24.1k
  MaybeHandleStaticInExternC(D, GV);
4402
4403
24.1k
  if (D->hasAttr<AnnotateAttr>())
4404
5
    AddGlobalAnnotations(D, GV);
4405
4406
  // Set the llvm linkage type as appropriate.
4407
24.1k
  llvm::GlobalValue::LinkageTypes Linkage =
4408
24.1k
      getLLVMLinkageVarDefinition(D, GV->isConstant());
4409
4410
  // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4411
  // the device. [...]"
4412
  // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4413
  // __device__, declares a variable that: [...]
4414
  // Is accessible from all the threads within the grid and from the host
4415
  // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4416
  // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4417
24.1k
  if (GV && LangOpts.CUDA) {
4418
471
    if (LangOpts.CUDAIsDevice) {
4419
263
      if (Linkage != llvm::GlobalValue::InternalLinkage &&
4420
263
          
(228
D->hasAttr<CUDADeviceAttr>()228
||
D->hasAttr<CUDAConstantAttr>()114
))
4421
182
        GV->setExternallyInitialized(true);
4422
263
    } else {
4423
208
      getCUDARuntime().internalizeDeviceSideVar(D, Linkage);
4424
208
    }
4425
471
    getCUDARuntime().handleVarRegistration(D, *GV);
4426
471
  }
4427
4428
24.1k
  GV->setInitializer(Init);
4429
24.1k
  if (emitter)
4430
16.2k
    emitter->finalize(GV);
4431
4432
  // If it is safe to mark the global 'constant', do so now.
4433
24.1k
  GV->setConstant(!NeedsGlobalCtor && 
!NeedsGlobalDtor18.6k
&&
4434
24.1k
                  
isTypeConstant(D->getType(), true)18.2k
);
4435
4436
  // If it is in a read-only section, mark it 'constant'.
4437
24.1k
  if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4438
59
    const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4439
59
    if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4440
8
      GV->setConstant(true);
4441
59
  }
4442
4443
24.1k
  GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4444
4445
  // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4446
  // function is only defined alongside the variable, not also alongside
4447
  // callers. Normally, all accesses to a thread_local go through the
4448
  // thread-wrapper in order to ensure initialization has occurred, underlying
4449
  // variable will never be used other than the thread-wrapper, so it can be
4450
  // converted to internal linkage.
4451
  //
4452
  // However, if the variable has the 'constinit' attribute, it _can_ be
4453
  // referenced directly, without calling the thread-wrapper, so the linkage
4454
  // must not be changed.
4455
  //
4456
  // Additionally, if the variable isn't plain external linkage, e.g. if it's
4457
  // weak or linkonce, the de-duplication semantics are important to preserve,
4458
  // so we don't change the linkage.
4459
24.1k
  if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4460
24.1k
      
Linkage == llvm::GlobalValue::ExternalLinkage249
&&
4461
24.1k
      
Context.getTargetInfo().getTriple().isOSDarwin()109
&&
4462
24.1k
      
!D->hasAttr<ConstInitAttr>()31
)
4463
29
    Linkage = llvm::GlobalValue::InternalLinkage;
4464
4465
24.1k
  GV->setLinkage(Linkage);
4466
24.1k
  if (D->hasAttr<DLLImportAttr>())
4467
50
    GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4468
24.0k
  else if (D->hasAttr<DLLExportAttr>())
4469
509
    GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4470
23.5k
  else
4471
23.5k
    GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4472
4473
24.1k
  if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4474
    // common vars aren't constant even if declared const.
4475
17
    GV->setConstant(false);
4476
    // Tentative definition of global variables may be initialized with
4477
    // non-zero null pointers. In this case they should have weak linkage
4478
    // since common linkage must have zero initializer and must not have
4479
    // explicit section therefore cannot have non-zero initial value.
4480
17
    if (!GV->getInitializer()->isNullValue())
4481
4
      GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4482
17
  }
4483
4484
24.1k
  setNonAliasAttributes(D, GV);
4485
4486
24.1k
  if (D->getTLSKind() && 
!GV->isThreadLocal()321
) {
4487
4
    if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4488
0
      CXXThreadLocals.push_back(D);
4489
4
    setTLSMode(GV, *D);
4490
4
  }
4491
4492
24.1k
  maybeSetTrivialComdat(*D, *GV);
4493
4494
  // Emit the initializer function if necessary.
4495
24.1k
  if (NeedsGlobalCtor || 
NeedsGlobalDtor18.6k
)
4496
5.89k
    EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4497
4498
24.1k
  SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4499
4500
  // Emit global variable debug information.
4501
24.1k
  if (CGDebugInfo *DI = getModuleDebugInfo())
4502
4.52k
    if (getCodeGenOpts().hasReducedDebugInfo())
4503
4.43k
      DI->EmitGlobalVariable(GV, D);
4504
24.1k
}
4505
4506
7
void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4507
7
  if (CGDebugInfo *DI = getModuleDebugInfo())
4508
7
    if (getCodeGenOpts().hasReducedDebugInfo()) {
4509
7
      QualType ASTTy = D->getType();
4510
7
      llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4511
7
      llvm::Constant *GV = GetOrCreateLLVMGlobal(
4512
7
          D->getName(), Ty, getContext().getTargetAddressSpace(ASTTy), D);
4513
7
      DI->EmitExternalVariable(
4514
7
          cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4515
7
    }
4516
7
}
4517
4518
static bool isVarDeclStrongDefinition(const ASTContext &Context,
4519
                                      CodeGenModule &CGM, const VarDecl *D,
4520
7.19k
                                      bool NoCommon) {
4521
  // Don't give variables common linkage if -fno-common was specified unless it
4522
  // was overridden by a NoCommon attribute.
4523
7.19k
  if ((NoCommon || 
D->hasAttr<NoCommonAttr>()41
) &&
!D->hasAttr<CommonAttr>()7.15k
)
4524
7.15k
    return true;
4525
4526
  // C11 6.9.2/2:
4527
  //   A declaration of an identifier for an object that has file scope without
4528
  //   an initializer, and without a storage-class specifier or with the
4529
  //   storage-class specifier static, constitutes a tentative definition.
4530
42
  if (D->getInit() || 
D->hasExternalStorage()18
)
4531
24
    return true;
4532
4533
  // A variable cannot be both common and exist in a section.
4534
18
  if (D->hasAttr<SectionAttr>())
4535
0
    return true;
4536
4537
  // A variable cannot be both common and exist in a section.
4538
  // We don't try to determine which is the right section in the front-end.
4539
  // If no specialized section name is applicable, it will resort to default.
4540
18
  if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4541
18
      D->hasAttr<PragmaClangDataSectionAttr>() ||
4542
18
      D->hasAttr<PragmaClangRelroSectionAttr>() ||
4543
18
      D->hasAttr<PragmaClangRodataSectionAttr>())
4544
0
    return true;
4545
4546
  // Thread local vars aren't considered common linkage.
4547
18
  if (D->getTLSKind())
4548
0
    return true;
4549
4550
  // Tentative definitions marked with WeakImportAttr are true definitions.
4551
18
  if (D->hasAttr<WeakImportAttr>())
4552
0
    return true;
4553
4554
  // A variable cannot be both common and exist in a comdat.
4555
18
  if (shouldBeInCOMDAT(CGM, *D))
4556
0
    return true;
4557
4558
  // Declarations with a required alignment do not have common linkage in MSVC
4559
  // mode.
4560
18
  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4561
3
    if (D->hasAttr<AlignedAttr>())
4562
0
      return true;
4563
3
    QualType VarType = D->getType();
4564
3
    if (Context.isAlignmentRequired(VarType))
4565
0
      return true;
4566
4567
3
    if (const auto *RT = VarType->getAs<RecordType>()) {
4568
0
      const RecordDecl *RD = RT->getDecl();
4569
0
      for (const FieldDecl *FD : RD->fields()) {
4570
0
        if (FD->isBitField())
4571
0
          continue;
4572
0
        if (FD->hasAttr<AlignedAttr>())
4573
0
          return true;
4574
0
        if (Context.isAlignmentRequired(FD->getType()))
4575
0
          return true;
4576
0
      }
4577
0
    }
4578
3
  }
4579
4580
  // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4581
  // common symbols, so symbols with greater alignment requirements cannot be
4582
  // common.
4583
  // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4584
  // alignments for common symbols via the aligncomm directive, so this
4585
  // restriction only applies to MSVC environments.
4586
18
  if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4587
18
      Context.getTypeAlignIfKnown(D->getType()) >
4588
3
          Context.toBits(CharUnits::fromQuantity(32)))
4589
1
    return true;
4590
4591
17
  return false;
4592
18
}
4593
4594
llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4595
656k
    const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4596
656k
  if (Linkage == GVA_Internal)
4597
85.6k
    return llvm::Function::InternalLinkage;
4598
4599
571k
  if (D->hasAttr<WeakAttr>()) {
4600
96
    if (IsConstantVariable)
4601
2
      return llvm::GlobalVariable::WeakODRLinkage;
4602
94
    else
4603
94
      return llvm::GlobalVariable::WeakAnyLinkage;
4604
96
  }
4605
4606
571k
  if (const auto *FD = D->getAsFunction())
4607
547k
    if (FD->isMultiVersion() && 
Linkage == GVA_AvailableExternally299
)
4608
16
      return llvm::GlobalVariable::LinkOnceAnyLinkage;
4609
4610
  // We are guaranteed to have a strong definition somewhere else,
4611
  // so we can use available_externally linkage.
4612
571k
  if (Linkage == GVA_AvailableExternally)
4613
4.33k
    return llvm::GlobalValue::AvailableExternallyLinkage;
4614
4615
  // Note that Apple's kernel linker doesn't support symbol
4616
  // coalescing, so we need to avoid linkonce and weak linkages there.
4617
  // Normally, this means we just map to internal, but for explicit
4618
  // instantiations we'll map to external.
4619
4620
  // In C++, the compiler has to emit a definition in every translation unit
4621
  // that references the function.  We should use linkonce_odr because
4622
  // a) if all references in this translation unit are optimized away, we
4623
  // don't need to codegen it.  b) if the function persists, it needs to be
4624
  // merged with other definitions. c) C++ has the ODR, so we know the
4625
  // definition is dependable.
4626
566k
  if (Linkage == GVA_DiscardableODR)
4627
235k
    return !Context.getLangOpts().AppleKext ? 
llvm::Function::LinkOnceODRLinkage235k
4628
235k
                                            : 
llvm::Function::InternalLinkage20
;
4629
4630
  // An explicit instantiation of a template has weak linkage, since
4631
  // explicit instantiations can occur in multiple translation units
4632
  // and must all be equivalent. However, we are not allowed to
4633
  // throw away these explicit instantiations.
4634
  //
4635
  // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU,
4636
  // so say that CUDA templates are either external (for kernels) or internal.
4637
  // This lets llvm perform aggressive inter-procedural optimizations. For
4638
  // -fgpu-rdc case, device function calls across multiple TU's are allowed,
4639
  // therefore we need to follow the normal linkage paradigm.
4640
331k
  if (Linkage == GVA_StrongODR) {
4641
5.76k
    if (getLangOpts().AppleKext)
4642
3
      return llvm::Function::ExternalLinkage;
4643
5.76k
    if (getLangOpts().CUDA && 
getLangOpts().CUDAIsDevice51
&&
4644
5.76k
        
!getLangOpts().GPURelocatableDeviceCode51
)
4645
47
      return D->hasAttr<CUDAGlobalAttr>() ? 
llvm::Function::ExternalLinkage44
4646
47
                                          : 
llvm::Function::InternalLinkage3
;
4647
5.71k
    return llvm::Function::WeakODRLinkage;
4648
5.76k
  }
4649
4650
  // C++ doesn't have tentative definitions and thus cannot have common
4651
  // linkage.
4652
325k
  if (!getLangOpts().CPlusPlus && 
isa<VarDecl>(D)194k
&&
4653
325k
      !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4654
7.19k
                                 CodeGenOpts.NoCommon))
4655
17
    return llvm::GlobalVariable::CommonLinkage;
4656
4657
  // selectany symbols are externally visible, so use weak instead of
4658
  // linkonce.  MSVC optimizes away references to const selectany globals, so
4659
  // all definitions should be the same and ODR linkage should be used.
4660
  // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4661
325k
  if (D->hasAttr<SelectAnyAttr>())
4662
16
    return llvm::GlobalVariable::WeakODRLinkage;
4663
4664
  // Otherwise, we have strong external linkage.
4665
325k
  assert(Linkage == GVA_StrongExternal);
4666
0
  return llvm::GlobalVariable::ExternalLinkage;
4667
325k
}
4668
4669
llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4670
39.2k
    const VarDecl *VD, bool IsConstant) {
4671
39.2k
  GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4672
39.2k
  return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4673
39.2k
}
4674
4675
/// Replace the uses of a function that was declared with a non-proto type.
4676
/// We want to silently drop extra arguments from call sites
4677
static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4678
134
                                          llvm::Function *newFn) {
4679
  // Fast path.
4680
134
  if (old->use_empty()) 
return2
;
4681
4682
132
  llvm::Type *newRetTy = newFn->getReturnType();
4683
132
  SmallVector<llvm::Value*, 4> newArgs;
4684
4685
132
  for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4686
268
         ui != ue; ) {
4687
136
    llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4688
136
    llvm::User *user = use->getUser();
4689
4690
    // Recognize and replace uses of bitcasts.  Most calls to
4691
    // unprototyped functions will use bitcasts.
4692
136
    if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4693
34
      if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4694
33
        replaceUsesOfNonProtoConstant(bitcast, newFn);
4695
34
      continue;
4696
34
    }
4697
4698
    // Recognize calls to the function.
4699
102
    llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4700
102
    if (!callSite) 
continue23
;
4701
79
    if (!callSite->isCallee(&*use))
4702
3
      continue;
4703
4704
    // If the return types don't match exactly, then we can't
4705
    // transform this call unless it's dead.
4706
76
    if (callSite->getType() != newRetTy && 
!callSite->use_empty()0
)
4707
0
      continue;
4708
4709
    // Get the call site's attribute list.
4710
76
    SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4711
76
    llvm::AttributeList oldAttrs = callSite->getAttributes();
4712
4713
    // If the function was passed too few arguments, don't transform.
4714
76
    unsigned newNumArgs = newFn->arg_size();
4715
76
    if (callSite->arg_size() < newNumArgs)
4716
5
      continue;
4717
4718
    // If extra arguments were passed, we silently drop them.
4719
    // If any of the types mismatch, we don't transform.
4720
71
    unsigned argNo = 0;
4721
71
    bool dontTransform = false;
4722
71
    for (llvm::Argument &A : newFn->args()) {
4723
12
      if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4724
0
        dontTransform = true;
4725
0
        break;
4726
0
      }
4727
4728
      // Add any parameter attributes.
4729
12
      newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4730
12
      argNo++;
4731
12
    }
4732
71
    if (dontTransform)
4733
0
      continue;
4734
4735
    // Okay, we can transform this.  Create the new call instruction and copy
4736
    // over the required information.
4737
71
    newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4738
4739
    // Copy over any operand bundles.
4740
71
    SmallVector<llvm::OperandBundleDef, 1> newBundles;
4741
71
    callSite->getOperandBundlesAsDefs(newBundles);
4742
4743
71
    llvm::CallBase *newCall;
4744
71
    if (dyn_cast<llvm::CallInst>(callSite)) {
4745
68
      newCall =
4746
68
          llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4747
68
    } else {
4748
3
      auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4749
3
      newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4750
3
                                         oldInvoke->getUnwindDest(), newArgs,
4751
3
                                         newBundles, "", callSite);
4752
3
    }
4753
71
    newArgs.clear(); // for the next iteration
4754
4755
71
    if (!newCall->getType()->isVoidTy())
4756
23
      newCall->takeName(callSite);
4757
71
    newCall->setAttributes(llvm::AttributeList::get(
4758
71
        newFn->getContext(), oldAttrs.getFnAttributes(),
4759
71
        oldAttrs.getRetAttributes(), newArgAttrs));
4760
71
    newCall->setCallingConv(callSite->getCallingConv());
4761
4762
    // Finally, remove the old call, replacing any uses with the new one.
4763
71
    if (!callSite->use_empty())
4764
21
      callSite->replaceAllUsesWith(newCall);
4765
4766
    // Copy debug location attached to CI.
4767
71
    if (callSite->getDebugLoc())
4768
14
      newCall->setDebugLoc(callSite->getDebugLoc());
4769
4770
71
    callSite->eraseFromParent();
4771
71
  }
4772
132
}
4773
4774
/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4775
/// implement a function with no prototype, e.g. "int foo() {}".  If there are
4776
/// existing call uses of the old function in the module, this adjusts them to
4777
/// call the new function directly.
4778
///
4779
/// This is not just a cleanup: the always_inline pass requires direct calls to
4780
/// functions to be able to inline them.  If there is a bitcast in the way, it
4781
/// won't inline them.  Instcombine normally deletes these calls, but it isn't
4782
/// run at -O0.
4783
static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4784
102
                                                      llvm::Function *NewFn) {
4785
  // If we're redefining a global as a function, don't transform it.
4786
102
  if (!isa<llvm::Function>(Old)) 
return1
;
4787
4788
101
  replaceUsesOfNonProtoConstant(Old, NewFn);
4789
101
}
4790
4791
550k
void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4792
550k
  auto DK = VD->isThisDeclarationADefinition();
4793
550k
  if (DK == VarDecl::Definition && 
VD->hasAttr<DLLImportAttr>()550k
)
4794
45
    return;
4795
4796
550k
  TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4797
  // If we have a definition, this might be a deferred decl. If the
4798
  // instantiation is explicit, make sure we emit it at the end.
4799
550k
  if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4800
176
    GetAddrOfGlobalVar(VD);
4801
4802
550k
  EmitTopLevelDecl(VD);
4803
550k
}
4804
4805
void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4806
251k
                                                 llvm::GlobalValue *GV) {
4807
251k
  const auto *D = cast<FunctionDecl>(GD.getDecl());
4808
4809
  // Compute the function info and LLVM type.
4810
251k
  const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4811
251k
  llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4812
4813
  // Get or create the prototype for the function.
4814
251k
  if (!GV || 
(GV->getValueType() != Ty)102k
)
4815
148k
    GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4816
148k
                                                   /*DontDefer=*/true,
4817
148k
                                                   ForDefinition));
4818
4819
  // Already emitted.
4820
251k
  if (!GV->isDeclaration())
4821
18
    return;
4822
4823
  // We need to set linkage and visibility on the function before
4824
  // generating code for it because various parts of IR generation
4825
  // want to propagate this information down (e.g. to local static
4826
  // declarations).
4827
251k
  auto *Fn = cast<llvm::Function>(GV);
4828
251k
  setFunctionLinkage(GD, Fn);
4829
4830
  // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4831
251k
  setGVProperties(Fn, GD);
4832
4833
251k
  MaybeHandleStaticInExternC(D, Fn);
4834
4835
251k
  maybeSetTrivialComdat(*D, *Fn);
4836
4837
  // Set CodeGen attributes that represent floating point environment.
4838
251k
  setLLVMFunctionFEnvAttributes(D, Fn);
4839
4840
251k
  CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4841
4842
251k
  setNonAliasAttributes(GD, Fn);
4843
251k
  SetLLVMFunctionAttributesForDefinition(D, Fn);
4844
4845
251k
  if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4846
22
    AddGlobalCtor(Fn, CA->getPriority());
4847
251k
  if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4848
39
    AddGlobalDtor(Fn, DA->getPriority(), true);
4849
251k
  if (D->hasAttr<AnnotateAttr>())
4850
6
    AddGlobalAnnotations(D, Fn);
4851
251k
}
4852
4853
137
void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4854
137
  const auto *D = cast<ValueDecl>(GD.getDecl());
4855
137
  const AliasAttr *AA = D->getAttr<AliasAttr>();
4856
137
  assert(AA && "Not an alias?");
4857
4858
0
  StringRef MangledName = getMangledName(GD);
4859
4860
137
  if (AA->getAliasee() == MangledName) {
4861
1
    Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4862
1
    return;
4863
1
  }
4864
4865
  // If there is a definition in the module, then it wins over the alias.
4866
  // This is dubious, but allow it to be safe.  Just ignore the alias.
4867
136
  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4868
136
  if (Entry && 
!Entry->isDeclaration()13
)
4869
3
    return;
4870
4871
133
  Aliases.push_back(GD);
4872
4873
133
  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4874
4875
  // Create a reference to the named value.  This ensures that it is emitted
4876
  // if a deferred decl.
4877
133
  llvm::Constant *Aliasee;
4878
133
  llvm::GlobalValue::LinkageTypes LT;
4879
133
  if (isa<llvm::FunctionType>(DeclTy)) {
4880
91
    Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4881
91
                                      /*ForVTable=*/false);
4882
91
    LT = getFunctionLinkage(GD);
4883
91
  } else {
4884
42
    Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, 0,
4885
42
                                    /*D=*/nullptr);
4886
42
    if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl()))
4887
38
      LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified());
4888
4
    else
4889
4
      LT = getFunctionLinkage(GD);
4890
42
  }
4891
4892
  // Create the new alias itself, but don't set a name yet.
4893
133
  unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4894
133
  auto *GA =
4895
133
      llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4896
4897
133
  if (Entry) {
4898
10
    if (GA->getAliasee() == Entry) {
4899
0
      Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4900
0
      return;
4901
0
    }
4902
4903
10
    assert(Entry->isDeclaration());
4904
4905
    // If there is a declaration in the module, then we had an extern followed
4906
    // by the alias, as in:
4907
    //   extern int test6();
4908
    //   ...
4909
    //   int test6() __attribute__((alias("test7")));
4910
    //
4911
    // Remove it and replace uses of it with the alias.
4912
0
    GA->takeName(Entry);
4913
4914
10
    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4915
10
                                                          Entry->getType()));
4916
10
    Entry->eraseFromParent();
4917
123
  } else {
4918
123
    GA->setName(MangledName);
4919
123
  }
4920
4921
  // Set attributes which are particular to an alias; this is a
4922
  // specialization of the attributes which may be set on a global
4923
  // variable/function.
4924
133
  if (D->hasAttr<WeakAttr>() || 
D->hasAttr<WeakRefAttr>()110
||
4925
133
      
D->isWeakImported()110
) {
4926
23
    GA->setLinkage(llvm::Function::WeakAnyLinkage);
4927
23
  }
4928
4929
133
  if (const auto *VD = dyn_cast<VarDecl>(D))
4930
38
    if (VD->getTLSKind())
4931
4
      setTLSMode(GA, *VD);
4932
4933
133
  SetCommonAttributes(GD, GA);
4934
133
}
4935
4936
14
void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4937
14
  const auto *D = cast<ValueDecl>(GD.getDecl());
4938
14
  const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4939
14
  assert(IFA && "Not an ifunc?");
4940
4941
0
  StringRef MangledName = getMangledName(GD);
4942
4943
14
  if (IFA->getResolver() == MangledName) {
4944
0
    Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4945
0
    return;
4946
0
  }
4947
4948
  // Report an error if some definition overrides ifunc.
4949
14
  llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4950
14
  if (Entry && 
!Entry->isDeclaration()4
) {
4951
1
    GlobalDecl OtherGD;
4952
1
    if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4953
1
        DiagnosedConflictingDefinitions.insert(GD).second) {
4954
1
      Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4955
1
          << MangledName;
4956
1
      Diags.Report(OtherGD.getDecl()->getLocation(),
4957
1
                   diag::note_previous_definition);
4958
1
    }
4959
1
    return;
4960
1
  }
4961
4962
13
  Aliases.push_back(GD);
4963
4964
13
  llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4965
13
  llvm::Constant *Resolver =
4966
13
      GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4967
13
                              /*ForVTable=*/false);
4968
13
  llvm::GlobalIFunc *GIF =
4969
13
      llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4970
13
                                "", Resolver, &getModule());
4971
13
  if (Entry) {
4972
3
    if (GIF->getResolver() == Entry) {
4973
0
      Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4974
0
      return;
4975
0
    }
4976
3
    assert(Entry->isDeclaration());
4977
4978
    // If there is a declaration in the module, then we had an extern followed
4979
    // by the ifunc, as in:
4980
    //   extern int test();
4981
    //   ...
4982
    //   int test() __attribute__((ifunc("resolver")));
4983
    //
4984
    // Remove it and replace uses of it with the ifunc.
4985
0
    GIF->takeName(Entry);
4986
4987
3
    Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4988
3
                                                          Entry->getType()));
4989
3
    Entry->eraseFromParent();
4990
3
  } else
4991
10
    GIF->setName(MangledName);
4992
4993
13
  SetCommonAttributes(GD, GIF);
4994
13
}
4995
4996
llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4997
126k
                                            ArrayRef<llvm::Type*> Tys) {
4998
126k
  return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4999
126k
                                         Tys);
5000
126k
}
5001
5002
static llvm::StringMapEntry<llvm::GlobalVariable *> &
5003
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
5004
                         const StringLiteral *Literal, bool TargetIsLSB,
5005
5.60k
                         bool &IsUTF16, unsigned &StringLength) {
5006
5.60k
  StringRef String = Literal->getString();
5007
5.60k
  unsigned NumBytes = String.size();
5008
5009
  // Check for simple case.
5010
5.60k
  if (!Literal->containsNonAsciiOrNull()) {
5011
5.40k
    StringLength = NumBytes;
5012
5.40k
    return *Map.insert(std::make_pair(String, nullptr)).first;
5013
5.40k
  }
5014
5015
  // Otherwise, convert the UTF8 literals into a string of shorts.
5016
205
  IsUTF16 = true;
5017
5018
205
  SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
5019
205
  const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5020
205
  llvm::UTF16 *ToPtr = &ToBuf[0];
5021
5022
205
  (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5023
205
                                 ToPtr + NumBytes, llvm::strictConversion);
5024
5025
  // ConvertUTF8toUTF16 returns the length in ToPtr.
5026
205
  StringLength = ToPtr - &ToBuf[0];
5027
5028
  // Add an explicit null.
5029
205
  *ToPtr = 0;
5030
205
  return *Map.insert(std::make_pair(
5031
205
                         StringRef(reinterpret_cast<const char *>(ToBuf.data()),
5032
205
                                   (StringLength + 1) * 2),
5033
205
                         nullptr)).first;
5034
5.60k
}
5035
5036
ConstantAddress
5037
5.60k
CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
5038
5.60k
  unsigned StringLength = 0;
5039
5.60k
  bool isUTF16 = false;
5040
5.60k
  llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
5041
5.60k
      GetConstantCFStringEntry(CFConstantStringMap, Literal,
5042
5.60k
                               getDataLayout().isLittleEndian(), isUTF16,
5043
5.60k
                               StringLength);
5044
5045
5.60k
  if (auto *C = Entry.second)
5046
1.88k
    return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
5047
5048
3.72k
  llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
5049
3.72k
  llvm::Constant *Zeros[] = { Zero, Zero };
5050
5051
3.72k
  const ASTContext &Context = getContext();
5052
3.72k
  const llvm::Triple &Triple = getTriple();
5053
5054
3.72k
  const auto CFRuntime = getLangOpts().CFRuntime;
5055
3.72k
  const bool IsSwiftABI =
5056
3.72k
      static_cast<unsigned>(CFRuntime) >=
5057
3.72k
      static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
5058
3.72k
  const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
5059