Coverage Report

Created: 2021-08-24 07:12

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