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 "CGOpenMPRuntimeNVPTX.h"
23 #include "CodeGenFunction.h"
24 #include "CodeGenPGO.h"
25 #include "ConstantEmitter.h"
26 #include "CoverageMappingGen.h"
27 #include "TargetInfo.h"
28 #include "clang/AST/ASTContext.h"
29 #include "clang/AST/CharUnits.h"
30 #include "clang/AST/DeclCXX.h"
31 #include "clang/AST/DeclObjC.h"
32 #include "clang/AST/DeclTemplate.h"
33 #include "clang/AST/Mangle.h"
34 #include "clang/AST/RecordLayout.h"
35 #include "clang/AST/RecursiveASTVisitor.h"
36 #include "clang/AST/StmtVisitor.h"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CharInfo.h"
39 #include "clang/Basic/CodeGenOptions.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/FileManager.h"
42 #include "clang/Basic/Module.h"
43 #include "clang/Basic/SourceManager.h"
44 #include "clang/Basic/TargetInfo.h"
45 #include "clang/Basic/Version.h"
46 #include "clang/CodeGen/ConstantInitBuilder.h"
47 #include "clang/Frontend/FrontendDiagnostic.h"
48 #include "llvm/ADT/ScopeExit.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/Cheri.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/Intrinsics.h"
57 #include "llvm/IR/LLVMContext.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/ProfileSummary.h"
60 #include "llvm/ProfileData/InstrProfReader.h"
61 #include "llvm/Support/CodeGen.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/ConvertUTF.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/FileSystem.h"
66 #include "llvm/Support/MD5.h"
67 #include "llvm/Support/YAMLParser.h"
68 #include "llvm/Support/TimeProfiler.h"
69 #include "llvm/Transforms/Utils/CheriSetBounds.h"
70
71 using namespace clang;
72 using namespace CodeGen;
73
74 static llvm::cl::opt<bool> LimitedCoverage(
75 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
76 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
77 llvm::cl::init(false));
78
79 static llvm::cl::opt<bool> CollectPointerCastStats(
80 "collect-pointer-cast-stats", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
81 llvm::cl::desc("Collect statistics on numbers of int <-> pointer casts"),
82 llvm::cl::init(false));
83
84 static const char AnnotationSection[] = "llvm.metadata";
85
createCXXABI(CodeGenModule & CGM)86 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
87 switch (CGM.getTarget().getCXXABI().getKind()) {
88 case TargetCXXABI::Fuchsia:
89 case TargetCXXABI::GenericAArch64:
90 case TargetCXXABI::GenericARM:
91 case TargetCXXABI::iOS:
92 case TargetCXXABI::iOS64:
93 case TargetCXXABI::WatchOS:
94 case TargetCXXABI::GenericMIPS:
95 case TargetCXXABI::GenericItanium:
96 case TargetCXXABI::WebAssembly:
97 case TargetCXXABI::XL:
98 return CreateItaniumCXXABI(CGM);
99 case TargetCXXABI::Microsoft:
100 return CreateMicrosoftCXXABI(CGM);
101 }
102
103 llvm_unreachable("invalid C++ ABI kind");
104 }
105
CodeGenModule(ASTContext & C,const HeaderSearchOptions & HSO,const PreprocessorOptions & PPO,const CodeGenOptions & CGO,llvm::Module & M,DiagnosticsEngine & diags,CoverageSourceInfo * CoverageInfo)106 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
107 const PreprocessorOptions &PPO,
108 const CodeGenOptions &CGO, llvm::Module &M,
109 DiagnosticsEngine &diags,
110 CoverageSourceInfo *CoverageInfo)
111 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
112 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
113 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
114 VMContext(M.getContext()), Types(*this), VTables(*this),
115 SanitizerMD(new SanitizerMetadata(*this)) {
116
117 // Initialize the type cache.
118 llvm::LLVMContext &LLVMContext = M.getContext();
119 VoidTy = llvm::Type::getVoidTy(LLVMContext);
120 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
121 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
122 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
123 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
124 HalfTy = llvm::Type::getHalfTy(LLVMContext);
125 BFloatTy = llvm::Type::getBFloatTy(LLVMContext);
126 FloatTy = llvm::Type::getFloatTy(LLVMContext);
127 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
128 const TargetInfo &Target = C.getTargetInfo();
129 PointerWidthInBits = Target.getPointerWidth(0);
130 PointerAlignInBytes =
131 C.toCharUnitsFromBits(Target.getPointerAlign(0)).getQuantity();
132 // XXXAR: these are a union why even bother assigning both??
133 // XXXAR: just use the pointer range as the width/align of size_t
134 SizeAlignInBytes =
135 C.toCharUnitsFromBits(Target.getTypeAlign(Target.getSizeType())).getQuantity();
136 SizeSizeInBytes =
137 C.toCharUnitsFromBits(Target.getTypeWidth(Target.getSizeType())).getQuantity();
138 IntAlignInBytes =
139 C.toCharUnitsFromBits(Target.getIntAlign()).getQuantity();
140 IntTy = llvm::IntegerType::get(LLVMContext, Target.getIntWidth());
141 // XXXAR it seems like the codegen uses this type as an integer which can fit
142 // the pointer range and not as an integer with the same width as a pointer
143 IntPtrTy = llvm::IntegerType::get(LLVMContext, Target.getMaxPointerRange());
144 Int8PtrTy = Int8Ty->getPointerTo(getTargetCodeGenInfo().getDefaultAS());
145 if (Target.SupportsCapabilities()) {
146 Int8CheriCapTy =
147 Int8Ty->getPointerTo(getTargetCodeGenInfo().getCHERICapabilityAS());
148 } else {
149 Int8CheriCapTy = nullptr;
150 }
151 Int8PtrPtrTy = Int8PtrTy->getPointerTo(getTargetCodeGenInfo().getDefaultAS());
152 AllocaInt8PtrTy =
153 Int8Ty->getPointerTo(M.getDataLayout().getAllocaAddrSpace());
154 ProgramInt8PtrTy =
155 Int8Ty->getPointerTo(M.getDataLayout().getProgramAddressSpace());
156 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
157
158 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
159
160 if (LangOpts.ObjC)
161 createObjCRuntime();
162 if (LangOpts.OpenCL)
163 createOpenCLRuntime();
164 if (LangOpts.OpenMP)
165 createOpenMPRuntime();
166 if (LangOpts.CUDA)
167 createCUDARuntime();
168
169 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
170 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
171 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
172 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
173 getCXXABI().getMangleContext()));
174
175 // If debug info or coverage generation is enabled, create the CGDebugInfo
176 // object.
177 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
178 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
179 DebugInfo.reset(new CGDebugInfo(*this));
180
181 Block.GlobalUniqueCount = 0;
182
183 if (C.getLangOpts().ObjC)
184 ObjCData.reset(new ObjCEntrypoints());
185
186 if (CodeGenOpts.hasProfileClangUse()) {
187 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
188 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
189 if (auto E = ReaderOrErr.takeError()) {
190 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
191 "Could not read profile %0: %1");
192 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
193 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
194 << EI.message();
195 });
196 } else
197 PGOReader = std::move(ReaderOrErr.get());
198 }
199
200 // If coverage mapping generation is enabled, create the
201 // CoverageMappingModuleGen object.
202 if (CodeGenOpts.CoverageMapping)
203 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
204
205 if (CollectPointerCastStats)
206 PointerCastStats.reset(new PointerCastLocations);
207 }
208
~CodeGenModule()209 CodeGenModule::~CodeGenModule() {}
210
createObjCRuntime()211 void CodeGenModule::createObjCRuntime() {
212 // This is just isGNUFamily(), but we want to force implementors of
213 // new ABIs to decide how best to do this.
214 switch (LangOpts.ObjCRuntime.getKind()) {
215 case ObjCRuntime::GNUstep:
216 case ObjCRuntime::GCC:
217 case ObjCRuntime::ObjFW:
218 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
219 return;
220
221 case ObjCRuntime::FragileMacOSX:
222 case ObjCRuntime::MacOSX:
223 case ObjCRuntime::iOS:
224 case ObjCRuntime::WatchOS:
225 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
226 return;
227 }
228 llvm_unreachable("bad runtime kind");
229 }
230
createOpenCLRuntime()231 void CodeGenModule::createOpenCLRuntime() {
232 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
233 }
234
createOpenMPRuntime()235 void CodeGenModule::createOpenMPRuntime() {
236 // Select a specialized code generation class based on the target, if any.
237 // If it does not exist use the default implementation.
238 switch (getTriple().getArch()) {
239 case llvm::Triple::nvptx:
240 case llvm::Triple::nvptx64:
241 assert(getLangOpts().OpenMPIsDevice &&
242 "OpenMP NVPTX is only prepared to deal with device code.");
243 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
244 break;
245 default:
246 if (LangOpts.OpenMPSimd)
247 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
248 else
249 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
250 break;
251 }
252 }
253
createCUDARuntime()254 void CodeGenModule::createCUDARuntime() {
255 CUDARuntime.reset(CreateNVCUDARuntime(*this));
256 }
257
addReplacement(StringRef Name,llvm::Constant * C)258 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
259 Replacements[Name] = C;
260 }
261
applyReplacements()262 void CodeGenModule::applyReplacements() {
263 for (auto &I : Replacements) {
264 StringRef MangledName = I.first();
265 llvm::Constant *Replacement = I.second;
266 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
267 if (!Entry)
268 continue;
269 auto *OldF = cast<llvm::Function>(Entry);
270 auto *NewF = dyn_cast<llvm::Function>(Replacement);
271 if (!NewF) {
272 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
273 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
274 } else {
275 auto *CE = cast<llvm::ConstantExpr>(Replacement);
276 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
277 CE->getOpcode() == llvm::Instruction::GetElementPtr);
278 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
279 }
280 }
281
282 // Replace old with new, but keep the old order.
283 OldF->replaceAllUsesWith(Replacement);
284 if (NewF) {
285 NewF->removeFromParent();
286 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
287 NewF);
288 }
289 OldF->eraseFromParent();
290 }
291 }
292
addGlobalValReplacement(llvm::GlobalValue * GV,llvm::Constant * C)293 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
294 GlobalValReplacements.push_back(std::make_pair(GV, C));
295 }
296
applyGlobalValReplacements()297 void CodeGenModule::applyGlobalValReplacements() {
298 for (auto &I : GlobalValReplacements) {
299 llvm::GlobalValue *GV = I.first;
300 llvm::Constant *C = I.second;
301
302 GV->replaceAllUsesWith(C);
303 GV->eraseFromParent();
304 }
305 }
306
307 // This is only used in aliases that we created and we know they have a
308 // linear structure.
getAliasedGlobal(const llvm::GlobalIndirectSymbol & GIS)309 static const llvm::GlobalObject *getAliasedGlobal(
310 const llvm::GlobalIndirectSymbol &GIS) {
311 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
312 const llvm::Constant *C = &GIS;
313 for (;;) {
314 C = C->stripPointerCasts();
315 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
316 return GO;
317 // stripPointerCasts will not walk over weak aliases.
318 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
319 if (!GIS2)
320 return nullptr;
321 if (!Visited.insert(GIS2).second)
322 return nullptr;
323 C = GIS2->getIndirectSymbol();
324 }
325 }
326
getAddressSpaceForType(QualType T)327 unsigned CodeGenModule::getAddressSpaceForType(QualType T) {
328 return getTargetCodeGenInfo().getAddressSpaceForType(T, getContext());
329 }
330
getTargetAddressSpace(LangAS AddrSpace)331 unsigned CodeGenModule::getTargetAddressSpace(LangAS AddrSpace) {
332 unsigned Result = getContext().getTargetAddressSpace(AddrSpace);
333 return Result;
334 }
335
checkAliases()336 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 bool Error = false;
341 DiagnosticsEngine &Diags = getDiags();
342 for (const GlobalDecl &GD : Aliases) {
343 const auto *D = cast<ValueDecl>(GD.getDecl());
344 SourceLocation Location;
345 bool IsIFunc = D->hasAttr<IFuncAttr>();
346 if (const Attr *A = D->getDefiningAttr())
347 Location = A->getLocation();
348 else
349 llvm_unreachable("Not an alias or ifunc?");
350 StringRef MangledName = getMangledName(GD);
351 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
352 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
353 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
354 if (!GV) {
355 Error = true;
356 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
357 } else if (GV->isDeclaration()) {
358 Error = true;
359 Diags.Report(Location, diag::err_alias_to_undefined)
360 << IsIFunc << IsIFunc;
361 } else if (IsIFunc) {
362 // Check resolver function type.
363 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
364 GV->getType()->getPointerElementType());
365 assert(FTy);
366 if (!FTy->getReturnType()->isPointerTy())
367 Diags.Report(Location, diag::err_ifunc_resolver_return);
368 }
369
370 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
371 llvm::GlobalValue *AliaseeGV;
372 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
373 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
374 else
375 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
376
377 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
378 StringRef AliasSection = SA->getName();
379 if (AliasSection != AliaseeGV->getSection())
380 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
381 << AliasSection << IsIFunc << IsIFunc;
382 }
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 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
390 if (GA->isInterposable()) {
391 Diags.Report(Location, diag::warn_alias_to_weak_alias)
392 << GV->getName() << GA->getName() << IsIFunc;
393 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
394 GA->getIndirectSymbol(), Alias->getType());
395 Alias->setIndirectSymbol(Aliasee);
396 }
397 }
398 }
399 if (!Error)
400 return;
401
402 for (const GlobalDecl &GD : Aliases) {
403 StringRef MangledName = getMangledName(GD);
404 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
405 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
406 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
407 Alias->eraseFromParent();
408 }
409 }
410
clear()411 void CodeGenModule::clear() {
412 DeferredDeclsToEmit.clear();
413 if (OpenMPRuntime)
414 OpenMPRuntime->clear();
415 }
416
reportDiagnostics(DiagnosticsEngine & Diags,StringRef MainFile)417 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
418 StringRef MainFile) {
419 if (!hasDiagnostics())
420 return;
421 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
422 if (MainFile.empty())
423 MainFile = "<stdin>";
424 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
425 } else {
426 if (Mismatched > 0)
427 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
428
429 if (Missing > 0)
430 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
431 }
432 }
433
printStats(llvm::raw_ostream & OS,const CodeGenModule & CGM)434 void CodeGenModule::PointerCastLocations::printStats(llvm::raw_ostream &OS,
435 const CodeGenModule &CGM) {
436 const SourceManager &SM = CGM.getContext().getSourceManager();
437 auto DumpStat = [&](const llvm::SmallVectorImpl<std::pair<SourceRange, bool>> &Vec) {
438 const size_t Total = Vec.size();
439 OS << "\t\t\"count\": " << Total << ",\n\t\t\"locations\": [";
440 unsigned NumImplicitCasts = 0;
441 if (Total == 0) {
442 OS << "]";
443 return;
444 }
445
446 for (size_t i = 0; i < Total;) {
447 OS << "\n\t\t\t\"" << llvm::yaml::escape(Vec[i].first.printToString(SM));
448 if (Vec[i].second) {
449 OS << " (implicit)";
450 NumImplicitCasts++;
451 }
452 OS << '"';
453 i++;
454 if (i < Total)
455 OS << ',';
456 }
457 OS << "\n\t\t]";
458 if (NumImplicitCasts)
459 OS << ",\n\t\t\"implicit_count\": " << NumImplicitCasts << "";
460 };
461
462 OS << "{ \"pointer_cast_stats\": {\n";
463 StringRef MainFile = CGM.getCodeGenOpts().MainFileName;
464 if (MainFile.empty()) {
465 SourceLocation MainFileLoc = SM.getLocForStartOfFile(SM.getMainFileID());
466 MainFile = SM.getFilename(MainFileLoc);
467 }
468 OS << "\t\"main_file\": \"" << llvm::yaml::escape(MainFile) << "\",\n";
469 OS << "\t\"ptrtoint\": {\n";
470
471 DumpStat(PointerToInt);
472 OS << "\n\t}, \"inttoptr\": {\n";
473 DumpStat(IntToPointer);
474 OS << "\n\t}, \"captoptr\": {\n";
475 DumpStat(CapToPointer);
476 OS << "\n\t}, \"ptrtocap\": {\n";
477 DumpStat(PointerToCap);
478 OS << "\n\t}";
479 OS << "\n} }";
480 }
481
Release()482 void CodeGenModule::Release() {
483 EmitDeferred();
484 EmitVTablesOpportunistically();
485 applyGlobalValReplacements();
486 applyReplacements();
487 checkAliases();
488 emitMultiVersionFunctions();
489 EmitCXXGlobalInitFunc();
490 EmitCXXGlobalCleanUpFunc();
491 registerGlobalDtorsWithAtExit();
492 EmitCXXThreadLocalInitFunc();
493 if (ObjCRuntime)
494 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
495 AddGlobalCtor(ObjCInitFunction);
496 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
497 CUDARuntime) {
498 if (llvm::Function *CudaCtorFunction =
499 CUDARuntime->makeModuleCtorFunction())
500 AddGlobalCtor(CudaCtorFunction);
501 }
502 if (OpenMPRuntime) {
503 if (llvm::Function *OpenMPRequiresDirectiveRegFun =
504 OpenMPRuntime->emitRequiresDirectiveRegFun()) {
505 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
506 }
507 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
508 OpenMPRuntime->clear();
509 }
510 if (PGOReader) {
511 getModule().setProfileSummary(
512 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
513 llvm::ProfileSummary::PSK_Instr);
514 if (PGOStats.hasDiagnostics())
515 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
516 }
517 EmitCtorList(GlobalCtors, "llvm.global_ctors");
518 EmitCtorList(GlobalDtors, "llvm.global_dtors");
519 EmitGlobalAnnotations();
520 EmitStaticExternCAliases();
521 EmitDeferredUnusedCoverageMappings();
522 if (CoverageMapping)
523 CoverageMapping->emit();
524 if (CodeGenOpts.SanitizeCfiCrossDso) {
525 CodeGenFunction(*this).EmitCfiCheckFail();
526 CodeGenFunction(*this).EmitCfiCheckStub();
527 }
528 emitAtAvailableLinkGuard();
529 if (Context.getTargetInfo().getTriple().isWasm() &&
530 !Context.getTargetInfo().getTriple().isOSEmscripten()) {
531 EmitMainVoidAlias();
532 }
533 emitLLVMUsed();
534 if (SanStats)
535 SanStats->finish();
536
537 if (CollectPointerCastStats) {
538 auto StatsOS = llvm::cheri::StatsOutputFile::open(
539 getCodeGenOpts().CHERIStatsFile,
540 [this](StringRef StatsFile, const std::error_code &EC) {
541 getDiags().Report(diag::warn_fe_unable_to_open_stats_file)
542 << StatsFile << EC.message();
543 },
544 [this](StringRef StatsFile, const std::error_code &EC) {
545 getDiags().Report(diag::warn_fe_unable_to_lock_stats_file)
546 << StatsFile << EC.message();
547 });
548 if (StatsOS)
549 PointerCastStats->printStats(StatsOS->stream(), *this);
550 }
551
552 if (CodeGenOpts.Autolink &&
553 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
554 EmitModuleLinkOptions();
555 }
556
557 // On ELF we pass the dependent library specifiers directly to the linker
558 // without manipulating them. This is in contrast to other platforms where
559 // they are mapped to a specific linker option by the compiler. This
560 // difference is a result of the greater variety of ELF linkers and the fact
561 // that ELF linkers tend to handle libraries in a more complicated fashion
562 // than on other platforms. This forces us to defer handling the dependent
563 // libs to the linker.
564 //
565 // CUDA/HIP device and host libraries are different. Currently there is no
566 // way to differentiate dependent libraries for host or device. Existing
567 // usage of #pragma comment(lib, *) is intended for host libraries on
568 // Windows. Therefore emit llvm.dependent-libraries only for host.
569 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
570 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
571 for (auto *MD : ELFDependentLibraries)
572 NMD->addOperand(MD);
573 }
574
575 // Record mregparm value now so it is visible through rest of codegen.
576 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
577 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
578 CodeGenOpts.NumRegisterParameters);
579
580 if (CodeGenOpts.DwarfVersion) {
581 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
582 CodeGenOpts.DwarfVersion);
583 }
584
585 if (Context.getLangOpts().SemanticInterposition)
586 // Require various optimization to respect semantic interposition.
587 getModule().setSemanticInterposition(1);
588 else if (Context.getLangOpts().ExplicitNoSemanticInterposition)
589 // Allow dso_local on applicable targets.
590 getModule().setSemanticInterposition(0);
591
592 if (CodeGenOpts.EmitCodeView) {
593 // Indicate that we want CodeView in the metadata.
594 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
595 }
596 if (CodeGenOpts.CodeViewGHash) {
597 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
598 }
599 if (CodeGenOpts.ControlFlowGuard) {
600 // Function ID tables and checks for Control Flow Guard (cfguard=2).
601 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
602 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
603 // Function ID tables for Control Flow Guard (cfguard=1).
604 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
605 }
606 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
607 // We don't support LTO with 2 with different StrictVTablePointers
608 // FIXME: we could support it by stripping all the information introduced
609 // by StrictVTablePointers.
610
611 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
612
613 llvm::Metadata *Ops[2] = {
614 llvm::MDString::get(VMContext, "StrictVTablePointers"),
615 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
616 llvm::Type::getInt32Ty(VMContext), 1))};
617
618 getModule().addModuleFlag(llvm::Module::Require,
619 "StrictVTablePointersRequirement",
620 llvm::MDNode::get(VMContext, Ops));
621 }
622 if (getModuleDebugInfo())
623 // We support a single version in the linked module. The LLVM
624 // parser will drop debug info with a different version number
625 // (and warn about it, too).
626 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
627 llvm::DEBUG_METADATA_VERSION);
628
629 // We need to record the widths of enums and wchar_t, so that we can generate
630 // the correct build attributes in the ARM backend. wchar_size is also used by
631 // TargetLibraryInfo.
632 uint64_t WCharWidth =
633 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
634 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
635
636 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
637 if ( Arch == llvm::Triple::arm
638 || Arch == llvm::Triple::armeb
639 || Arch == llvm::Triple::thumb
640 || Arch == llvm::Triple::thumbeb) {
641 // The minimum width of an enum in bytes
642 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
643 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
644 }
645
646 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
647 StringRef ABIStr = Target.getABI();
648 llvm::LLVMContext &Ctx = TheModule.getContext();
649 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
650 llvm::MDString::get(Ctx, ABIStr));
651 }
652
653 if (CodeGenOpts.SanitizeCfiCrossDso) {
654 // Indicate that we want cross-DSO control flow integrity checks.
655 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
656 }
657
658 if (CodeGenOpts.WholeProgramVTables) {
659 // Indicate whether VFE was enabled for this module, so that the
660 // vcall_visibility metadata added under whole program vtables is handled
661 // appropriately in the optimizer.
662 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim",
663 CodeGenOpts.VirtualFunctionElimination);
664 }
665
666 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
667 getModule().addModuleFlag(llvm::Module::Override,
668 "CFI Canonical Jump Tables",
669 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
670 }
671
672 if (CodeGenOpts.CFProtectionReturn &&
673 Target.checkCFProtectionReturnSupported(getDiags())) {
674 // Indicate that we want to instrument return control flow protection.
675 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
676 1);
677 }
678
679 if (CodeGenOpts.CFProtectionBranch &&
680 Target.checkCFProtectionBranchSupported(getDiags())) {
681 // Indicate that we want to instrument branch control flow protection.
682 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
683 1);
684 }
685
686 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
687 // Indicate whether __nvvm_reflect should be configured to flush denormal
688 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
689 // property.)
690 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
691 CodeGenOpts.FP32DenormalMode.Output !=
692 llvm::DenormalMode::IEEE);
693 }
694
695 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
696 if (LangOpts.OpenCL) {
697 EmitOpenCLMetadata();
698 // Emit SPIR version.
699 if (getTriple().isSPIR()) {
700 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
701 // opencl.spir.version named metadata.
702 // C++ is backwards compatible with OpenCL v2.0.
703 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
704 llvm::Metadata *SPIRVerElts[] = {
705 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
706 Int32Ty, Version / 100)),
707 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
708 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
709 llvm::NamedMDNode *SPIRVerMD =
710 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
711 llvm::LLVMContext &Ctx = TheModule.getContext();
712 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
713 }
714 }
715
716 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
717 assert(PLevel < 3 && "Invalid PIC Level");
718 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
719 if (Context.getLangOpts().PIE)
720 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
721 }
722
723 if (getCodeGenOpts().CodeModel.size() > 0) {
724 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
725 .Case("tiny", llvm::CodeModel::Tiny)
726 .Case("small", llvm::CodeModel::Small)
727 .Case("kernel", llvm::CodeModel::Kernel)
728 .Case("medium", llvm::CodeModel::Medium)
729 .Case("large", llvm::CodeModel::Large)
730 .Default(~0u);
731 if (CM != ~0u) {
732 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
733 getModule().setCodeModel(codeModel);
734 }
735 }
736
737 if (CodeGenOpts.NoPLT)
738 getModule().setRtLibUseGOT();
739
740 SimplifyPersonality();
741
742 if (getCodeGenOpts().EmitDeclMetadata)
743 EmitDeclMetadata();
744
745 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
746 EmitCoverageFile();
747
748 if (CGDebugInfo *DI = getModuleDebugInfo())
749 DI->finalize();
750
751 if (getCodeGenOpts().EmitVersionIdentMetadata)
752 EmitVersionIdentMetadata();
753
754 if (!getCodeGenOpts().RecordCommandLine.empty())
755 EmitCommandLineMetadata();
756
757 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames);
758
759 EmitBackendOptionsMetadata(getCodeGenOpts());
760 }
761
EmitOpenCLMetadata()762 void CodeGenModule::EmitOpenCLMetadata() {
763 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
764 // opencl.ocl.version named metadata node.
765 // C++ is backwards compatible with OpenCL v2.0.
766 // FIXME: We might need to add CXX version at some point too?
767 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
768 llvm::Metadata *OCLVerElts[] = {
769 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
770 Int32Ty, Version / 100)),
771 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
772 Int32Ty, (Version % 100) / 10))};
773 llvm::NamedMDNode *OCLVerMD =
774 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
775 llvm::LLVMContext &Ctx = TheModule.getContext();
776 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
777 }
778
EmitBackendOptionsMetadata(const CodeGenOptions CodeGenOpts)779 void CodeGenModule::EmitBackendOptionsMetadata(
780 const CodeGenOptions CodeGenOpts) {
781 switch (getTriple().getArch()) {
782 default:
783 break;
784 case llvm::Triple::riscv32:
785 case llvm::Triple::riscv64:
786 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit",
787 CodeGenOpts.SmallDataLimit);
788 break;
789 }
790 }
791
UpdateCompletedType(const TagDecl * TD)792 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
793 // Make sure that this type is translated.
794 Types.UpdateCompletedType(TD);
795 }
796
RefreshTypeCacheForClass(const CXXRecordDecl * RD)797 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
798 // Make sure that this type is translated.
799 Types.RefreshTypeCacheForClass(RD);
800 }
801
getTBAATypeInfo(QualType QTy)802 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
803 if (!TBAA)
804 return nullptr;
805 return TBAA->getTypeInfo(QTy);
806 }
807
getTBAAAccessInfo(QualType AccessType)808 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
809 if (!TBAA)
810 return TBAAAccessInfo();
811 if (getLangOpts().CUDAIsDevice) {
812 // As CUDA builtin surface/texture types are replaced, skip generating TBAA
813 // access info.
814 if (AccessType->isCUDADeviceBuiltinSurfaceType()) {
815 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() !=
816 nullptr)
817 return TBAAAccessInfo();
818 } else if (AccessType->isCUDADeviceBuiltinTextureType()) {
819 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() !=
820 nullptr)
821 return TBAAAccessInfo();
822 }
823 }
824 return TBAA->getAccessInfo(AccessType);
825 }
826
827 TBAAAccessInfo
getTBAAVTablePtrAccessInfo(llvm::Type * VTablePtrType)828 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
829 if (!TBAA)
830 return TBAAAccessInfo();
831 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
832 }
833
getTBAAStructInfo(QualType QTy)834 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
835 if (!TBAA)
836 return nullptr;
837 return TBAA->getTBAAStructInfo(QTy);
838 }
839
getTBAABaseTypeInfo(QualType QTy)840 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
841 if (!TBAA)
842 return nullptr;
843 return TBAA->getBaseTypeInfo(QTy);
844 }
845
getTBAAAccessTagInfo(TBAAAccessInfo Info)846 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
847 if (!TBAA)
848 return nullptr;
849 return TBAA->getAccessTagInfo(Info);
850 }
851
mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,TBAAAccessInfo TargetInfo)852 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
853 TBAAAccessInfo TargetInfo) {
854 if (!TBAA)
855 return TBAAAccessInfo();
856 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
857 }
858
859 TBAAAccessInfo
mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,TBAAAccessInfo InfoB)860 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
861 TBAAAccessInfo InfoB) {
862 if (!TBAA)
863 return TBAAAccessInfo();
864 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
865 }
866
867 TBAAAccessInfo
mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,TBAAAccessInfo SrcInfo)868 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
869 TBAAAccessInfo SrcInfo) {
870 if (!TBAA)
871 return TBAAAccessInfo();
872 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
873 }
874
DecorateInstructionWithTBAA(llvm::Instruction * Inst,TBAAAccessInfo TBAAInfo)875 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
876 TBAAAccessInfo TBAAInfo) {
877 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
878 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
879 }
880
DecorateInstructionWithInvariantGroup(llvm::Instruction * I,const CXXRecordDecl * RD)881 void CodeGenModule::DecorateInstructionWithInvariantGroup(
882 llvm::Instruction *I, const CXXRecordDecl *RD) {
883 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
884 llvm::MDNode::get(getLLVMContext(), {}));
885 }
886
Error(SourceLocation loc,StringRef message)887 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
888 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
889 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
890 }
891
892 /// ErrorUnsupported - Print out an error that codegen doesn't support the
893 /// specified stmt yet.
ErrorUnsupported(const Stmt * S,const char * Type)894 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
895 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
896 "cannot compile this %0 yet");
897 std::string Msg = Type;
898 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
899 << Msg << S->getSourceRange();
900 }
901
902 /// ErrorUnsupported - Print out an error that codegen doesn't support the
903 /// specified decl yet.
ErrorUnsupported(const Decl * D,const char * Type)904 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
905 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
906 "cannot compile this %0 yet");
907 std::string Msg = Type;
908 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
909 }
910
getSize(CharUnits size)911 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
912 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
913 }
914
setGlobalVisibility(llvm::GlobalValue * GV,const NamedDecl * D) const915 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
916 const NamedDecl *D) const {
917 if (GV->hasDLLImportStorageClass())
918 return;
919 // Internal definitions always have default visibility.
920 if (GV->hasLocalLinkage()) {
921 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
922 return;
923 }
924 if (!D)
925 return;
926 // Set visibility for definitions, and for declarations if requested globally
927 // or set explicitly.
928 LinkageInfo LV = D->getLinkageAndVisibility();
929 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
930 !GV->isDeclarationForLinker())
931 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
932 }
933
shouldAssumeDSOLocal(const CodeGenModule & CGM,llvm::GlobalValue * GV)934 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
935 llvm::GlobalValue *GV) {
936 if (GV->hasLocalLinkage())
937 return true;
938
939 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
940 return true;
941
942 // DLLImport explicitly marks the GV as external.
943 if (GV->hasDLLImportStorageClass())
944 return false;
945
946 const llvm::Triple &TT = CGM.getTriple();
947 if (TT.isWindowsGNUEnvironment()) {
948 // In MinGW, variables without DLLImport can still be automatically
949 // imported from a DLL by the linker; don't mark variables that
950 // potentially could come from another DLL as DSO local.
951 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
952 !GV->isThreadLocal())
953 return false;
954 }
955
956 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
957 // remain unresolved in the link, they can be resolved to zero, which is
958 // outside the current DSO.
959 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
960 return false;
961
962 // Every other GV is local on COFF.
963 // Make an exception for windows OS in the triple: Some firmware builds use
964 // *-win32-macho triples. This (accidentally?) produced windows relocations
965 // without GOT tables in older clang versions; Keep this behaviour.
966 // FIXME: even thread local variables?
967 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
968 return true;
969
970 // Only handle COFF and ELF for now.
971 if (!TT.isOSBinFormatELF())
972 return false;
973
974 // If this is not an executable, don't assume anything is local.
975 const auto &CGOpts = CGM.getCodeGenOpts();
976 llvm::Reloc::Model RM = CGOpts.RelocationModel;
977 const auto &LOpts = CGM.getLangOpts();
978 if (RM != llvm::Reloc::Static && !LOpts.PIE)
979 return false;
980
981 // A definition cannot be preempted from an executable.
982 if (!GV->isDeclarationForLinker())
983 return true;
984
985 // Most PIC code sequences that assume that a symbol is local cannot produce a
986 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
987 // depended, it seems worth it to handle it here.
988 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
989 return false;
990
991 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
992 llvm::Triple::ArchType Arch = TT.getArch();
993 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
994 Arch == llvm::Triple::ppc64le)
995 return false;
996
997 // If we can use copy relocations we can assume it is local.
998 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
999 if (!Var->isThreadLocal() &&
1000 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
1001 return true;
1002
1003 // If we can use a plt entry as the symbol address we can assume it
1004 // is local.
1005 // FIXME: This should work for PIE, but the gold linker doesn't support it.
1006 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
1007 return true;
1008
1009 // Otherwise don't assume it is local.
1010 return false;
1011 }
1012
setDSOLocal(llvm::GlobalValue * GV) const1013 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
1014 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
1015 }
1016
setDLLImportDLLExport(llvm::GlobalValue * GV,GlobalDecl GD) const1017 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1018 GlobalDecl GD) const {
1019 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
1020 // C++ destructors have a few C++ ABI specific special cases.
1021 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
1022 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
1023 return;
1024 }
1025 setDLLImportDLLExport(GV, D);
1026 }
1027
setDLLImportDLLExport(llvm::GlobalValue * GV,const NamedDecl * D) const1028 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
1029 const NamedDecl *D) const {
1030 if (D && D->isExternallyVisible()) {
1031 if (D->hasAttr<DLLImportAttr>())
1032 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1033 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
1034 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
1035 }
1036 }
1037
setGVProperties(llvm::GlobalValue * GV,GlobalDecl GD) const1038 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1039 GlobalDecl GD) const {
1040 setDLLImportDLLExport(GV, GD);
1041 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
1042 }
1043
setGVProperties(llvm::GlobalValue * GV,const NamedDecl * D) const1044 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
1045 const NamedDecl *D) const {
1046 setDLLImportDLLExport(GV, D);
1047 setGVPropertiesAux(GV, D);
1048 }
1049
setGVPropertiesAux(llvm::GlobalValue * GV,const NamedDecl * D) const1050 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
1051 const NamedDecl *D) const {
1052 setGlobalVisibility(GV, D);
1053 setDSOLocal(GV);
1054 GV->setPartition(CodeGenOpts.SymbolPartition);
1055 }
1056
GetLLVMTLSModel(StringRef S)1057 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
1058 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
1059 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
1060 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
1061 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
1062 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
1063 }
1064
1065 llvm::GlobalVariable::ThreadLocalMode
GetDefaultLLVMTLSModel() const1066 CodeGenModule::GetDefaultLLVMTLSModel() const {
1067 switch (CodeGenOpts.getDefaultTLSModel()) {
1068 case CodeGenOptions::GeneralDynamicTLSModel:
1069 return llvm::GlobalVariable::GeneralDynamicTLSModel;
1070 case CodeGenOptions::LocalDynamicTLSModel:
1071 return llvm::GlobalVariable::LocalDynamicTLSModel;
1072 case CodeGenOptions::InitialExecTLSModel:
1073 return llvm::GlobalVariable::InitialExecTLSModel;
1074 case CodeGenOptions::LocalExecTLSModel:
1075 return llvm::GlobalVariable::LocalExecTLSModel;
1076 }
1077 llvm_unreachable("Invalid TLS model!");
1078 }
1079
setTLSMode(llvm::GlobalValue * GV,const VarDecl & D) const1080 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
1081 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
1082
1083 llvm::GlobalValue::ThreadLocalMode TLM;
1084 TLM = GetDefaultLLVMTLSModel();
1085
1086 // Override the TLS model if it is explicitly specified.
1087 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
1088 TLM = GetLLVMTLSModel(Attr->getModel());
1089 }
1090
1091 GV->setThreadLocalMode(TLM);
1092 }
1093
getCPUSpecificMangling(const CodeGenModule & CGM,StringRef Name)1094 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
1095 StringRef Name) {
1096 const TargetInfo &Target = CGM.getTarget();
1097 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
1098 }
1099
AppendCPUSpecificCPUDispatchMangling(const CodeGenModule & CGM,const CPUSpecificAttr * Attr,unsigned CPUIndex,raw_ostream & Out)1100 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
1101 const CPUSpecificAttr *Attr,
1102 unsigned CPUIndex,
1103 raw_ostream &Out) {
1104 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
1105 // supported.
1106 if (Attr)
1107 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
1108 else if (CGM.getTarget().supportsIFunc())
1109 Out << ".resolver";
1110 }
1111
AppendTargetMangling(const CodeGenModule & CGM,const TargetAttr * Attr,raw_ostream & Out)1112 static void AppendTargetMangling(const CodeGenModule &CGM,
1113 const TargetAttr *Attr, raw_ostream &Out) {
1114 if (Attr->isDefaultVersion())
1115 return;
1116
1117 Out << '.';
1118 const TargetInfo &Target = CGM.getTarget();
1119 ParsedTargetAttr Info =
1120 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
1121 // Multiversioning doesn't allow "no-${feature}", so we can
1122 // only have "+" prefixes here.
1123 assert(LHS.startswith("+") && RHS.startswith("+") &&
1124 "Features should always have a prefix.");
1125 return Target.multiVersionSortPriority(LHS.substr(1)) >
1126 Target.multiVersionSortPriority(RHS.substr(1));
1127 });
1128
1129 bool IsFirst = true;
1130
1131 if (!Info.Architecture.empty()) {
1132 IsFirst = false;
1133 Out << "arch_" << Info.Architecture;
1134 }
1135
1136 for (StringRef Feat : Info.Features) {
1137 if (!IsFirst)
1138 Out << '_';
1139 IsFirst = false;
1140 Out << Feat.substr(1);
1141 }
1142 }
1143
getMangledNameImpl(const CodeGenModule & CGM,GlobalDecl GD,const NamedDecl * ND,bool OmitMultiVersionMangling=false)1144 static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
1145 const NamedDecl *ND,
1146 bool OmitMultiVersionMangling = false) {
1147 SmallString<256> Buffer;
1148 llvm::raw_svector_ostream Out(Buffer);
1149 MangleContext &MC = CGM.getCXXABI().getMangleContext();
1150 if (MC.shouldMangleDeclName(ND))
1151 MC.mangleName(GD.getWithDecl(ND), Out);
1152 else {
1153 IdentifierInfo *II = ND->getIdentifier();
1154 assert(II && "Attempt to mangle unnamed decl.");
1155 const auto *FD = dyn_cast<FunctionDecl>(ND);
1156
1157 if (FD &&
1158 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1159 Out << "__regcall3__" << II->getName();
1160 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() &&
1161 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) {
1162 Out << "__device_stub__" << II->getName();
1163 } else {
1164 Out << II->getName();
1165 }
1166 }
1167
1168 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1169 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1170 switch (FD->getMultiVersionKind()) {
1171 case MultiVersionKind::CPUDispatch:
1172 case MultiVersionKind::CPUSpecific:
1173 AppendCPUSpecificCPUDispatchMangling(CGM,
1174 FD->getAttr<CPUSpecificAttr>(),
1175 GD.getMultiVersionIndex(), Out);
1176 break;
1177 case MultiVersionKind::Target:
1178 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1179 break;
1180 case MultiVersionKind::None:
1181 llvm_unreachable("None multiversion type isn't valid here");
1182 }
1183 }
1184
1185 return std::string(Out.str());
1186 }
1187
UpdateMultiVersionNames(GlobalDecl GD,const FunctionDecl * FD)1188 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1189 const FunctionDecl *FD) {
1190 if (!FD->isMultiVersion())
1191 return;
1192
1193 // Get the name of what this would be without the 'target' attribute. This
1194 // allows us to lookup the version that was emitted when this wasn't a
1195 // multiversion function.
1196 std::string NonTargetName =
1197 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1198 GlobalDecl OtherGD;
1199 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1200 assert(OtherGD.getCanonicalDecl()
1201 .getDecl()
1202 ->getAsFunction()
1203 ->isMultiVersion() &&
1204 "Other GD should now be a multiversioned function");
1205 // OtherFD is the version of this function that was mangled BEFORE
1206 // becoming a MultiVersion function. It potentially needs to be updated.
1207 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1208 .getDecl()
1209 ->getAsFunction()
1210 ->getMostRecentDecl();
1211 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1212 // This is so that if the initial version was already the 'default'
1213 // version, we don't try to update it.
1214 if (OtherName != NonTargetName) {
1215 // Remove instead of erase, since others may have stored the StringRef
1216 // to this.
1217 const auto ExistingRecord = Manglings.find(NonTargetName);
1218 if (ExistingRecord != std::end(Manglings))
1219 Manglings.remove(&(*ExistingRecord));
1220 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1221 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1222 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1223 Entry->setName(OtherName);
1224 }
1225 }
1226 }
1227
getMangledName(GlobalDecl GD)1228 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1229 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1230
1231 // Some ABIs don't have constructor variants. Make sure that base and
1232 // complete constructors get mangled the same.
1233 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1234 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1235 CXXCtorType OrigCtorType = GD.getCtorType();
1236 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1237 if (OrigCtorType == Ctor_Base)
1238 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1239 }
1240 }
1241
1242 auto FoundName = MangledDeclNames.find(CanonicalGD);
1243 if (FoundName != MangledDeclNames.end())
1244 return FoundName->second;
1245
1246 // Keep the first result in the case of a mangling collision.
1247 const auto *ND = cast<NamedDecl>(GD.getDecl());
1248 std::string MangledName = getMangledNameImpl(*this, GD, ND);
1249
1250 // Ensure either we have different ABIs between host and device compilations,
1251 // says host compilation following MSVC ABI but device compilation follows
1252 // Itanium C++ ABI or, if they follow the same ABI, kernel names after
1253 // mangling should be the same after name stubbing. The later checking is
1254 // very important as the device kernel name being mangled in host-compilation
1255 // is used to resolve the device binaries to be executed. Inconsistent naming
1256 // result in undefined behavior. Even though we cannot check that naming
1257 // directly between host- and device-compilations, the host- and
1258 // device-mangling in host compilation could help catching certain ones.
1259 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() ||
1260 getLangOpts().CUDAIsDevice ||
1261 (getContext().getAuxTargetInfo() &&
1262 (getContext().getAuxTargetInfo()->getCXXABI() !=
1263 getContext().getTargetInfo().getCXXABI())) ||
1264 getCUDARuntime().getDeviceSideName(ND) ==
1265 getMangledNameImpl(
1266 *this,
1267 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel),
1268 ND));
1269
1270 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1271 return MangledDeclNames[CanonicalGD] = Result.first->first();
1272 }
1273
getBlockMangledName(GlobalDecl GD,const BlockDecl * BD)1274 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1275 const BlockDecl *BD) {
1276 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1277 const Decl *D = GD.getDecl();
1278
1279 SmallString<256> Buffer;
1280 llvm::raw_svector_ostream Out(Buffer);
1281 if (!D)
1282 MangleCtx.mangleGlobalBlock(BD,
1283 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1284 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1285 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1286 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1287 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1288 else
1289 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1290
1291 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1292 return Result.first->first();
1293 }
1294
GetGlobalValue(StringRef Name)1295 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1296 return getModule().getNamedValue(Name);
1297 }
1298
1299 /// AddGlobalCtor - Add a function to the list that will be called before
1300 /// main() runs.
AddGlobalCtor(llvm::Function * Ctor,int Priority,llvm::Constant * AssociatedData)1301 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1302 llvm::Constant *AssociatedData) {
1303 // FIXME: Type coercion of void()* types.
1304 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1305 }
1306
1307 /// AddGlobalDtor - Add a function to the list that will be called
1308 /// when the module is unloaded.
AddGlobalDtor(llvm::Function * Dtor,int Priority)1309 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1310 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1311 DtorsUsingAtExit[Priority].push_back(Dtor);
1312 return;
1313 }
1314
1315 // FIXME: Type coercion of void()* types.
1316 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1317 }
1318
EmitCtorList(CtorList & Fns,const char * GlobalName)1319 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1320 if (Fns.empty()) return;
1321
1322 // Ctor function type is void()*.
1323 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1324 unsigned CtorPtrAS = TheModule.getDataLayout().getProgramAddressSpace();
1325 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, CtorPtrAS);
1326
1327 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1328 llvm::StructType *CtorStructTy = llvm::StructType::get(
1329 Int32Ty, CtorPFTy, VoidPtrTy);
1330
1331 // Construct the constructor and destructor arrays.
1332 ConstantInitBuilder builder(*this);
1333 auto ctors = builder.beginArray(CtorStructTy);
1334 for (const auto &I : Fns) {
1335 auto ctor = ctors.beginStruct(CtorStructTy);
1336 ctor.addInt(Int32Ty, I.Priority);
1337 ctor.add(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(I.Initializer,
1338 CtorPFTy));
1339 if (I.AssociatedData)
1340 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1341 else
1342 ctor.addNullPointer(VoidPtrTy);
1343 ctor.finishAndAddTo(ctors);
1344 }
1345
1346 auto list =
1347 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1348 /*constant*/ false,
1349 llvm::GlobalValue::AppendingLinkage);
1350
1351 // The LTO linker doesn't seem to like it when we set an alignment
1352 // on appending variables. Take it off as a workaround.
1353 list->setAlignment(llvm::None);
1354
1355 Fns.clear();
1356 }
1357
1358 llvm::GlobalValue::LinkageTypes
getFunctionLinkage(GlobalDecl GD)1359 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1360 const auto *D = cast<FunctionDecl>(GD.getDecl());
1361
1362 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1363
1364 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1365 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1366
1367 if (isa<CXXConstructorDecl>(D) &&
1368 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1369 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1370 // Our approach to inheriting constructors is fundamentally different from
1371 // that used by the MS ABI, so keep our inheriting constructor thunks
1372 // internal rather than trying to pick an unambiguous mangling for them.
1373 return llvm::GlobalValue::InternalLinkage;
1374 }
1375
1376 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1377 }
1378
CreateCrossDsoCfiTypeId(llvm::Metadata * MD)1379 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1380 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1381 if (!MDS) return nullptr;
1382
1383 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1384 }
1385
SetLLVMFunctionAttributes(GlobalDecl GD,const CGFunctionInfo & Info,llvm::Function * F)1386 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1387 const CGFunctionInfo &Info,
1388 llvm::Function *F) {
1389 unsigned CallingConv;
1390 llvm::AttributeList PAL;
1391 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
1392 F->setAttributes(PAL);
1393 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1394 }
1395
removeImageAccessQualifier(std::string & TyName)1396 static void removeImageAccessQualifier(std::string& TyName) {
1397 std::string ReadOnlyQual("__read_only");
1398 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1399 if (ReadOnlyPos != std::string::npos)
1400 // "+ 1" for the space after access qualifier.
1401 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1402 else {
1403 std::string WriteOnlyQual("__write_only");
1404 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1405 if (WriteOnlyPos != std::string::npos)
1406 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1407 else {
1408 std::string ReadWriteQual("__read_write");
1409 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1410 if (ReadWritePos != std::string::npos)
1411 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1412 }
1413 }
1414 }
1415
1416 // Returns the address space id that should be produced to the
1417 // kernel_arg_addr_space metadata. This is always fixed to the ids
1418 // as specified in the SPIR 2.0 specification in order to differentiate
1419 // for example in clGetKernelArgInfo() implementation between the address
1420 // spaces with targets without unique mapping to the OpenCL address spaces
1421 // (basically all single AS CPUs).
ArgInfoAddressSpace(LangAS AS)1422 static unsigned ArgInfoAddressSpace(LangAS AS) {
1423 switch (AS) {
1424 case LangAS::opencl_global: return 1;
1425 case LangAS::opencl_constant: return 2;
1426 case LangAS::opencl_local: return 3;
1427 case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
1428 default:
1429 return 0; // Assume private.
1430 }
1431 }
1432
GenOpenCLArgMetadata(llvm::Function * Fn,const FunctionDecl * FD,CodeGenFunction * CGF)1433 void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
1434 const FunctionDecl *FD,
1435 CodeGenFunction *CGF) {
1436 assert(((FD && CGF) || (!FD && !CGF)) &&
1437 "Incorrect use - FD and CGF should either be both null or not!");
1438 // Create MDNodes that represent the kernel arg metadata.
1439 // Each MDNode is a list in the form of "key", N number of values which is
1440 // the same number of values as their are kernel arguments.
1441
1442 const PrintingPolicy &Policy = Context.getPrintingPolicy();
1443
1444 // MDNode for the kernel argument address space qualifiers.
1445 SmallVector<llvm::Metadata *, 8> addressQuals;
1446
1447 // MDNode for the kernel argument access qualifiers (images only).
1448 SmallVector<llvm::Metadata *, 8> accessQuals;
1449
1450 // MDNode for the kernel argument type names.
1451 SmallVector<llvm::Metadata *, 8> argTypeNames;
1452
1453 // MDNode for the kernel argument base type names.
1454 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1455
1456 // MDNode for the kernel argument type qualifiers.
1457 SmallVector<llvm::Metadata *, 8> argTypeQuals;
1458
1459 // MDNode for the kernel argument names.
1460 SmallVector<llvm::Metadata *, 8> argNames;
1461
1462 if (FD && CGF)
1463 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1464 const ParmVarDecl *parm = FD->getParamDecl(i);
1465 QualType ty = parm->getType();
1466 std::string typeQuals;
1467
1468 if (ty->isPointerType()) {
1469 QualType pointeeTy = ty->getPointeeType();
1470
1471 // Get address qualifier.
1472 addressQuals.push_back(
1473 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1474 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1475
1476 // Get argument type name.
1477 std::string typeName =
1478 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
1479
1480 // Turn "unsigned type" to "utype"
1481 std::string::size_type pos = typeName.find("unsigned");
1482 if (pointeeTy.isCanonical() && pos != std::string::npos)
1483 typeName.erase(pos + 1, 8);
1484
1485 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1486
1487 std::string baseTypeName =
1488 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
1489 Policy) +
1490 "*";
1491
1492 // Turn "unsigned type" to "utype"
1493 pos = baseTypeName.find("unsigned");
1494 if (pos != std::string::npos)
1495 baseTypeName.erase(pos + 1, 8);
1496
1497 argBaseTypeNames.push_back(
1498 llvm::MDString::get(VMContext, baseTypeName));
1499
1500 // Get argument type qualifiers:
1501 if (ty.isRestrictQualified())
1502 typeQuals = "restrict";
1503 if (pointeeTy.isConstQualified() ||
1504 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1505 typeQuals += typeQuals.empty() ? "const" : " const";
1506 if (pointeeTy.isVolatileQualified())
1507 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1508 } else {
1509 uint32_t AddrSpc = 0;
1510 bool isPipe = ty->isPipeType();
1511 if (ty->isImageType() || isPipe)
1512 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1513
1514 addressQuals.push_back(
1515 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1516
1517 // Get argument type name.
1518 std::string typeName;
1519 if (isPipe)
1520 typeName = ty.getCanonicalType()
1521 ->castAs<PipeType>()
1522 ->getElementType()
1523 .getAsString(Policy);
1524 else
1525 typeName = ty.getUnqualifiedType().getAsString(Policy);
1526
1527 // Turn "unsigned type" to "utype"
1528 std::string::size_type pos = typeName.find("unsigned");
1529 if (ty.isCanonical() && pos != std::string::npos)
1530 typeName.erase(pos + 1, 8);
1531
1532 std::string baseTypeName;
1533 if (isPipe)
1534 baseTypeName = ty.getCanonicalType()
1535 ->castAs<PipeType>()
1536 ->getElementType()
1537 .getCanonicalType()
1538 .getAsString(Policy);
1539 else
1540 baseTypeName =
1541 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
1542
1543 // Remove access qualifiers on images
1544 // (as they are inseparable from type in clang implementation,
1545 // but OpenCL spec provides a special query to get access qualifier
1546 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1547 if (ty->isImageType()) {
1548 removeImageAccessQualifier(typeName);
1549 removeImageAccessQualifier(baseTypeName);
1550 }
1551
1552 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1553
1554 // Turn "unsigned type" to "utype"
1555 pos = baseTypeName.find("unsigned");
1556 if (pos != std::string::npos)
1557 baseTypeName.erase(pos + 1, 8);
1558
1559 argBaseTypeNames.push_back(
1560 llvm::MDString::get(VMContext, baseTypeName));
1561
1562 if (isPipe)
1563 typeQuals = "pipe";
1564 }
1565
1566 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1567
1568 // Get image and pipe access qualifier:
1569 if (ty->isImageType() || ty->isPipeType()) {
1570 const Decl *PDecl = parm;
1571 if (auto *TD = dyn_cast<TypedefType>(ty))
1572 PDecl = TD->getDecl();
1573 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1574 if (A && A->isWriteOnly())
1575 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1576 else if (A && A->isReadWrite())
1577 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1578 else
1579 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1580 } else
1581 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1582
1583 // Get argument name.
1584 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1585 }
1586
1587 Fn->setMetadata("kernel_arg_addr_space",
1588 llvm::MDNode::get(VMContext, addressQuals));
1589 Fn->setMetadata("kernel_arg_access_qual",
1590 llvm::MDNode::get(VMContext, accessQuals));
1591 Fn->setMetadata("kernel_arg_type",
1592 llvm::MDNode::get(VMContext, argTypeNames));
1593 Fn->setMetadata("kernel_arg_base_type",
1594 llvm::MDNode::get(VMContext, argBaseTypeNames));
1595 Fn->setMetadata("kernel_arg_type_qual",
1596 llvm::MDNode::get(VMContext, argTypeQuals));
1597 if (getCodeGenOpts().EmitOpenCLArgMetadata)
1598 Fn->setMetadata("kernel_arg_name",
1599 llvm::MDNode::get(VMContext, argNames));
1600 }
1601
1602 /// Determines whether the language options require us to model
1603 /// unwind exceptions. We treat -fexceptions as mandating this
1604 /// except under the fragile ObjC ABI with only ObjC exceptions
1605 /// enabled. This means, for example, that C with -fexceptions
1606 /// enables this.
hasUnwindExceptions(const LangOptions & LangOpts)1607 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1608 // If exceptions are completely disabled, obviously this is false.
1609 if (!LangOpts.Exceptions) return false;
1610
1611 // If C++ exceptions are enabled, this is true.
1612 if (LangOpts.CXXExceptions) return true;
1613
1614 // If ObjC exceptions are enabled, this depends on the ABI.
1615 if (LangOpts.ObjCExceptions) {
1616 return LangOpts.ObjCRuntime.hasUnwindExceptions();
1617 }
1618
1619 return true;
1620 }
1621
requiresMemberFunctionPointerTypeMetadata(CodeGenModule & CGM,const CXXMethodDecl * MD)1622 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1623 const CXXMethodDecl *MD) {
1624 // Check that the type metadata can ever actually be used by a call.
1625 if (!CGM.getCodeGenOpts().LTOUnit ||
1626 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1627 return false;
1628
1629 // Only functions whose address can be taken with a member function pointer
1630 // need this sort of type metadata.
1631 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1632 !isa<CXXDestructorDecl>(MD);
1633 }
1634
1635 std::vector<const CXXRecordDecl *>
getMostBaseClasses(const CXXRecordDecl * RD)1636 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1637 llvm::SetVector<const CXXRecordDecl *> MostBases;
1638
1639 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1640 CollectMostBases = [&](const CXXRecordDecl *RD) {
1641 if (RD->getNumBases() == 0)
1642 MostBases.insert(RD);
1643 for (const CXXBaseSpecifier &B : RD->bases())
1644 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1645 };
1646 CollectMostBases(RD);
1647 return MostBases.takeVector();
1648 }
1649
SetLLVMFunctionAttributesForDefinition(const Decl * D,llvm::Function * F)1650 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1651 llvm::Function *F) {
1652 llvm::AttrBuilder B;
1653
1654 if (CodeGenOpts.UnwindTables)
1655 B.addAttribute(llvm::Attribute::UWTable);
1656
1657 if (CodeGenOpts.StackClashProtector)
1658 B.addAttribute("probe-stack", "inline-asm");
1659
1660 if (!hasUnwindExceptions(LangOpts))
1661 B.addAttribute(llvm::Attribute::NoUnwind);
1662
1663 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1664 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1665 B.addAttribute(llvm::Attribute::StackProtect);
1666 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1667 B.addAttribute(llvm::Attribute::StackProtectStrong);
1668 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1669 B.addAttribute(llvm::Attribute::StackProtectReq);
1670 }
1671
1672 if (!D) {
1673 // If we don't have a declaration to control inlining, the function isn't
1674 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1675 // disabled, mark the function as noinline.
1676 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1677 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1678 B.addAttribute(llvm::Attribute::NoInline);
1679
1680 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1681 return;
1682 }
1683
1684 // Track whether we need to add the optnone LLVM attribute,
1685 // starting with the default for this optimization level.
1686 bool ShouldAddOptNone =
1687 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1688 // We can't add optnone in the following cases, it won't pass the verifier.
1689 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1690 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1691
1692 // Add optnone, but do so only if the function isn't always_inline.
1693 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1694 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1695 B.addAttribute(llvm::Attribute::OptimizeNone);
1696
1697 // OptimizeNone implies noinline; we should not be inlining such functions.
1698 B.addAttribute(llvm::Attribute::NoInline);
1699
1700 // We still need to handle naked functions even though optnone subsumes
1701 // much of their semantics.
1702 if (D->hasAttr<NakedAttr>())
1703 B.addAttribute(llvm::Attribute::Naked);
1704
1705 // OptimizeNone wins over OptimizeForSize and MinSize.
1706 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1707 F->removeFnAttr(llvm::Attribute::MinSize);
1708 } else if (D->hasAttr<NakedAttr>()) {
1709 // Naked implies noinline: we should not be inlining such functions.
1710 B.addAttribute(llvm::Attribute::Naked);
1711 B.addAttribute(llvm::Attribute::NoInline);
1712 } else if (D->hasAttr<NoDuplicateAttr>()) {
1713 B.addAttribute(llvm::Attribute::NoDuplicate);
1714 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1715 // Add noinline if the function isn't always_inline.
1716 B.addAttribute(llvm::Attribute::NoInline);
1717 } else if (D->hasAttr<AlwaysInlineAttr>() &&
1718 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1719 // (noinline wins over always_inline, and we can't specify both in IR)
1720 B.addAttribute(llvm::Attribute::AlwaysInline);
1721 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1722 // If we're not inlining, then force everything that isn't always_inline to
1723 // carry an explicit noinline attribute.
1724 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1725 B.addAttribute(llvm::Attribute::NoInline);
1726 } else {
1727 // Otherwise, propagate the inline hint attribute and potentially use its
1728 // absence to mark things as noinline.
1729 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1730 // Search function and template pattern redeclarations for inline.
1731 auto CheckForInline = [](const FunctionDecl *FD) {
1732 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1733 return Redecl->isInlineSpecified();
1734 };
1735 if (any_of(FD->redecls(), CheckRedeclForInline))
1736 return true;
1737 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1738 if (!Pattern)
1739 return false;
1740 return any_of(Pattern->redecls(), CheckRedeclForInline);
1741 };
1742 if (CheckForInline(FD)) {
1743 B.addAttribute(llvm::Attribute::InlineHint);
1744 } else if (CodeGenOpts.getInlining() ==
1745 CodeGenOptions::OnlyHintInlining &&
1746 !FD->isInlined() &&
1747 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1748 B.addAttribute(llvm::Attribute::NoInline);
1749 }
1750 }
1751 }
1752
1753 // Add other optimization related attributes if we are optimizing this
1754 // function.
1755 if (!D->hasAttr<OptimizeNoneAttr>()) {
1756 if (D->hasAttr<ColdAttr>()) {
1757 if (!ShouldAddOptNone)
1758 B.addAttribute(llvm::Attribute::OptimizeForSize);
1759 B.addAttribute(llvm::Attribute::Cold);
1760 }
1761
1762 if (D->hasAttr<MinSizeAttr>())
1763 B.addAttribute(llvm::Attribute::MinSize);
1764 }
1765
1766 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1767
1768 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1769 if (alignment)
1770 F->setAlignment(llvm::Align(alignment));
1771
1772 if (!D->hasAttr<AlignedAttr>())
1773 if (LangOpts.FunctionAlignment)
1774 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
1775
1776 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1777 // reserve a bit for differentiating between virtual and non-virtual member
1778 // functions. If the current target's C++ ABI requires this and this is a
1779 // member function, set its alignment accordingly.
1780 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1781 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1782 F->setAlignment(llvm::Align(2));
1783 }
1784
1785 // In the cross-dso CFI mode with canonical jump tables, we want !type
1786 // attributes on definitions only.
1787 if (CodeGenOpts.SanitizeCfiCrossDso &&
1788 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1789 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1790 // Skip available_externally functions. They won't be codegen'ed in the
1791 // current module anyway.
1792 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
1793 CreateFunctionTypeMetadataForIcall(FD, F);
1794 }
1795 }
1796
1797 // Emit type metadata on member functions for member function pointer checks.
1798 // These are only ever necessary on definitions; we're guaranteed that the
1799 // definition will be present in the LTO unit as a result of LTO visibility.
1800 auto *MD = dyn_cast<CXXMethodDecl>(D);
1801 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1802 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1803 llvm::Metadata *Id =
1804 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1805 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1806 F->addTypeMetadata(0, Id);
1807 }
1808 }
1809 }
1810
SetCommonAttributes(GlobalDecl GD,llvm::GlobalValue * GV)1811 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1812 const Decl *D = GD.getDecl();
1813 if (dyn_cast_or_null<NamedDecl>(D))
1814 setGVProperties(GV, GD);
1815 else
1816 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1817
1818 if (D && D->hasAttr<UsedAttr>())
1819 addUsedGlobal(GV);
1820
1821 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1822 const auto *VD = cast<VarDecl>(D);
1823 if (VD->getType().isConstQualified() &&
1824 VD->getStorageDuration() == SD_Static)
1825 addUsedGlobal(GV);
1826 }
1827 }
1828
GetCPUAndFeaturesAttributes(GlobalDecl GD,llvm::AttrBuilder & Attrs)1829 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
1830 llvm::AttrBuilder &Attrs) {
1831 // Add target-cpu and target-features attributes to functions. If
1832 // we have a decl for the function and it has a target attribute then
1833 // parse that and add it to the feature set.
1834 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1835 std::vector<std::string> Features;
1836 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
1837 FD = FD ? FD->getMostRecentDecl() : FD;
1838 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1839 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1840 bool AddedAttr = false;
1841 if (TD || SD) {
1842 llvm::StringMap<bool> FeatureMap;
1843 getContext().getFunctionFeatureMap(FeatureMap, GD);
1844
1845 // Produce the canonical string for this set of features.
1846 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1847 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1848
1849 // Now add the target-cpu and target-features to the function.
1850 // While we populated the feature map above, we still need to
1851 // get and parse the target attribute so we can get the cpu for
1852 // the function.
1853 if (TD) {
1854 ParsedTargetAttr ParsedAttr = TD->parse();
1855 if (ParsedAttr.Architecture != "" &&
1856 getTarget().isValidCPUName(ParsedAttr.Architecture))
1857 TargetCPU = ParsedAttr.Architecture;
1858 }
1859 } else {
1860 // Otherwise just add the existing target cpu and target features to the
1861 // function.
1862 Features = getTarget().getTargetOpts().Features;
1863 }
1864
1865 if (TargetCPU != "") {
1866 Attrs.addAttribute("target-cpu", TargetCPU);
1867 AddedAttr = true;
1868 }
1869 if (!Features.empty()) {
1870 llvm::sort(Features);
1871 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1872 AddedAttr = true;
1873 }
1874
1875 return AddedAttr;
1876 }
1877
setNonAliasAttributes(GlobalDecl GD,llvm::GlobalObject * GO)1878 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1879 llvm::GlobalObject *GO) {
1880 const Decl *D = GD.getDecl();
1881 SetCommonAttributes(GD, GO);
1882
1883 if (D) {
1884 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1885 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1886 GV->addAttribute("bss-section", SA->getName());
1887 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1888 GV->addAttribute("data-section", SA->getName());
1889 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1890 GV->addAttribute("rodata-section", SA->getName());
1891 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
1892 GV->addAttribute("relro-section", SA->getName());
1893 }
1894
1895 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1896 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1897 if (!D->getAttr<SectionAttr>())
1898 F->addFnAttr("implicit-section-name", SA->getName());
1899
1900 llvm::AttrBuilder Attrs;
1901 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
1902 // We know that GetCPUAndFeaturesAttributes will always have the
1903 // newest set, since it has the newest possible FunctionDecl, so the
1904 // new ones should replace the old.
1905 F->removeFnAttr("target-cpu");
1906 F->removeFnAttr("target-features");
1907 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1908 }
1909 }
1910
1911 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1912 GO->setSection(CSA->getName());
1913 else if (const auto *SA = D->getAttr<SectionAttr>())
1914 GO->setSection(SA->getName());
1915 }
1916
1917 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1918 }
1919
SetInternalFunctionAttributes(GlobalDecl GD,llvm::Function * F,const CGFunctionInfo & FI)1920 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1921 llvm::Function *F,
1922 const CGFunctionInfo &FI) {
1923 const Decl *D = GD.getDecl();
1924 SetLLVMFunctionAttributes(GD, FI, F);
1925 SetLLVMFunctionAttributesForDefinition(D, F);
1926
1927 F->setLinkage(llvm::Function::InternalLinkage);
1928
1929 setNonAliasAttributes(GD, F);
1930 }
1931
setLinkageForGV(llvm::GlobalValue * GV,const NamedDecl * ND)1932 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1933 // Set linkage and visibility in case we never see a definition.
1934 LinkageInfo LV = ND->getLinkageAndVisibility();
1935 // Don't set internal linkage on declarations.
1936 // "extern_weak" is overloaded in LLVM; we probably should have
1937 // separate linkage types for this.
1938 if (isExternallyVisible(LV.getLinkage()) &&
1939 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1940 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1941 }
1942
CreateFunctionTypeMetadataForIcall(const FunctionDecl * FD,llvm::Function * F)1943 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1944 llvm::Function *F) {
1945 // Only if we are checking indirect calls.
1946 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1947 return;
1948
1949 // Non-static class methods are handled via vtable or member function pointer
1950 // checks elsewhere.
1951 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1952 return;
1953
1954 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1955 F->addTypeMetadata(0, MD);
1956 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1957
1958 // Emit a hash-based bit set entry for cross-DSO calls.
1959 if (CodeGenOpts.SanitizeCfiCrossDso)
1960 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1961 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1962 }
1963
SetFunctionAttributes(GlobalDecl GD,llvm::Function * F,bool IsIncompleteFunction,bool IsThunk)1964 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1965 bool IsIncompleteFunction,
1966 bool IsThunk) {
1967
1968 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1969 // If this is an intrinsic function, set the function's attributes
1970 // to the intrinsic's attributes.
1971 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1972 return;
1973 }
1974
1975 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1976
1977 if (!IsIncompleteFunction)
1978 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
1979
1980 // Add the Returned attribute for "this", except for iOS 5 and earlier
1981 // where substantial code, including the libstdc++ dylib, was compiled with
1982 // GCC and does not actually return "this".
1983 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1984 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1985 assert(!F->arg_empty() &&
1986 F->arg_begin()->getType()
1987 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1988 "unexpected this return");
1989 F->addAttribute(1, llvm::Attribute::Returned);
1990 }
1991
1992 // Only a few attributes are set on declarations; these may later be
1993 // overridden by a definition.
1994
1995 setLinkageForGV(F, FD);
1996 setGVProperties(F, FD);
1997
1998 // Setup target-specific attributes.
1999 if (!IsIncompleteFunction && F->isDeclaration())
2000 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
2001
2002 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
2003 F->setSection(CSA->getName());
2004 else if (const auto *SA = FD->getAttr<SectionAttr>())
2005 F->setSection(SA->getName());
2006
2007 // If we plan on emitting this inline builtin, we can't treat it as a builtin.
2008 if (FD->isInlineBuiltinDeclaration()) {
2009 const FunctionDecl *FDBody;
2010 bool HasBody = FD->hasBody(FDBody);
2011 (void)HasBody;
2012 assert(HasBody && "Inline builtin declarations should always have an "
2013 "available body!");
2014 if (shouldEmitFunction(FDBody))
2015 F->addAttribute(llvm::AttributeList::FunctionIndex,
2016 llvm::Attribute::NoBuiltin);
2017 }
2018
2019 if (FD->isReplaceableGlobalAllocationFunction()) {
2020 // A replaceable global allocation function does not act like a builtin by
2021 // default, only if it is invoked by a new-expression or delete-expression.
2022 F->addAttribute(llvm::AttributeList::FunctionIndex,
2023 llvm::Attribute::NoBuiltin);
2024 }
2025
2026 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
2027 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2028 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
2029 if (MD->isVirtual())
2030 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2031
2032 // Don't emit entries for function declarations in the cross-DSO mode. This
2033 // is handled with better precision by the receiving DSO. But if jump tables
2034 // are non-canonical then we need type metadata in order to produce the local
2035 // jump table.
2036 if (!CodeGenOpts.SanitizeCfiCrossDso ||
2037 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
2038 CreateFunctionTypeMetadataForIcall(FD, F);
2039
2040 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
2041 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
2042
2043 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
2044 // Annotate the callback behavior as metadata:
2045 // - The callback callee (as argument number).
2046 // - The callback payloads (as argument numbers).
2047 llvm::LLVMContext &Ctx = F->getContext();
2048 llvm::MDBuilder MDB(Ctx);
2049
2050 // The payload indices are all but the first one in the encoding. The first
2051 // identifies the callback callee.
2052 int CalleeIdx = *CB->encoding_begin();
2053 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
2054 F->addMetadata(llvm::LLVMContext::MD_callback,
2055 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2056 CalleeIdx, PayloadIndices,
2057 /* VarArgsArePassed */ false)}));
2058 }
2059 }
2060
addUsedGlobal(llvm::GlobalValue * GV)2061 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
2062 assert(!GV->isDeclaration() &&
2063 "Only globals with definition can force usage.");
2064 LLVMUsed.emplace_back(GV);
2065 }
2066
addCompilerUsedGlobal(llvm::GlobalValue * GV)2067 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
2068 assert(!GV->isDeclaration() &&
2069 "Only globals with definition can force usage.");
2070 LLVMCompilerUsed.emplace_back(GV);
2071 }
2072
emitUsed(CodeGenModule & CGM,StringRef Name,std::vector<llvm::WeakTrackingVH> & List)2073 static void emitUsed(CodeGenModule &CGM, StringRef Name,
2074 std::vector<llvm::WeakTrackingVH> &List) {
2075 llvm::PointerType *UsedPtrTy = CGM.Int8Ty->getPointerTo(0);
2076 // Don't create llvm.used if there is no need.
2077 if (List.empty())
2078 return;
2079
2080 // Convert List to what ConstantArray needs.
2081 SmallVector<llvm::Constant*, 8> UsedArray;
2082 UsedArray.resize(List.size());
2083 for (unsigned i = 0, e = List.size(); i != e; ++i) {
2084 UsedArray[i] =
2085 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
2086 cast<llvm::Constant>(&*List[i]), UsedPtrTy);
2087 }
2088
2089 if (UsedArray.empty())
2090 return;
2091 llvm::ArrayType *ATy = llvm::ArrayType::get(UsedPtrTy, UsedArray.size());
2092
2093 auto *GV = new llvm::GlobalVariable(
2094 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
2095 llvm::ConstantArray::get(ATy, UsedArray), Name);
2096
2097 GV->setSection("llvm.metadata");
2098 }
2099
emitLLVMUsed()2100 void CodeGenModule::emitLLVMUsed() {
2101 emitUsed(*this, "llvm.used", LLVMUsed);
2102 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
2103 }
2104
AppendLinkerOptions(StringRef Opts)2105 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
2106 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
2107 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2108 }
2109
AddDetectMismatch(StringRef Name,StringRef Value)2110 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
2111 llvm::SmallString<32> Opt;
2112 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
2113 if (Opt.empty())
2114 return;
2115 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2116 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
2117 }
2118
AddDependentLib(StringRef Lib)2119 void CodeGenModule::AddDependentLib(StringRef Lib) {
2120 auto &C = getLLVMContext();
2121 if (getTarget().getTriple().isOSBinFormatELF()) {
2122 ELFDependentLibraries.push_back(
2123 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
2124 return;
2125 }
2126
2127 llvm::SmallString<24> Opt;
2128 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
2129 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
2130 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
2131 }
2132
2133 /// Add link options implied by the given module, including modules
2134 /// it depends on, using a postorder walk.
addLinkOptionsPostorder(CodeGenModule & CGM,Module * Mod,SmallVectorImpl<llvm::MDNode * > & Metadata,llvm::SmallPtrSet<Module *,16> & Visited)2135 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
2136 SmallVectorImpl<llvm::MDNode *> &Metadata,
2137 llvm::SmallPtrSet<Module *, 16> &Visited) {
2138 // Import this module's parent.
2139 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
2140 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
2141 }
2142
2143 // Import this module's dependencies.
2144 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
2145 if (Visited.insert(Mod->Imports[I - 1]).second)
2146 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
2147 }
2148
2149 // Add linker options to link against the libraries/frameworks
2150 // described by this module.
2151 llvm::LLVMContext &Context = CGM.getLLVMContext();
2152 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
2153
2154 // For modules that use export_as for linking, use that module
2155 // name instead.
2156 if (Mod->UseExportAsModuleLinkName)
2157 return;
2158
2159 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
2160 // Link against a framework. Frameworks are currently Darwin only, so we
2161 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2162 if (Mod->LinkLibraries[I-1].IsFramework) {
2163 llvm::Metadata *Args[2] = {
2164 llvm::MDString::get(Context, "-framework"),
2165 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
2166
2167 Metadata.push_back(llvm::MDNode::get(Context, Args));
2168 continue;
2169 }
2170
2171 // Link against a library.
2172 if (IsELF) {
2173 llvm::Metadata *Args[2] = {
2174 llvm::MDString::get(Context, "lib"),
2175 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
2176 };
2177 Metadata.push_back(llvm::MDNode::get(Context, Args));
2178 } else {
2179 llvm::SmallString<24> Opt;
2180 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
2181 Mod->LinkLibraries[I - 1].Library, Opt);
2182 auto *OptString = llvm::MDString::get(Context, Opt);
2183 Metadata.push_back(llvm::MDNode::get(Context, OptString));
2184 }
2185 }
2186 }
2187
EmitModuleLinkOptions()2188 void CodeGenModule::EmitModuleLinkOptions() {
2189 // Collect the set of all of the modules we want to visit to emit link
2190 // options, which is essentially the imported modules and all of their
2191 // non-explicit child modules.
2192 llvm::SetVector<clang::Module *> LinkModules;
2193 llvm::SmallPtrSet<clang::Module *, 16> Visited;
2194 SmallVector<clang::Module *, 16> Stack;
2195
2196 // Seed the stack with imported modules.
2197 for (Module *M : ImportedModules) {
2198 // Do not add any link flags when an implementation TU of a module imports
2199 // a header of that same module.
2200 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2201 !getLangOpts().isCompilingModule())
2202 continue;
2203 if (Visited.insert(M).second)
2204 Stack.push_back(M);
2205 }
2206
2207 // Find all of the modules to import, making a little effort to prune
2208 // non-leaf modules.
2209 while (!Stack.empty()) {
2210 clang::Module *Mod = Stack.pop_back_val();
2211
2212 bool AnyChildren = false;
2213
2214 // Visit the submodules of this module.
2215 for (const auto &SM : Mod->submodules()) {
2216 // Skip explicit children; they need to be explicitly imported to be
2217 // linked against.
2218 if (SM->IsExplicit)
2219 continue;
2220
2221 if (Visited.insert(SM).second) {
2222 Stack.push_back(SM);
2223 AnyChildren = true;
2224 }
2225 }
2226
2227 // We didn't find any children, so add this module to the list of
2228 // modules to link against.
2229 if (!AnyChildren) {
2230 LinkModules.insert(Mod);
2231 }
2232 }
2233
2234 // Add link options for all of the imported modules in reverse topological
2235 // order. We don't do anything to try to order import link flags with respect
2236 // to linker options inserted by things like #pragma comment().
2237 SmallVector<llvm::MDNode *, 16> MetadataArgs;
2238 Visited.clear();
2239 for (Module *M : LinkModules)
2240 if (Visited.insert(M).second)
2241 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2242 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2243 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2244
2245 // Add the linker options metadata flag.
2246 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2247 for (auto *MD : LinkerOptionsMetadata)
2248 NMD->addOperand(MD);
2249 }
2250
EmitDeferred()2251 void CodeGenModule::EmitDeferred() {
2252 // Emit deferred declare target declarations.
2253 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2254 getOpenMPRuntime().emitDeferredTargetDecls();
2255
2256 // Emit code for any potentially referenced deferred decls. Since a
2257 // previously unused static decl may become used during the generation of code
2258 // for a static function, iterate until no changes are made.
2259
2260 if (!DeferredVTables.empty()) {
2261 EmitDeferredVTables();
2262
2263 // Emitting a vtable doesn't directly cause more vtables to
2264 // become deferred, although it can cause functions to be
2265 // emitted that then need those vtables.
2266 assert(DeferredVTables.empty());
2267 }
2268
2269 // Stop if we're out of both deferred vtables and deferred declarations.
2270 if (DeferredDeclsToEmit.empty())
2271 return;
2272
2273 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2274 // work, it will not interfere with this.
2275 std::vector<GlobalDecl> CurDeclsToEmit;
2276 CurDeclsToEmit.swap(DeferredDeclsToEmit);
2277
2278 for (GlobalDecl &D : CurDeclsToEmit) {
2279 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2280 // to get GlobalValue with exactly the type we need, not something that
2281 // might had been created for another decl with the same mangled name but
2282 // different type.
2283 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2284 GetAddrOfGlobal(D, ForDefinition));
2285
2286 // In case of different address spaces, we may still get a cast, even with
2287 // IsForDefinition equal to true. Query mangled names table to get
2288 // GlobalValue.
2289 if (!GV)
2290 GV = GetGlobalValue(getMangledName(D));
2291
2292 // Make sure GetGlobalValue returned non-null.
2293 assert(GV);
2294
2295 // Check to see if we've already emitted this. This is necessary
2296 // for a couple of reasons: first, decls can end up in the
2297 // deferred-decls queue multiple times, and second, decls can end
2298 // up with definitions in unusual ways (e.g. by an extern inline
2299 // function acquiring a strong function redefinition). Just
2300 // ignore these cases.
2301 if (!GV->isDeclaration())
2302 continue;
2303
2304 // If this is OpenMP, check if it is legal to emit this global normally.
2305 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2306 continue;
2307
2308 // Otherwise, emit the definition and move on to the next one.
2309 EmitGlobalDefinition(D, GV);
2310
2311 // If we found out that we need to emit more decls, do that recursively.
2312 // This has the advantage that the decls are emitted in a DFS and related
2313 // ones are close together, which is convenient for testing.
2314 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2315 EmitDeferred();
2316 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2317 }
2318 }
2319 }
2320
EmitVTablesOpportunistically()2321 void CodeGenModule::EmitVTablesOpportunistically() {
2322 // Try to emit external vtables as available_externally if they have emitted
2323 // all inlined virtual functions. It runs after EmitDeferred() and therefore
2324 // is not allowed to create new references to things that need to be emitted
2325 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2326
2327 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2328 && "Only emit opportunistic vtables with optimizations");
2329
2330 for (const CXXRecordDecl *RD : OpportunisticVTables) {
2331 assert(getVTables().isVTableExternal(RD) &&
2332 "This queue should only contain external vtables");
2333 if (getCXXABI().canSpeculativelyEmitVTable(RD))
2334 VTables.GenerateClassData(RD);
2335 }
2336 OpportunisticVTables.clear();
2337 }
2338
EmitGlobalAnnotations()2339 void CodeGenModule::EmitGlobalAnnotations() {
2340 if (Annotations.empty())
2341 return;
2342
2343 // Create a new global variable for the ConstantStruct in the Module.
2344 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2345 Annotations[0]->getType(), Annotations.size()), Annotations);
2346 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2347 llvm::GlobalValue::AppendingLinkage,
2348 Array, "llvm.global.annotations");
2349 gv->setSection(AnnotationSection);
2350 }
2351
EmitAnnotationString(StringRef Str)2352 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2353 llvm::Constant *&AStr = AnnotationStrings[Str];
2354 if (AStr)
2355 return AStr;
2356
2357 // Not found yet, create a new global.
2358 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2359 auto *gv = new llvm::GlobalVariable(getModule(), s->getType(),
2360 true, llvm::GlobalValue::PrivateLinkage, s, ".str", nullptr,
2361 llvm::GlobalVariable::NotThreadLocal, getTargetCodeGenInfo().getDefaultAS());
2362 gv->setSection(AnnotationSection);
2363 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2364 AStr = gv;
2365 return gv;
2366 }
2367
EmitAnnotationUnit(SourceLocation Loc)2368 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2369 SourceManager &SM = getContext().getSourceManager();
2370 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2371 if (PLoc.isValid())
2372 return EmitAnnotationString(PLoc.getFilename());
2373 return EmitAnnotationString(SM.getBufferName(Loc));
2374 }
2375
EmitAnnotationLineNo(SourceLocation L)2376 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2377 SourceManager &SM = getContext().getSourceManager();
2378 PresumedLoc PLoc = SM.getPresumedLoc(L);
2379 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2380 SM.getExpansionLineNumber(L);
2381 return llvm::ConstantInt::get(Int32Ty, LineNo);
2382 }
2383
EmitAnnotateAttr(llvm::GlobalValue * GV,const AnnotateAttr * AA,SourceLocation L)2384 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2385 const AnnotateAttr *AA,
2386 SourceLocation L) {
2387 // Get the globals for file name, annotation, and the line number.
2388 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2389 *UnitGV = EmitAnnotationUnit(L),
2390 *LineNoCst = EmitAnnotationLineNo(L);
2391
2392 llvm::Constant *ASZeroGV = GV;
2393 if (GV->getAddressSpace() != 0) {
2394 ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2395 GV, GV->getValueType()->getPointerTo(0));
2396 }
2397
2398 // Create the ConstantStruct for the global annotation.
2399 llvm::Constant *Fields[4] = {
2400 llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
2401 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2402 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2403 LineNoCst
2404 };
2405 return llvm::ConstantStruct::getAnon(Fields);
2406 }
2407
AddGlobalAnnotations(const ValueDecl * D,llvm::GlobalValue * GV)2408 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2409 llvm::GlobalValue *GV) {
2410 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2411 // Get the struct elements for these annotations.
2412 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2413 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2414 }
2415
isInSanitizerBlacklist(SanitizerMask Kind,llvm::Function * Fn,SourceLocation Loc) const2416 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
2417 llvm::Function *Fn,
2418 SourceLocation Loc) const {
2419 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2420 // Blacklist by function name.
2421 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
2422 return true;
2423 // Blacklist by location.
2424 if (Loc.isValid())
2425 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
2426 // If location is unknown, this may be a compiler-generated function. Assume
2427 // it's located in the main file.
2428 auto &SM = Context.getSourceManager();
2429 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2430 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
2431 }
2432 return false;
2433 }
2434
isInSanitizerBlacklist(llvm::GlobalVariable * GV,SourceLocation Loc,QualType Ty,StringRef Category) const2435 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
2436 SourceLocation Loc, QualType Ty,
2437 StringRef Category) const {
2438 // For now globals can be blacklisted only in ASan and KASan.
2439 const SanitizerMask EnabledAsanMask =
2440 LangOpts.Sanitize.Mask &
2441 (SanitizerKind::Address | SanitizerKind::KernelAddress |
2442 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2443 SanitizerKind::MemTag);
2444 if (!EnabledAsanMask)
2445 return false;
2446 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2447 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
2448 return true;
2449 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
2450 return true;
2451 // Check global type.
2452 if (!Ty.isNull()) {
2453 // Drill down the array types: if global variable of a fixed type is
2454 // blacklisted, we also don't instrument arrays of them.
2455 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2456 Ty = AT->getElementType();
2457 Ty = Ty.getCanonicalType().getUnqualifiedType();
2458 // We allow to blacklist only record types (classes, structs etc.)
2459 if (Ty->isRecordType()) {
2460 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2461 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
2462 return true;
2463 }
2464 }
2465 return false;
2466 }
2467
imbueXRayAttrs(llvm::Function * Fn,SourceLocation Loc,StringRef Category) const2468 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2469 StringRef Category) const {
2470 const auto &XRayFilter = getContext().getXRayFilter();
2471 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2472 auto Attr = ImbueAttr::NONE;
2473 if (Loc.isValid())
2474 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2475 if (Attr == ImbueAttr::NONE)
2476 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2477 switch (Attr) {
2478 case ImbueAttr::NONE:
2479 return false;
2480 case ImbueAttr::ALWAYS:
2481 Fn->addFnAttr("function-instrument", "xray-always");
2482 break;
2483 case ImbueAttr::ALWAYS_ARG1:
2484 Fn->addFnAttr("function-instrument", "xray-always");
2485 Fn->addFnAttr("xray-log-args", "1");
2486 break;
2487 case ImbueAttr::NEVER:
2488 Fn->addFnAttr("function-instrument", "xray-never");
2489 break;
2490 }
2491 return true;
2492 }
2493
MustBeEmitted(const ValueDecl * Global)2494 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2495 // Never defer when EmitAllDecls is specified.
2496 if (LangOpts.EmitAllDecls)
2497 return true;
2498
2499 if (CodeGenOpts.KeepStaticConsts) {
2500 const auto *VD = dyn_cast<VarDecl>(Global);
2501 if (VD && VD->getType().isConstQualified() &&
2502 VD->getStorageDuration() == SD_Static)
2503 return true;
2504 }
2505
2506 return getContext().DeclMustBeEmitted(Global);
2507 }
2508
MayBeEmittedEagerly(const ValueDecl * Global)2509 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2510 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2511 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2512 // Implicit template instantiations may change linkage if they are later
2513 // explicitly instantiated, so they should not be emitted eagerly.
2514 return false;
2515 // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
2516 // not emit them eagerly unless we sure that the function must be emitted on
2517 // the host.
2518 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
2519 !LangOpts.OpenMPIsDevice &&
2520 !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
2521 !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
2522 return false;
2523 }
2524 if (const auto *VD = dyn_cast<VarDecl>(Global))
2525 if (Context.getInlineVariableDefinitionKind(VD) ==
2526 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2527 // A definition of an inline constexpr static data member may change
2528 // linkage later if it's redeclared outside the class.
2529 return false;
2530 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2531 // codegen for global variables, because they may be marked as threadprivate.
2532 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2533 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2534 !isTypeConstant(Global->getType(), false) &&
2535 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2536 return false;
2537
2538 return true;
2539 }
2540
GetAddrOfMSGuidDecl(const MSGuidDecl * GD)2541 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) {
2542 StringRef Name = getMangledName(GD);
2543
2544 // The UUID descriptor should be pointer aligned.
2545 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2546
2547 // Look for an existing global.
2548 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2549 return ConstantAddress(GV, Alignment);
2550
2551 ConstantEmitter Emitter(*this);
2552 llvm::Constant *Init;
2553
2554 APValue &V = GD->getAsAPValue();
2555 if (!V.isAbsent()) {
2556 // If possible, emit the APValue version of the initializer. In particular,
2557 // this gets the type of the constant right.
2558 Init = Emitter.emitForInitializer(
2559 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType());
2560 } else {
2561 // As a fallback, directly construct the constant.
2562 // FIXME: This may get padding wrong under esoteric struct layout rules.
2563 // MSVC appears to create a complete type 'struct __s_GUID' that it
2564 // presumably uses to represent these constants.
2565 MSGuidDecl::Parts Parts = GD->getParts();
2566 llvm::Constant *Fields[4] = {
2567 llvm::ConstantInt::get(Int32Ty, Parts.Part1),
2568 llvm::ConstantInt::get(Int16Ty, Parts.Part2),
2569 llvm::ConstantInt::get(Int16Ty, Parts.Part3),
2570 llvm::ConstantDataArray::getRaw(
2571 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8,
2572 Int8Ty)};
2573 Init = llvm::ConstantStruct::getAnon(Fields);
2574 }
2575
2576 auto *GV = new llvm::GlobalVariable(
2577 getModule(), Init->getType(),
2578 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2579 if (supportsCOMDAT())
2580 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2581 setDSOLocal(GV);
2582
2583 llvm::Constant *Addr = GV;
2584 if (!V.isAbsent()) {
2585 Emitter.finalize(GV);
2586 } else {
2587 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType());
2588 Addr = llvm::ConstantExpr::getBitCast(
2589 GV, Ty->getPointerTo(GV->getAddressSpace()));
2590 }
2591 return ConstantAddress(Addr, Alignment);
2592 }
2593
GetWeakRefReference(const ValueDecl * VD)2594 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2595 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2596 assert(AA && "No alias?");
2597
2598 CharUnits Alignment = getContext().getDeclAlign(VD);
2599 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2600
2601 // See if there is already something with the target's name in the module.
2602 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2603 unsigned AS = getAddressSpaceForType(VD->getType());
2604 if (Entry) {
2605 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2606 return ConstantAddress(Ptr, Alignment);
2607 }
2608
2609 llvm::Constant *Aliasee;
2610 if (isa<llvm::FunctionType>(DeclTy))
2611 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2612 GlobalDecl(cast<FunctionDecl>(VD)),
2613 /*ForVTable=*/false);
2614 else
2615 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2616 llvm::PointerType::get(DeclTy, AS),
2617 nullptr);
2618
2619 auto *F = cast<llvm::GlobalValue>(Aliasee);
2620 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2621 WeakRefReferences.insert(F);
2622
2623 return ConstantAddress(Aliasee, Alignment);
2624 }
2625
EmitGlobal(GlobalDecl GD)2626 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2627 const auto *Global = cast<ValueDecl>(GD.getDecl());
2628
2629 // Weak references don't produce any output by themselves.
2630 if (Global->hasAttr<WeakRefAttr>())
2631 return;
2632
2633 // If this is an alias definition (which otherwise looks like a declaration)
2634 // emit it now.
2635 if (Global->hasAttr<AliasAttr>())
2636 return EmitAliasDefinition(GD);
2637
2638 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2639 if (Global->hasAttr<IFuncAttr>())
2640 return emitIFuncDefinition(GD);
2641
2642 // If this is a cpu_dispatch multiversion function, emit the resolver.
2643 if (Global->hasAttr<CPUDispatchAttr>())
2644 return emitCPUDispatchDefinition(GD);
2645
2646 // If this is CUDA, be selective about which declarations we emit.
2647 if (LangOpts.CUDA) {
2648 if (LangOpts.CUDAIsDevice) {
2649 if (!Global->hasAttr<CUDADeviceAttr>() &&
2650 !Global->hasAttr<CUDAGlobalAttr>() &&
2651 !Global->hasAttr<CUDAConstantAttr>() &&
2652 !Global->hasAttr<CUDASharedAttr>() &&
2653 !Global->getType()->isCUDADeviceBuiltinSurfaceType() &&
2654 !Global->getType()->isCUDADeviceBuiltinTextureType())
2655 return;
2656 } else {
2657 // We need to emit host-side 'shadows' for all global
2658 // device-side variables because the CUDA runtime needs their
2659 // size and host-side address in order to provide access to
2660 // their device-side incarnations.
2661
2662 // So device-only functions are the only things we skip.
2663 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2664 Global->hasAttr<CUDADeviceAttr>())
2665 return;
2666
2667 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2668 "Expected Variable or Function");
2669 }
2670 }
2671
2672 if (LangOpts.OpenMP) {
2673 // If this is OpenMP, check if it is legal to emit this global normally.
2674 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2675 return;
2676 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2677 if (MustBeEmitted(Global))
2678 EmitOMPDeclareReduction(DRD);
2679 return;
2680 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2681 if (MustBeEmitted(Global))
2682 EmitOMPDeclareMapper(DMD);
2683 return;
2684 }
2685 }
2686
2687 // Ignore declarations, they will be emitted on their first use.
2688 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2689 // Forward declarations are emitted lazily on first use.
2690 if (!FD->doesThisDeclarationHaveABody()) {
2691 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2692 return;
2693
2694 StringRef MangledName = getMangledName(GD);
2695
2696 // Compute the function info and LLVM type.
2697 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2698 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2699
2700 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2701 /*DontDefer=*/false);
2702 return;
2703 }
2704 } else {
2705 const auto *VD = cast<VarDecl>(Global);
2706 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2707 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2708 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2709 if (LangOpts.OpenMP) {
2710 // Emit declaration of the must-be-emitted declare target variable.
2711 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2712 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2713 bool UnifiedMemoryEnabled =
2714 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2715 if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2716 !UnifiedMemoryEnabled) {
2717 (void)GetAddrOfGlobalVar(VD);
2718 } else {
2719 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2720 (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2721 UnifiedMemoryEnabled)) &&
2722 "Link clause or to clause with unified memory expected.");
2723 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2724 }
2725
2726 return;
2727 }
2728 }
2729 // If this declaration may have caused an inline variable definition to
2730 // change linkage, make sure that it's emitted.
2731 if (Context.getInlineVariableDefinitionKind(VD) ==
2732 ASTContext::InlineVariableDefinitionKind::Strong)
2733 GetAddrOfGlobalVar(VD);
2734 return;
2735 }
2736 }
2737
2738 // Defer code generation to first use when possible, e.g. if this is an inline
2739 // function. If the global must always be emitted, do it eagerly if possible
2740 // to benefit from cache locality.
2741 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2742 // Emit the definition if it can't be deferred.
2743 EmitGlobalDefinition(GD);
2744 return;
2745 }
2746
2747 // If we're deferring emission of a C++ variable with an
2748 // initializer, remember the order in which it appeared in the file.
2749 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2750 cast<VarDecl>(Global)->hasInit()) {
2751 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2752 CXXGlobalInits.push_back(nullptr);
2753 }
2754
2755 StringRef MangledName = getMangledName(GD);
2756 if (GetGlobalValue(MangledName) != nullptr) {
2757 // The value has already been used and should therefore be emitted.
2758 addDeferredDeclToEmit(GD);
2759 } else if (MustBeEmitted(Global)) {
2760 // The value must be emitted, but cannot be emitted eagerly.
2761 assert(!MayBeEmittedEagerly(Global));
2762 addDeferredDeclToEmit(GD);
2763 } else {
2764 // Otherwise, remember that we saw a deferred decl with this name. The
2765 // first use of the mangled name will cause it to move into
2766 // DeferredDeclsToEmit.
2767 DeferredDecls[MangledName] = GD;
2768 }
2769 }
2770
2771 // Check if T is a class type with a destructor that's not dllimport.
HasNonDllImportDtor(QualType T)2772 static bool HasNonDllImportDtor(QualType T) {
2773 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2774 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2775 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2776 return true;
2777
2778 return false;
2779 }
2780
2781 namespace {
2782 struct FunctionIsDirectlyRecursive
2783 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
2784 const StringRef Name;
2785 const Builtin::Context &BI;
FunctionIsDirectlyRecursive__anond22324070911::FunctionIsDirectlyRecursive2786 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
2787 : Name(N), BI(C) {}
2788
VisitCallExpr__anond22324070911::FunctionIsDirectlyRecursive2789 bool VisitCallExpr(const CallExpr *E) {
2790 const FunctionDecl *FD = E->getDirectCallee();
2791 if (!FD)
2792 return false;
2793 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2794 if (Attr && Name == Attr->getLabel())
2795 return true;
2796 unsigned BuiltinID = FD->getBuiltinID();
2797 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2798 return false;
2799 StringRef BuiltinName = BI.getName(BuiltinID);
2800 if (BuiltinName.startswith("__builtin_") &&
2801 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2802 return true;
2803 }
2804 return false;
2805 }
2806
VisitStmt__anond22324070911::FunctionIsDirectlyRecursive2807 bool VisitStmt(const Stmt *S) {
2808 for (const Stmt *Child : S->children())
2809 if (Child && this->Visit(Child))
2810 return true;
2811 return false;
2812 }
2813 };
2814
2815 // Make sure we're not referencing non-imported vars or functions.
2816 struct DLLImportFunctionVisitor
2817 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2818 bool SafeToInline = true;
2819
shouldVisitImplicitCode__anond22324070911::DLLImportFunctionVisitor2820 bool shouldVisitImplicitCode() const { return true; }
2821
VisitVarDecl__anond22324070911::DLLImportFunctionVisitor2822 bool VisitVarDecl(VarDecl *VD) {
2823 if (VD->getTLSKind()) {
2824 // A thread-local variable cannot be imported.
2825 SafeToInline = false;
2826 return SafeToInline;
2827 }
2828
2829 // A variable definition might imply a destructor call.
2830 if (VD->isThisDeclarationADefinition())
2831 SafeToInline = !HasNonDllImportDtor(VD->getType());
2832
2833 return SafeToInline;
2834 }
2835
VisitCXXBindTemporaryExpr__anond22324070911::DLLImportFunctionVisitor2836 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2837 if (const auto *D = E->getTemporary()->getDestructor())
2838 SafeToInline = D->hasAttr<DLLImportAttr>();
2839 return SafeToInline;
2840 }
2841
VisitDeclRefExpr__anond22324070911::DLLImportFunctionVisitor2842 bool VisitDeclRefExpr(DeclRefExpr *E) {
2843 ValueDecl *VD = E->getDecl();
2844 if (isa<FunctionDecl>(VD))
2845 SafeToInline = VD->hasAttr<DLLImportAttr>();
2846 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2847 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2848 return SafeToInline;
2849 }
2850
VisitCXXConstructExpr__anond22324070911::DLLImportFunctionVisitor2851 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2852 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2853 return SafeToInline;
2854 }
2855
VisitCXXMemberCallExpr__anond22324070911::DLLImportFunctionVisitor2856 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2857 CXXMethodDecl *M = E->getMethodDecl();
2858 if (!M) {
2859 // Call through a pointer to member function. This is safe to inline.
2860 SafeToInline = true;
2861 } else {
2862 SafeToInline = M->hasAttr<DLLImportAttr>();
2863 }
2864 return SafeToInline;
2865 }
2866
VisitCXXDeleteExpr__anond22324070911::DLLImportFunctionVisitor2867 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2868 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2869 return SafeToInline;
2870 }
2871
VisitCXXNewExpr__anond22324070911::DLLImportFunctionVisitor2872 bool VisitCXXNewExpr(CXXNewExpr *E) {
2873 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2874 return SafeToInline;
2875 }
2876 };
2877 }
2878
2879 // isTriviallyRecursive - Check if this function calls another
2880 // decl that, because of the asm attribute or the other decl being a builtin,
2881 // ends up pointing to itself.
2882 bool
isTriviallyRecursive(const FunctionDecl * FD)2883 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2884 StringRef Name;
2885 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2886 // asm labels are a special kind of mangling we have to support.
2887 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2888 if (!Attr)
2889 return false;
2890 Name = Attr->getLabel();
2891 } else {
2892 Name = FD->getName();
2893 }
2894
2895 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2896 const Stmt *Body = FD->getBody();
2897 return Body ? Walker.Visit(Body) : false;
2898 }
2899
shouldEmitFunction(GlobalDecl GD)2900 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2901 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2902 return true;
2903 const auto *F = cast<FunctionDecl>(GD.getDecl());
2904 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2905 return false;
2906
2907 if (F->hasAttr<DLLImportAttr>()) {
2908 // Check whether it would be safe to inline this dllimport function.
2909 DLLImportFunctionVisitor Visitor;
2910 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2911 if (!Visitor.SafeToInline)
2912 return false;
2913
2914 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2915 // Implicit destructor invocations aren't captured in the AST, so the
2916 // check above can't see them. Check for them manually here.
2917 for (const Decl *Member : Dtor->getParent()->decls())
2918 if (isa<FieldDecl>(Member))
2919 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2920 return false;
2921 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2922 if (HasNonDllImportDtor(B.getType()))
2923 return false;
2924 }
2925 }
2926
2927 // PR9614. Avoid cases where the source code is lying to us. An available
2928 // externally function should have an equivalent function somewhere else,
2929 // but a function that calls itself through asm label/`__builtin_` trickery is
2930 // clearly not equivalent to the real implementation.
2931 // This happens in glibc's btowc and in some configure checks.
2932 return !isTriviallyRecursive(F);
2933 }
2934
shouldOpportunisticallyEmitVTables()2935 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2936 return CodeGenOpts.OptimizationLevel > 0;
2937 }
2938
EmitMultiVersionFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)2939 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2940 llvm::GlobalValue *GV) {
2941 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2942
2943 if (FD->isCPUSpecificMultiVersion()) {
2944 auto *Spec = FD->getAttr<CPUSpecificAttr>();
2945 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2946 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2947 // Requires multiple emits.
2948 } else
2949 EmitGlobalFunctionDefinition(GD, GV);
2950 }
2951
EmitGlobalDefinition(GlobalDecl GD,llvm::GlobalValue * GV)2952 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2953 const auto *D = cast<ValueDecl>(GD.getDecl());
2954
2955 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2956 Context.getSourceManager(),
2957 "Generating code for declaration");
2958
2959 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2960 // At -O0, don't generate IR for functions with available_externally
2961 // linkage.
2962 if (!shouldEmitFunction(GD))
2963 return;
2964
2965 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
2966 std::string Name;
2967 llvm::raw_string_ostream OS(Name);
2968 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
2969 /*Qualified=*/true);
2970 return Name;
2971 });
2972
2973 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2974 // Make sure to emit the definition(s) before we emit the thunks.
2975 // This is necessary for the generation of certain thunks.
2976 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2977 ABI->emitCXXStructor(GD);
2978 else if (FD->isMultiVersion())
2979 EmitMultiVersionFunctionDefinition(GD, GV);
2980 else
2981 EmitGlobalFunctionDefinition(GD, GV);
2982
2983 if (Method->isVirtual())
2984 getVTables().EmitThunks(GD);
2985
2986 return;
2987 }
2988
2989 if (FD->isMultiVersion())
2990 return EmitMultiVersionFunctionDefinition(GD, GV);
2991 return EmitGlobalFunctionDefinition(GD, GV);
2992 }
2993
2994 if (const auto *VD = dyn_cast<VarDecl>(D))
2995 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2996
2997 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2998 }
2999
3000 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3001 llvm::Function *NewFn);
3002
3003 static unsigned
TargetMVPriority(const TargetInfo & TI,const CodeGenFunction::MultiVersionResolverOption & RO)3004 TargetMVPriority(const TargetInfo &TI,
3005 const CodeGenFunction::MultiVersionResolverOption &RO) {
3006 unsigned Priority = 0;
3007 for (StringRef Feat : RO.Conditions.Features)
3008 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
3009
3010 if (!RO.Conditions.Architecture.empty())
3011 Priority = std::max(
3012 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
3013 return Priority;
3014 }
3015
emitMultiVersionFunctions()3016 void CodeGenModule::emitMultiVersionFunctions() {
3017 for (GlobalDecl GD : MultiVersionFuncs) {
3018 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3019 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
3020 getContext().forEachMultiversionedFunctionVersion(
3021 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
3022 GlobalDecl CurGD{
3023 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
3024 StringRef MangledName = getMangledName(CurGD);
3025 llvm::Constant *Func = GetGlobalValue(MangledName);
3026 if (!Func) {
3027 if (CurFD->isDefined()) {
3028 EmitGlobalFunctionDefinition(CurGD, nullptr);
3029 Func = GetGlobalValue(MangledName);
3030 } else {
3031 const CGFunctionInfo &FI =
3032 getTypes().arrangeGlobalDeclaration(GD);
3033 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3034 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
3035 /*DontDefer=*/false, ForDefinition);
3036 }
3037 assert(Func && "This should have just been created");
3038 }
3039
3040 const auto *TA = CurFD->getAttr<TargetAttr>();
3041 llvm::SmallVector<StringRef, 8> Feats;
3042 TA->getAddedFeatures(Feats);
3043
3044 Options.emplace_back(cast<llvm::Function>(Func),
3045 TA->getArchitecture(), Feats);
3046 });
3047
3048 llvm::Function *ResolverFunc;
3049 const TargetInfo &TI = getTarget();
3050
3051 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
3052 ResolverFunc = cast<llvm::Function>(
3053 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
3054 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3055 } else {
3056 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
3057 }
3058
3059 if (supportsCOMDAT())
3060 ResolverFunc->setComdat(
3061 getModule().getOrInsertComdat(ResolverFunc->getName()));
3062
3063 llvm::stable_sort(
3064 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
3065 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3066 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
3067 });
3068 CodeGenFunction CGF(*this);
3069 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3070 }
3071 }
3072
emitCPUDispatchDefinition(GlobalDecl GD)3073 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
3074 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3075 assert(FD && "Not a FunctionDecl?");
3076 const auto *DD = FD->getAttr<CPUDispatchAttr>();
3077 assert(DD && "Not a cpu_dispatch Function?");
3078 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
3079
3080 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
3081 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
3082 DeclTy = getTypes().GetFunctionType(FInfo);
3083 }
3084
3085 StringRef ResolverName = getMangledName(GD);
3086
3087 llvm::Type *ResolverType;
3088 GlobalDecl ResolverGD;
3089 if (getTarget().supportsIFunc())
3090 ResolverType = llvm::FunctionType::get(
3091 llvm::PointerType::get(DeclTy,
3092 getAddressSpaceForType(FD->getType())),
3093 false);
3094 else {
3095 ResolverType = DeclTy;
3096 ResolverGD = GD;
3097 }
3098
3099 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
3100 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
3101 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
3102 if (supportsCOMDAT())
3103 ResolverFunc->setComdat(
3104 getModule().getOrInsertComdat(ResolverFunc->getName()));
3105
3106 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
3107 const TargetInfo &Target = getTarget();
3108 unsigned Index = 0;
3109 for (const IdentifierInfo *II : DD->cpus()) {
3110 // Get the name of the target function so we can look it up/create it.
3111 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
3112 getCPUSpecificMangling(*this, II->getName());
3113
3114 llvm::Constant *Func = GetGlobalValue(MangledName);
3115
3116 if (!Func) {
3117 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
3118 if (ExistingDecl.getDecl() &&
3119 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
3120 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
3121 Func = GetGlobalValue(MangledName);
3122 } else {
3123 if (!ExistingDecl.getDecl())
3124 ExistingDecl = GD.getWithMultiVersionIndex(Index);
3125
3126 Func = GetOrCreateLLVMFunction(
3127 MangledName, DeclTy, ExistingDecl,
3128 /*ForVTable=*/false, /*DontDefer=*/true,
3129 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
3130 }
3131 }
3132
3133 llvm::SmallVector<StringRef, 32> Features;
3134 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3135 llvm::transform(Features, Features.begin(),
3136 [](StringRef Str) { return Str.substr(1); });
3137 Features.erase(std::remove_if(
3138 Features.begin(), Features.end(), [&Target](StringRef Feat) {
3139 return !Target.validateCpuSupports(Feat);
3140 }), Features.end());
3141 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3142 ++Index;
3143 }
3144
3145 llvm::sort(
3146 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3147 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3148 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3149 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3150 });
3151
3152 // If the list contains multiple 'default' versions, such as when it contains
3153 // 'pentium' and 'generic', don't emit the call to the generic one (since we
3154 // always run on at least a 'pentium'). We do this by deleting the 'least
3155 // advanced' (read, lowest mangling letter).
3156 while (Options.size() > 1 &&
3157 CodeGenFunction::GetX86CpuSupportsMask(
3158 (Options.end() - 2)->Conditions.Features) == 0) {
3159 StringRef LHSName = (Options.end() - 2)->Function->getName();
3160 StringRef RHSName = (Options.end() - 1)->Function->getName();
3161 if (LHSName.compare(RHSName) < 0)
3162 Options.erase(Options.end() - 2);
3163 else
3164 Options.erase(Options.end() - 1);
3165 }
3166
3167 CodeGenFunction CGF(*this);
3168 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3169
3170 if (getTarget().supportsIFunc()) {
3171 std::string AliasName = getMangledNameImpl(
3172 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3173 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3174 if (!AliasFunc) {
3175 auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3176 AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3177 /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3178 auto *GA = llvm::GlobalAlias::create(
3179 DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3180 GA->setLinkage(llvm::Function::WeakODRLinkage);
3181 SetCommonAttributes(GD, GA);
3182 }
3183 }
3184 }
3185
3186 /// If a dispatcher for the specified mangled name is not in the module, create
3187 /// and return an llvm Function with the specified type.
GetOrCreateMultiVersionResolver(GlobalDecl GD,llvm::Type * DeclTy,const FunctionDecl * FD)3188 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3189 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3190 std::string MangledName =
3191 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3192
3193 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3194 // a separate resolver).
3195 std::string ResolverName = MangledName;
3196 if (getTarget().supportsIFunc())
3197 ResolverName += ".ifunc";
3198 else if (FD->isTargetMultiVersion())
3199 ResolverName += ".resolver";
3200
3201 // If this already exists, just return that one.
3202 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3203 return ResolverGV;
3204
3205 // Since this is the first time we've created this IFunc, make sure
3206 // that we put this multiversioned function into the list to be
3207 // replaced later if necessary (target multiversioning only).
3208 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3209 MultiVersionFuncs.push_back(GD);
3210
3211 if (getTarget().supportsIFunc()) {
3212 llvm::Type *ResolverType = llvm::FunctionType::get(
3213 llvm::PointerType::get(
3214 DeclTy, getAddressSpaceForType(FD->getType())),
3215 false);
3216 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3217 MangledName + ".resolver", ResolverType, GlobalDecl{},
3218 /*ForVTable=*/false);
3219 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3220 DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3221 GIF->setName(ResolverName);
3222 SetCommonAttributes(FD, GIF);
3223
3224 return GIF;
3225 }
3226
3227 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3228 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3229 assert(isa<llvm::GlobalValue>(Resolver) &&
3230 "Resolver should be created for the first time");
3231 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3232 return Resolver;
3233 }
3234
3235 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3236 /// module, create and return an llvm Function with the specified type. If there
3237 /// is something in the module with the specified name, return it potentially
3238 /// bitcasted to the right type.
3239 ///
3240 /// If D is non-null, it specifies a decl that correspond to this. This is used
3241 /// to set the attributes on the function when it is first created.
GetOrCreateLLVMFunction(StringRef MangledName,llvm::Type * Ty,GlobalDecl GD,bool ForVTable,bool DontDefer,bool IsThunk,llvm::AttributeList ExtraAttrs,ForDefinition_t IsForDefinition)3242 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3243 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3244 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3245 ForDefinition_t IsForDefinition) {
3246 const Decl *D = GD.getDecl();
3247 // Any attempts to use a MultiVersion function should result in retrieving
3248 // the iFunc instead. Name Mangling will handle the rest of the changes.
3249 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3250 // For the device mark the function as one that should be emitted.
3251 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3252 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3253 !DontDefer && !IsForDefinition) {
3254 if (const FunctionDecl *FDDef = FD->getDefinition()) {
3255 GlobalDecl GDDef;
3256 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3257 GDDef = GlobalDecl(CD, GD.getCtorType());
3258 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3259 GDDef = GlobalDecl(DD, GD.getDtorType());
3260 else
3261 GDDef = GlobalDecl(FDDef);
3262 EmitGlobal(GDDef);
3263 }
3264 }
3265
3266 if (FD->isMultiVersion()) {
3267 if (FD->hasAttr<TargetAttr>())
3268 UpdateMultiVersionNames(GD, FD);
3269 if (!IsForDefinition)
3270 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3271 }
3272 }
3273
3274 // Lookup the entry, lazily creating it if necessary.
3275 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3276 if (Entry) {
3277 if (WeakRefReferences.erase(Entry)) {
3278 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3279 if (FD && !FD->hasAttr<WeakAttr>())
3280 Entry->setLinkage(llvm::Function::ExternalLinkage);
3281 }
3282
3283 // Handle dropped DLL attributes.
3284 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3285 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3286 setDSOLocal(Entry);
3287 }
3288
3289 // If there are two attempts to define the same mangled name, issue an
3290 // error.
3291 if (IsForDefinition && !Entry->isDeclaration()) {
3292 GlobalDecl OtherGD;
3293 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3294 // to make sure that we issue an error only once.
3295 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3296 (GD.getCanonicalDecl().getDecl() !=
3297 OtherGD.getCanonicalDecl().getDecl()) &&
3298 DiagnosedConflictingDefinitions.insert(GD).second) {
3299 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3300 << MangledName;
3301 getDiags().Report(OtherGD.getDecl()->getLocation(),
3302 diag::note_previous_definition);
3303 }
3304 }
3305
3306 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3307 (Entry->getValueType() == Ty)) {
3308 return Entry;
3309 }
3310
3311 // Make sure the result is of the correct type.
3312 // (If function is requested for a definition, we always need to create a new
3313 // function, not just return a bitcast.)
3314 if (!IsForDefinition) {
3315 return llvm::ConstantExpr::getBitCast(
3316 Entry, Ty->getPointerTo(getFunctionAddrSpace()));
3317 }
3318 }
3319
3320 // This function doesn't have a complete type (for example, the return
3321 // type is an incomplete struct). Use a fake type instead, and make
3322 // sure not to try to set attributes.
3323 bool IsIncompleteFunction = false;
3324
3325 llvm::FunctionType *FTy;
3326 if (isa<llvm::FunctionType>(Ty)) {
3327 FTy = cast<llvm::FunctionType>(Ty);
3328 } else {
3329 FTy = llvm::FunctionType::get(VoidTy, false);
3330 IsIncompleteFunction = true;
3331 }
3332
3333 llvm::Function *F =
3334 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3335 Entry ? StringRef() : MangledName, &getModule());
3336
3337 // If we already created a function with the same mangled name (but different
3338 // type) before, take its name and add it to the list of functions to be
3339 // replaced with F at the end of CodeGen.
3340 //
3341 // This happens if there is a prototype for a function (e.g. "int f()") and
3342 // then a definition of a different type (e.g. "int f(int x)").
3343 if (Entry) {
3344 F->takeName(Entry);
3345
3346 // This might be an implementation of a function without a prototype, in
3347 // which case, try to do special replacement of calls which match the new
3348 // prototype. The really key thing here is that we also potentially drop
3349 // arguments from the call site so as to make a direct call, which makes the
3350 // inliner happier and suppresses a number of optimizer warnings (!) about
3351 // dropping arguments.
3352 if (!Entry->use_empty()) {
3353 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3354 Entry->removeDeadConstantUsers();
3355 }
3356
3357 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3358 F, Entry->getValueType()->getPointerTo(getFunctionAddrSpace()));
3359 addGlobalValReplacement(Entry, BC);
3360 }
3361
3362 assert(F->getName() == MangledName && "name was uniqued!");
3363 if (D)
3364 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3365 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3366 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3367 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3368 }
3369
3370 if (!DontDefer) {
3371 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3372 // each other bottoming out with the base dtor. Therefore we emit non-base
3373 // dtors on usage, even if there is no dtor definition in the TU.
3374 if (D && isa<CXXDestructorDecl>(D) &&
3375 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3376 GD.getDtorType()))
3377 addDeferredDeclToEmit(GD);
3378
3379 // This is the first use or definition of a mangled name. If there is a
3380 // deferred decl with this name, remember that we need to emit it at the end
3381 // of the file.
3382 auto DDI = DeferredDecls.find(MangledName);
3383 if (DDI != DeferredDecls.end()) {
3384 // Move the potentially referenced deferred decl to the
3385 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3386 // don't need it anymore).
3387 addDeferredDeclToEmit(DDI->second);
3388 DeferredDecls.erase(DDI);
3389
3390 // Otherwise, there are cases we have to worry about where we're
3391 // using a declaration for which we must emit a definition but where
3392 // we might not find a top-level definition:
3393 // - member functions defined inline in their classes
3394 // - friend functions defined inline in some class
3395 // - special member functions with implicit definitions
3396 // If we ever change our AST traversal to walk into class methods,
3397 // this will be unnecessary.
3398 //
3399 // We also don't emit a definition for a function if it's going to be an
3400 // entry in a vtable, unless it's already marked as used.
3401 } else if (getLangOpts().CPlusPlus && D) {
3402 // Look for a declaration that's lexically in a record.
3403 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3404 FD = FD->getPreviousDecl()) {
3405 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3406 if (FD->doesThisDeclarationHaveABody()) {
3407 addDeferredDeclToEmit(GD.getWithDecl(FD));
3408 break;
3409 }
3410 }
3411 }
3412 }
3413 }
3414
3415 // Make sure the result is of the requested type.
3416 if (!IsIncompleteFunction) {
3417 assert(F->getFunctionType() == Ty);
3418 return F;
3419 }
3420 llvm::Type *PTy = llvm::PointerType::get(Ty, getFunctionAddrSpace());
3421 return llvm::ConstantExpr::getBitCast(F, PTy);
3422 }
3423
3424 /// GetAddrOfFunction - Return the address of the given function. If Ty is
3425 /// non-null, then this function will use the specified type if it has to
3426 /// create it (this occurs when we see a definition of the function).
GetAddrOfFunction(GlobalDecl GD,llvm::Type * Ty,bool ForVTable,bool DontDefer,ForDefinition_t IsForDefinition)3427 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3428 llvm::Type *Ty,
3429 bool ForVTable,
3430 bool DontDefer,
3431 ForDefinition_t IsForDefinition) {
3432 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() &&
3433 "consteval function should never be emitted");
3434 // If there was no specific requested type, just convert it now.
3435 if (!Ty) {
3436 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3437 Ty = getTypes().ConvertType(FD->getType());
3438 }
3439
3440 // Devirtualized destructor calls may come through here instead of via
3441 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3442 // of the complete destructor when necessary.
3443 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3444 if (getTarget().getCXXABI().isMicrosoft() &&
3445 GD.getDtorType() == Dtor_Complete &&
3446 DD->getParent()->getNumVBases() == 0)
3447 GD = GlobalDecl(DD, Dtor_Base);
3448 }
3449
3450 StringRef MangledName = getMangledName(GD);
3451 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3452 /*IsThunk=*/false, llvm::AttributeList(),
3453 IsForDefinition);
3454 }
3455
3456 static const FunctionDecl *
GetRuntimeFunctionDecl(ASTContext & C,StringRef Name)3457 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3458 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3459 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3460
3461 IdentifierInfo &CII = C.Idents.get(Name);
3462 for (const auto &Result : DC->lookup(&CII))
3463 if (const auto FD = dyn_cast<FunctionDecl>(Result))
3464 return FD;
3465
3466 if (!C.getLangOpts().CPlusPlus)
3467 return nullptr;
3468
3469 // Demangle the premangled name from getTerminateFn()
3470 IdentifierInfo &CXXII =
3471 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3472 ? C.Idents.get("terminate")
3473 : C.Idents.get(Name);
3474
3475 for (const auto &N : {"__cxxabiv1", "std"}) {
3476 IdentifierInfo &NS = C.Idents.get(N);
3477 for (const auto &Result : DC->lookup(&NS)) {
3478 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3479 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
3480 for (const auto &Result : LSD->lookup(&NS))
3481 if ((ND = dyn_cast<NamespaceDecl>(Result)))
3482 break;
3483
3484 if (ND)
3485 for (const auto &Result : ND->lookup(&CXXII))
3486 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3487 return FD;
3488 }
3489 }
3490
3491 return nullptr;
3492 }
3493
3494 /// CreateRuntimeFunction - Create a new runtime function with the specified
3495 /// type and name.
3496 llvm::FunctionCallee
CreateRuntimeFunction(llvm::FunctionType * FTy,StringRef Name,llvm::AttributeList ExtraAttrs,bool Local,bool AssumeConvergent)3497 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3498 llvm::AttributeList ExtraAttrs, bool Local,
3499 bool AssumeConvergent) {
3500 if (AssumeConvergent) {
3501 ExtraAttrs =
3502 ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3503 llvm::Attribute::Convergent);
3504 }
3505
3506 llvm::Constant *C =
3507 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3508 /*DontDefer=*/false, /*IsThunk=*/false,
3509 ExtraAttrs);
3510
3511 if (auto *F = dyn_cast<llvm::Function>(C)) {
3512 if (F->empty()) {
3513 F->setCallingConv(getRuntimeCC());
3514
3515 // In Windows Itanium environments, try to mark runtime functions
3516 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3517 // will link their standard library statically or dynamically. Marking
3518 // functions imported when they are not imported can cause linker errors
3519 // and warnings.
3520 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3521 !getCodeGenOpts().LTOVisibilityPublicStd) {
3522 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3523 if (!FD || FD->hasAttr<DLLImportAttr>()) {
3524 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3525 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3526 }
3527 }
3528 setDSOLocal(F);
3529 }
3530 }
3531
3532 return {FTy, C};
3533 }
3534
3535 /// isTypeConstant - Determine whether an object of this type can be emitted
3536 /// as a constant.
3537 ///
3538 /// If ExcludeCtor is true, the duration when the object's constructor runs
3539 /// will not be considered. The caller will need to verify that the object is
3540 /// not written to during its construction.
isTypeConstant(QualType Ty,bool ExcludeCtor)3541 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3542 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3543 return false;
3544
3545 if (Context.getLangOpts().CPlusPlus) {
3546 if (const CXXRecordDecl *Record
3547 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3548 return ExcludeCtor && !Record->hasMutableFields() &&
3549 Record->hasTrivialDestructor();
3550 }
3551
3552 return true;
3553 }
3554
3555 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3556 /// create and return an llvm GlobalVariable with the specified type. If there
3557 /// is something in the module with the specified name, return it potentially
3558 /// bitcasted to the right type.
3559 ///
3560 /// If D is non-null, it specifies a decl that correspond to this. This is used
3561 /// to set the attributes on the global when it is first created.
3562 ///
3563 /// If IsForDefinition is true, it is guaranteed that an actual global with
3564 /// type Ty will be returned, not conversion of a variable with the same
3565 /// mangled name but some other type.
3566 llvm::Constant *
GetOrCreateLLVMGlobal(StringRef MangledName,llvm::PointerType * Ty,const VarDecl * D,ForDefinition_t IsForDefinition)3567 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3568 llvm::PointerType *Ty,
3569 const VarDecl *D,
3570 ForDefinition_t IsForDefinition) {
3571 // Lookup the entry, lazily creating it if necessary.
3572 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3573 if (Entry) {
3574 if (WeakRefReferences.erase(Entry)) {
3575 if (D && !D->hasAttr<WeakAttr>())
3576 Entry->setLinkage(llvm::Function::ExternalLinkage);
3577 }
3578
3579 // Handle dropped DLL attributes.
3580 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3581 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3582
3583 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3584 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3585
3586 if (Entry->getType() == Ty)
3587 return Entry;
3588
3589 // If there are two attempts to define the same mangled name, issue an
3590 // error.
3591 if (IsForDefinition && !Entry->isDeclaration()) {
3592 GlobalDecl OtherGD;
3593 const VarDecl *OtherD;
3594
3595 // Check that D is not yet in DiagnosedConflictingDefinitions is required
3596 // to make sure that we issue an error only once.
3597 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3598 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3599 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3600 OtherD->hasInit() &&
3601 DiagnosedConflictingDefinitions.insert(D).second) {
3602 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3603 << MangledName;
3604 getDiags().Report(OtherGD.getDecl()->getLocation(),
3605 diag::note_previous_definition);
3606 }
3607 }
3608
3609 // Make sure the result is of the correct type.
3610 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3611 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3612
3613 // (If global is requested for a definition, we always need to create a new
3614 // global, not just return a bitcast.)
3615 if (!IsForDefinition)
3616 return llvm::ConstantExpr::getBitCast(Entry, Ty);
3617 }
3618
3619 LangAS AddrSpace = GetGlobalVarAddressSpace(D);
3620 auto TargetAddrSpace = getTargetAddressSpace(AddrSpace);
3621
3622 auto *GV = new llvm::GlobalVariable(
3623 getModule(), Ty->getElementType(), false,
3624 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3625 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3626
3627 // If we already created a global with the same mangled name (but different
3628 // type) before, take its name and remove it from its parent.
3629 if (Entry) {
3630 GV->takeName(Entry);
3631
3632 if (!Entry->use_empty()) {
3633 llvm::Constant *NewPtrForOldDecl =
3634 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3635 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3636 }
3637
3638 Entry->eraseFromParent();
3639 }
3640
3641 // This is the first use or definition of a mangled name. If there is a
3642 // deferred decl with this name, remember that we need to emit it at the end
3643 // of the file.
3644 auto DDI = DeferredDecls.find(MangledName);
3645 if (DDI != DeferredDecls.end()) {
3646 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3647 // list, and remove it from DeferredDecls (since we don't need it anymore).
3648 addDeferredDeclToEmit(DDI->second);
3649 DeferredDecls.erase(DDI);
3650 }
3651
3652 // Handle things which are present even on external declarations.
3653 if (D) {
3654 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3655 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3656
3657 // FIXME: This code is overly simple and should be merged with other global
3658 // handling.
3659 GV->setConstant(isTypeConstant(D->getType(), false));
3660
3661 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3662
3663 setLinkageForGV(GV, D);
3664
3665 if (D->getTLSKind()) {
3666 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3667 CXXThreadLocals.push_back(D);
3668 setTLSMode(GV, *D);
3669 }
3670
3671 setGVProperties(GV, D);
3672
3673 // If required by the ABI, treat declarations of static data members with
3674 // inline initializers as definitions.
3675 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3676 EmitGlobalVarDefinition(D);
3677 }
3678
3679 // Emit section information for extern variables.
3680 if (D->hasExternalStorage()) {
3681 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3682 GV->setSection(SA->getName());
3683 }
3684
3685 // Handle XCore specific ABI requirements.
3686 if (getTriple().getArch() == llvm::Triple::xcore &&
3687 D->getLanguageLinkage() == CLanguageLinkage &&
3688 D->getType().isConstant(Context) &&
3689 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3690 GV->setSection(".cp.rodata");
3691
3692 // Check if we a have a const declaration with an initializer, we may be
3693 // able to emit it as available_externally to expose it's value to the
3694 // optimizer.
3695 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3696 D->getType().isConstQualified() && !GV->hasInitializer() &&
3697 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3698 const auto *Record =
3699 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3700 bool HasMutableFields = Record && Record->hasMutableFields();
3701 if (!HasMutableFields) {
3702 const VarDecl *InitDecl;
3703 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3704 if (InitExpr) {
3705 ConstantEmitter emitter(*this);
3706 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3707 if (Init) {
3708 auto *InitType = Init->getType();
3709 if (GV->getValueType() != InitType) {
3710 // The type of the initializer does not match the definition.
3711 // This happens when an initializer has a different type from
3712 // the type of the global (because of padding at the end of a
3713 // structure for instance).
3714 GV->setName(StringRef());
3715 // Make a new global with the correct type, this is now guaranteed
3716 // to work.
3717 auto *NewGV = cast<llvm::GlobalVariable>(
3718 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3719 ->stripPointerCasts());
3720
3721 // Erase the old global, since it is no longer used.
3722 GV->eraseFromParent();
3723 GV = NewGV;
3724 } else {
3725 GV->setInitializer(Init);
3726 GV->setConstant(true);
3727 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3728 }
3729 emitter.finalize(GV);
3730 }
3731 }
3732 }
3733 }
3734 }
3735
3736 if (GV->isDeclaration())
3737 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3738
3739 LangAS ExpectedAS =
3740 D ? D->getType().getAddressSpace()
3741 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3742 // XXXAR: not quite sure if this is correct (actually I think it's not needed)
3743 if (getContext().getTargetInfo().areAllPointersCapabilities())
3744 ExpectedAS = getLangASFromTargetAS(getTargetCodeGenInfo().getCHERICapabilityAS());
3745 assert(getTargetAddressSpace(ExpectedAS) == Ty->getPointerAddressSpace());
3746 if (AddrSpace != ExpectedAS)
3747 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3748 ExpectedAS, Ty);
3749
3750 return GV;
3751 }
3752
3753 llvm::Constant *
GetAddrOfGlobal(GlobalDecl GD,ForDefinition_t IsForDefinition)3754 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) {
3755 const Decl *D = GD.getDecl();
3756
3757 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3758 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3759 /*DontDefer=*/false, IsForDefinition);
3760
3761 if (isa<CXXMethodDecl>(D)) {
3762 auto FInfo =
3763 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D));
3764 auto Ty = getTypes().GetFunctionType(*FInfo);
3765 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3766 IsForDefinition);
3767 }
3768
3769 if (isa<FunctionDecl>(D)) {
3770 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3771 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3772 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3773 IsForDefinition);
3774 }
3775
3776 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition);
3777 }
3778
CreateOrReplaceCXXRuntimeVariable(StringRef Name,llvm::Type * Ty,llvm::GlobalValue::LinkageTypes Linkage,unsigned Alignment)3779 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3780 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3781 unsigned Alignment) {
3782 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3783 llvm::GlobalVariable *OldGV = nullptr;
3784
3785 if (GV) {
3786 // Check if the variable has the right type.
3787 if (GV->getValueType() == Ty)
3788 return GV;
3789
3790 // Because C++ name mangling, the only way we can end up with an already
3791 // existing global with the same name is if it has been declared extern "C".
3792 assert(GV->isDeclaration() && "Declaration has wrong type!");
3793 OldGV = GV;
3794 }
3795
3796 // Create a new variable.
3797 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3798 Linkage, nullptr, Name, nullptr,
3799 llvm::GlobalVariable::NotThreadLocal,
3800 getTargetCodeGenInfo().getDefaultAS());
3801
3802 if (OldGV) {
3803 // Replace occurrences of the old variable if needed.
3804 GV->takeName(OldGV);
3805
3806 if (!OldGV->use_empty()) {
3807 llvm::Constant *NewPtrForOldDecl =
3808 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3809 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3810 }
3811
3812 OldGV->eraseFromParent();
3813 }
3814
3815 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3816 !GV->hasAvailableExternallyLinkage())
3817 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3818
3819 GV->setAlignment(llvm::MaybeAlign(Alignment));
3820
3821 return GV;
3822 }
3823
3824 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3825 /// given global variable. If Ty is non-null and if the global doesn't exist,
3826 /// then it will be created with the specified type instead of whatever the
3827 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3828 /// that an actual global with type Ty will be returned, not conversion of a
3829 /// variable with the same mangled name but some other type.
GetAddrOfGlobalVar(const VarDecl * D,llvm::Type * Ty,ForDefinition_t IsForDefinition)3830 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3831 llvm::Type *Ty,
3832 ForDefinition_t IsForDefinition) {
3833 assert(D->hasGlobalStorage() && "Not a global variable");
3834 QualType ASTTy = D->getType();
3835 if (!Ty)
3836 Ty = getTypes().ConvertTypeForMem(ASTTy);
3837
3838 // a pointer to __intcap_t should not be AS200 in hybrid ABI
3839 // So This is not quite right: `unsigned AS = getAddressSpaceForType(ASTTy);`
3840 unsigned AS =
3841 getContext().getTargetInfo().areAllPointersCapabilities()
3842 ? getTargetCodeGenInfo().getCHERICapabilityAS()
3843 : getTargetAddressSpace(ASTTy.getAddressSpace());
3844 llvm::PointerType *PTy = llvm::PointerType::get(Ty, AS);
3845
3846 StringRef MangledName = getMangledName(D);
3847 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3848 }
3849
3850 /// CreateRuntimeVariable - Create a new runtime global variable with the
3851 /// specified type and name.
3852 llvm::Constant *
CreateRuntimeVariable(llvm::Type * Ty,StringRef Name,unsigned AddressSpace)3853 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3854 StringRef Name,
3855 unsigned AddressSpace) {
3856 auto PtrTy =
3857 getContext().getLangOpts().OpenCL
3858 ? llvm::PointerType::get(
3859 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
3860 : llvm::PointerType::get(Ty, AddressSpace);
3861 auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
3862 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3863 return Ret;
3864 }
3865
EmitTentativeDefinition(const VarDecl * D)3866 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3867 assert(!D->getInit() && "Cannot emit definite definitions here!");
3868
3869 StringRef MangledName = getMangledName(D);
3870 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3871
3872 // We already have a definition, not declaration, with the same mangled name.
3873 // Emitting of declaration is not required (and actually overwrites emitted
3874 // definition).
3875 if (GV && !GV->isDeclaration())
3876 return;
3877
3878 // If we have not seen a reference to this variable yet, place it into the
3879 // deferred declarations table to be emitted if needed later.
3880 if (!MustBeEmitted(D) && !GV) {
3881 DeferredDecls[MangledName] = D;
3882 return;
3883 }
3884
3885 // The tentative definition is the only definition.
3886 EmitGlobalVarDefinition(D);
3887 }
3888
EmitExternalDeclaration(const VarDecl * D)3889 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
3890 EmitExternalVarDeclaration(D);
3891 }
3892
GetTargetTypeStoreSize(llvm::Type * Ty) const3893 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3894 return Context.toCharUnitsFromBits(
3895 getDataLayout().getTypeStoreSizeInBits(Ty));
3896 }
3897
GetGlobalVarAddressSpace(const VarDecl * D)3898 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3899 LangAS AddrSpace = LangAS::Default;
3900 if (LangOpts.OpenCL) {
3901 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3902 assert(AddrSpace == LangAS::opencl_global ||
3903 AddrSpace == LangAS::opencl_constant ||
3904 AddrSpace == LangAS::opencl_local ||
3905 AddrSpace >= LangAS::FirstTargetAddressSpace);
3906 return AddrSpace;
3907 }
3908
3909 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3910 if (D && D->hasAttr<CUDAConstantAttr>())
3911 return LangAS::cuda_constant;
3912 else if (D && D->hasAttr<CUDASharedAttr>())
3913 return LangAS::cuda_shared;
3914 else if (D && D->hasAttr<CUDADeviceAttr>())
3915 return LangAS::cuda_device;
3916 else if (D && D->getType().isConstQualified())
3917 return LangAS::cuda_constant;
3918 else
3919 return LangAS::cuda_device;
3920 }
3921 // FIXME-cheri-qual: May need to handle GetGlobalVarAddressSpace carefully
3922 const TargetInfo &Target = getContext().getTargetInfo();
3923 if (Target.SupportsCapabilities()) {
3924 // In the hybrid ABI, AddrSpace == 200 means that D is a
3925 // capability-qualified pointer.
3926 // FIXME-cheri-qual: We currently can't handle thread-local storage
3927 unsigned CapAS = getTargetCodeGenInfo().getCHERICapabilityAS();
3928 if (Target.areAllPointersCapabilities()) { // Pure ABI
3929 if (D && (D->getTLSKind() != VarDecl::TLS_None)) {
3930 return getLangASFromTargetAS(
3931 getTargetCodeGenInfo().getTlsAddressSpace());
3932 }
3933 // All non-TLS variables should be in the Cap AS
3934 return getLangASFromTargetAS(CapAS);
3935 } else if (D && getAddressSpaceForType(D->getType()) == CapAS) {
3936 // In the hybrid ABI all globals are in AS 0 (even capabilities)
3937 return LangAS::Default; // XXXAR: FIXME: is this really correct?
3938 }
3939 }
3940
3941 if (LangOpts.OpenMP) {
3942 LangAS AS;
3943 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3944 return AS;
3945 }
3946 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3947 }
3948
getStringLiteralAddressSpace() const3949 LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3950 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3951 if (LangOpts.OpenCL)
3952 return LangAS::opencl_constant;
3953 if (auto AS = getTarget().getConstantAddressSpace())
3954 return AS.getValue();
3955 return LangAS::Default;
3956 }
3957
3958 // In address space agnostic languages, string literals are in default address
3959 // space in AST. However, certain targets (e.g. amdgcn) request them to be
3960 // emitted in constant address space in LLVM IR. To be consistent with other
3961 // parts of AST, string literal global variables in constant address space
3962 // need to be casted to default address space before being put into address
3963 // map and referenced by other part of CodeGen.
3964 // In OpenCL, string literals are in constant address space in AST, therefore
3965 // they should not be casted to default address space.
3966 static llvm::Constant *
castStringLiteralToDefaultAddressSpace(CodeGenModule & CGM,llvm::GlobalVariable * GV)3967 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3968 llvm::GlobalVariable *GV) {
3969 llvm::Constant *Cast = GV;
3970 if (!CGM.getLangOpts().OpenCL) {
3971 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3972 if (AS != LangAS::Default)
3973 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3974 CGM, GV, AS.getValue(), LangAS::Default,
3975 GV->getValueType()->getPointerTo(
3976 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3977 }
3978 }
3979 return Cast;
3980 }
3981
3982 template<typename SomeDecl>
MaybeHandleStaticInExternC(const SomeDecl * D,llvm::GlobalValue * GV)3983 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3984 llvm::GlobalValue *GV) {
3985 if (!getLangOpts().CPlusPlus)
3986 return;
3987
3988 // Must have 'used' attribute, or else inline assembly can't rely on
3989 // the name existing.
3990 if (!D->template hasAttr<UsedAttr>())
3991 return;
3992
3993 // Must have internal linkage and an ordinary name.
3994 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3995 return;
3996
3997 // Must be in an extern "C" context. Entities declared directly within
3998 // a record are not extern "C" even if the record is in such a context.
3999 const SomeDecl *First = D->getFirstDecl();
4000 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
4001 return;
4002
4003 // OK, this is an internal linkage entity inside an extern "C" linkage
4004 // specification. Make a note of that so we can give it the "expected"
4005 // mangled name if nothing else is using that name.
4006 std::pair<StaticExternCMap::iterator, bool> R =
4007 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
4008
4009 // If we have multiple internal linkage entities with the same name
4010 // in extern "C" regions, none of them gets that name.
4011 if (!R.second)
4012 R.first->second = nullptr;
4013 }
4014
shouldBeInCOMDAT(CodeGenModule & CGM,const Decl & D)4015 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
4016 if (!CGM.supportsCOMDAT())
4017 return false;
4018
4019 // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
4020 // them being "merged" by the COMDAT Folding linker optimization.
4021 if (D.hasAttr<CUDAGlobalAttr>())
4022 return false;
4023
4024 if (D.hasAttr<SelectAnyAttr>())
4025 return true;
4026
4027 GVALinkage Linkage;
4028 if (auto *VD = dyn_cast<VarDecl>(&D))
4029 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
4030 else
4031 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
4032
4033 switch (Linkage) {
4034 case GVA_Internal:
4035 case GVA_AvailableExternally:
4036 case GVA_StrongExternal:
4037 return false;
4038 case GVA_DiscardableODR:
4039 case GVA_StrongODR:
4040 return true;
4041 }
4042 llvm_unreachable("No such linkage");
4043 }
4044
maybeSetTrivialComdat(const Decl & D,llvm::GlobalObject & GO)4045 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
4046 llvm::GlobalObject &GO) {
4047 if (!shouldBeInCOMDAT(*this, D))
4048 return;
4049 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
4050 }
4051
4052 /// Pass IsTentative as true if you want to create a tentative definition.
EmitGlobalVarDefinition(const VarDecl * D,bool IsTentative)4053 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
4054 bool IsTentative) {
4055 // OpenCL global variables of sampler type are translated to function calls,
4056 // therefore no need to be translated.
4057 QualType ASTTy = D->getType();
4058 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
4059 return;
4060
4061 // If this is OpenMP device, check if it is legal to emit this global
4062 // normally.
4063 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
4064 OpenMPRuntime->emitTargetGlobalVariable(D))
4065 return;
4066
4067 llvm::Constant *Init = nullptr;
4068 bool NeedsGlobalCtor = false;
4069 bool NeedsGlobalDtor =
4070 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
4071
4072 const VarDecl *InitDecl;
4073 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
4074
4075 Optional<ConstantEmitter> emitter;
4076
4077 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
4078 // as part of their declaration." Sema has already checked for
4079 // error cases, so we just need to set Init to UndefValue.
4080 bool IsCUDASharedVar =
4081 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
4082 // Shadows of initialized device-side global variables are also left
4083 // undefined.
4084 bool IsCUDAShadowVar =
4085 !getLangOpts().CUDAIsDevice &&
4086 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4087 D->hasAttr<CUDASharedAttr>());
4088 bool IsCUDADeviceShadowVar =
4089 getLangOpts().CUDAIsDevice &&
4090 (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4091 D->getType()->isCUDADeviceBuiltinTextureType());
4092 // HIP pinned shadow of initialized host-side global variables are also
4093 // left undefined.
4094 if (getLangOpts().CUDA &&
4095 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar))
4096 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
4097 else if (D->hasAttr<LoaderUninitializedAttr>())
4098 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
4099 else if (!InitExpr) {
4100 // This is a tentative definition; tentative definitions are
4101 // implicitly initialized with { 0 }.
4102 //
4103 // Note that tentative definitions are only emitted at the end of
4104 // a translation unit, so they should never have incomplete
4105 // type. In addition, EmitTentativeDefinition makes sure that we
4106 // never attempt to emit a tentative definition if a real one
4107 // exists. A use may still exists, however, so we still may need
4108 // to do a RAUW.
4109 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
4110 Init = EmitNullConstant(D->getType());
4111 } else {
4112 initializedGlobalDecl = GlobalDecl(D);
4113 emitter.emplace(*this);
4114 Init = emitter->tryEmitForInitializer(*InitDecl);
4115
4116 if (!Init) {
4117 QualType T = InitExpr->getType();
4118 if (D->getType()->isReferenceType())
4119 T = D->getType();
4120
4121 if (getLangOpts().CPlusPlus) {
4122 Init = EmitNullConstant(T);
4123 NeedsGlobalCtor = true;
4124 } else {
4125 ErrorUnsupported(D, "static initializer");
4126 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
4127 }
4128 } else {
4129 // We don't need an initializer, so remove the entry for the delayed
4130 // initializer position (just in case this entry was delayed) if we
4131 // also don't need to register a destructor.
4132 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
4133 DelayedCXXInitPosition.erase(D);
4134 }
4135 }
4136
4137 llvm::Type* InitType = Init->getType();
4138 llvm::Constant *Entry =
4139 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
4140
4141 // Strip off pointer casts if we got them.
4142 Entry = Entry->stripPointerCasts();
4143
4144 // Entry is now either a Function or GlobalVariable.
4145 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
4146
4147 // We have a definition after a declaration with the wrong type.
4148 // We must make a new GlobalVariable* and update everything that used OldGV
4149 // (a declaration or tentative definition) with the new GlobalVariable*
4150 // (which will be a definition).
4151 //
4152 // This happens if there is a prototype for a global (e.g.
4153 // "extern int x[];") and then a definition of a different type (e.g.
4154 // "int x[10];"). This also happens when an initializer has a different type
4155 // from the type of the global (this happens with unions).
4156 if (!GV || GV->getValueType() != InitType ||
4157 GV->getType()->getAddressSpace() !=
4158 getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
4159
4160 // Move the old entry aside so that we'll create a new one.
4161 Entry->setName(StringRef());
4162
4163 // Make a new global with the correct type, this is now guaranteed to work.
4164 GV = cast<llvm::GlobalVariable>(
4165 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
4166 ->stripPointerCasts());
4167
4168 // Replace all uses of the old global with the new global
4169 llvm::Constant *NewPtrForOldDecl =
4170 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4171 Entry->replaceAllUsesWith(NewPtrForOldDecl);
4172
4173 // Erase the old global, since it is no longer used.
4174 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4175 }
4176
4177 MaybeHandleStaticInExternC(D, GV);
4178
4179 if (D->hasAttr<AnnotateAttr>())
4180 AddGlobalAnnotations(D, GV);
4181
4182 // Set the llvm linkage type as appropriate.
4183 llvm::GlobalValue::LinkageTypes Linkage =
4184 getLLVMLinkageVarDefinition(D, GV->isConstant());
4185
4186 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4187 // the device. [...]"
4188 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4189 // __device__, declares a variable that: [...]
4190 // Is accessible from all the threads within the grid and from the host
4191 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4192 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4193 if (GV && LangOpts.CUDA) {
4194 if (LangOpts.CUDAIsDevice) {
4195 if (Linkage != llvm::GlobalValue::InternalLinkage &&
4196 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
4197 GV->setExternallyInitialized(true);
4198 } else {
4199 // Host-side shadows of external declarations of device-side
4200 // global variables become internal definitions. These have to
4201 // be internal in order to prevent name conflicts with global
4202 // host variables with the same name in a different TUs.
4203 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
4204 Linkage = llvm::GlobalValue::InternalLinkage;
4205 // Shadow variables and their properties must be registered with CUDA
4206 // runtime. Skip Extern global variables, which will be registered in
4207 // the TU where they are defined.
4208 if (!D->hasExternalStorage())
4209 getCUDARuntime().registerDeviceVar(D, *GV, !D->hasDefinition(),
4210 D->hasAttr<CUDAConstantAttr>());
4211 } else if (D->hasAttr<CUDASharedAttr>()) {
4212 // __shared__ variables are odd. Shadows do get created, but
4213 // they are not registered with the CUDA runtime, so they
4214 // can't really be used to access their device-side
4215 // counterparts. It's not clear yet whether it's nvcc's bug or
4216 // a feature, but we've got to do the same for compatibility.
4217 Linkage = llvm::GlobalValue::InternalLinkage;
4218 } else if (D->getType()->isCUDADeviceBuiltinSurfaceType() ||
4219 D->getType()->isCUDADeviceBuiltinTextureType()) {
4220 // Builtin surfaces and textures and their template arguments are
4221 // also registered with CUDA runtime.
4222 Linkage = llvm::GlobalValue::InternalLinkage;
4223 const ClassTemplateSpecializationDecl *TD =
4224 cast<ClassTemplateSpecializationDecl>(
4225 D->getType()->getAs<RecordType>()->getDecl());
4226 const TemplateArgumentList &Args = TD->getTemplateArgs();
4227 if (TD->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) {
4228 assert(Args.size() == 2 &&
4229 "Unexpected number of template arguments of CUDA device "
4230 "builtin surface type.");
4231 auto SurfType = Args[1].getAsIntegral();
4232 if (!D->hasExternalStorage())
4233 getCUDARuntime().registerDeviceSurf(D, *GV, !D->hasDefinition(),
4234 SurfType.getSExtValue());
4235 } else {
4236 assert(Args.size() == 3 &&
4237 "Unexpected number of template arguments of CUDA device "
4238 "builtin texture type.");
4239 auto TexType = Args[1].getAsIntegral();
4240 auto Normalized = Args[2].getAsIntegral();
4241 if (!D->hasExternalStorage())
4242 getCUDARuntime().registerDeviceTex(D, *GV, !D->hasDefinition(),
4243 TexType.getSExtValue(),
4244 Normalized.getZExtValue());
4245 }
4246 }
4247 }
4248 }
4249
4250 GV->setInitializer(Init);
4251 if (emitter)
4252 emitter->finalize(GV);
4253
4254 // If it is safe to mark the global 'constant', do so now.
4255 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4256 isTypeConstant(D->getType(), true));
4257
4258 // If it is in a read-only section, mark it 'constant'.
4259 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4260 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4261 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4262 GV->setConstant(true);
4263 }
4264
4265 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4266
4267 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper
4268 // function is only defined alongside the variable, not also alongside
4269 // callers. Normally, all accesses to a thread_local go through the
4270 // thread-wrapper in order to ensure initialization has occurred, underlying
4271 // variable will never be used other than the thread-wrapper, so it can be
4272 // converted to internal linkage.
4273 //
4274 // However, if the variable has the 'constinit' attribute, it _can_ be
4275 // referenced directly, without calling the thread-wrapper, so the linkage
4276 // must not be changed.
4277 //
4278 // Additionally, if the variable isn't plain external linkage, e.g. if it's
4279 // weak or linkonce, the de-duplication semantics are important to preserve,
4280 // so we don't change the linkage.
4281 if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
4282 Linkage == llvm::GlobalValue::ExternalLinkage &&
4283 Context.getTargetInfo().getTriple().isOSDarwin() &&
4284 !D->hasAttr<ConstInitAttr>())
4285 Linkage = llvm::GlobalValue::InternalLinkage;
4286
4287 GV->setLinkage(Linkage);
4288 if (D->hasAttr<DLLImportAttr>())
4289 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4290 else if (D->hasAttr<DLLExportAttr>())
4291 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4292 else
4293 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4294
4295 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4296 // common vars aren't constant even if declared const.
4297 GV->setConstant(false);
4298 // Tentative definition of global variables may be initialized with
4299 // non-zero null pointers. In this case they should have weak linkage
4300 // since common linkage must have zero initializer and must not have
4301 // explicit section therefore cannot have non-zero initial value.
4302 if (!GV->getInitializer()->isNullValue())
4303 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4304 }
4305
4306 setNonAliasAttributes(D, GV);
4307
4308 if (D->getTLSKind() && !GV->isThreadLocal()) {
4309 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4310 CXXThreadLocals.push_back(D);
4311 setTLSMode(GV, *D);
4312 }
4313
4314 maybeSetTrivialComdat(*D, *GV);
4315
4316 // Emit the initializer function if necessary.
4317 if (NeedsGlobalCtor || NeedsGlobalDtor)
4318 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4319
4320 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4321
4322 // Emit global variable debug information.
4323 if (CGDebugInfo *DI = getModuleDebugInfo())
4324 if (getCodeGenOpts().hasReducedDebugInfo())
4325 DI->EmitGlobalVariable(GV, D);
4326 }
4327
EmitExternalVarDeclaration(const VarDecl * D)4328 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4329 if (CGDebugInfo *DI = getModuleDebugInfo())
4330 if (getCodeGenOpts().hasReducedDebugInfo()) {
4331 QualType ASTTy = D->getType();
4332 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4333 llvm::PointerType *PTy =
4334 llvm::PointerType::get(Ty, getAddressSpaceForType(ASTTy));
4335 llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4336 DI->EmitExternalVariable(
4337 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4338 }
4339 }
4340
isVarDeclStrongDefinition(const ASTContext & Context,CodeGenModule & CGM,const VarDecl * D,bool NoCommon)4341 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4342 CodeGenModule &CGM, const VarDecl *D,
4343 bool NoCommon) {
4344 // Don't give variables common linkage if -fno-common was specified unless it
4345 // was overridden by a NoCommon attribute.
4346 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4347 return true;
4348
4349 // C11 6.9.2/2:
4350 // A declaration of an identifier for an object that has file scope without
4351 // an initializer, and without a storage-class specifier or with the
4352 // storage-class specifier static, constitutes a tentative definition.
4353 if (D->getInit() || D->hasExternalStorage())
4354 return true;
4355
4356 // A variable cannot be both common and exist in a section.
4357 if (D->hasAttr<SectionAttr>())
4358 return true;
4359
4360 // A variable cannot be both common and exist in a section.
4361 // We don't try to determine which is the right section in the front-end.
4362 // If no specialized section name is applicable, it will resort to default.
4363 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4364 D->hasAttr<PragmaClangDataSectionAttr>() ||
4365 D->hasAttr<PragmaClangRelroSectionAttr>() ||
4366 D->hasAttr<PragmaClangRodataSectionAttr>())
4367 return true;
4368
4369 // Thread local vars aren't considered common linkage.
4370 if (D->getTLSKind())
4371 return true;
4372
4373 // Tentative definitions marked with WeakImportAttr are true definitions.
4374 if (D->hasAttr<WeakImportAttr>())
4375 return true;
4376
4377 // A variable cannot be both common and exist in a comdat.
4378 if (shouldBeInCOMDAT(CGM, *D))
4379 return true;
4380
4381 // Declarations with a required alignment do not have common linkage in MSVC
4382 // mode.
4383 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4384 if (D->hasAttr<AlignedAttr>())
4385 return true;
4386 QualType VarType = D->getType();
4387 if (Context.isAlignmentRequired(VarType))
4388 return true;
4389
4390 if (const auto *RT = VarType->getAs<RecordType>()) {
4391 const RecordDecl *RD = RT->getDecl();
4392 for (const FieldDecl *FD : RD->fields()) {
4393 if (FD->isBitField())
4394 continue;
4395 if (FD->hasAttr<AlignedAttr>())
4396 return true;
4397 if (Context.isAlignmentRequired(FD->getType()))
4398 return true;
4399 }
4400 }
4401 }
4402
4403 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4404 // common symbols, so symbols with greater alignment requirements cannot be
4405 // common.
4406 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4407 // alignments for common symbols via the aligncomm directive, so this
4408 // restriction only applies to MSVC environments.
4409 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4410 Context.getTypeAlignIfKnown(D->getType()) >
4411 Context.toBits(CharUnits::fromQuantity(32)))
4412 return true;
4413
4414 return false;
4415 }
4416
getLLVMLinkageForDeclarator(const DeclaratorDecl * D,GVALinkage Linkage,bool IsConstantVariable)4417 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4418 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4419 if (Linkage == GVA_Internal)
4420 return llvm::Function::InternalLinkage;
4421
4422 if (D->hasAttr<WeakAttr>()) {
4423 if (IsConstantVariable)
4424 return llvm::GlobalVariable::WeakODRLinkage;
4425 else
4426 return llvm::GlobalVariable::WeakAnyLinkage;
4427 }
4428
4429 if (const auto *FD = D->getAsFunction())
4430 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4431 return llvm::GlobalVariable::LinkOnceAnyLinkage;
4432
4433 // We are guaranteed to have a strong definition somewhere else,
4434 // so we can use available_externally linkage.
4435 if (Linkage == GVA_AvailableExternally)
4436 return llvm::GlobalValue::AvailableExternallyLinkage;
4437
4438 // Note that Apple's kernel linker doesn't support symbol
4439 // coalescing, so we need to avoid linkonce and weak linkages there.
4440 // Normally, this means we just map to internal, but for explicit
4441 // instantiations we'll map to external.
4442
4443 // In C++, the compiler has to emit a definition in every translation unit
4444 // that references the function. We should use linkonce_odr because
4445 // a) if all references in this translation unit are optimized away, we
4446 // don't need to codegen it. b) if the function persists, it needs to be
4447 // merged with other definitions. c) C++ has the ODR, so we know the
4448 // definition is dependable.
4449 if (Linkage == GVA_DiscardableODR)
4450 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4451 : llvm::Function::InternalLinkage;
4452
4453 // An explicit instantiation of a template has weak linkage, since
4454 // explicit instantiations can occur in multiple translation units
4455 // and must all be equivalent. However, we are not allowed to
4456 // throw away these explicit instantiations.
4457 //
4458 // We don't currently support CUDA device code spread out across multiple TUs,
4459 // so say that CUDA templates are either external (for kernels) or internal.
4460 // This lets llvm perform aggressive inter-procedural optimizations.
4461 if (Linkage == GVA_StrongODR) {
4462 if (Context.getLangOpts().AppleKext)
4463 return llvm::Function::ExternalLinkage;
4464 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
4465 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4466 : llvm::Function::InternalLinkage;
4467 return llvm::Function::WeakODRLinkage;
4468 }
4469
4470 // C++ doesn't have tentative definitions and thus cannot have common
4471 // linkage.
4472 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4473 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4474 CodeGenOpts.NoCommon))
4475 return llvm::GlobalVariable::CommonLinkage;
4476
4477 // selectany symbols are externally visible, so use weak instead of
4478 // linkonce. MSVC optimizes away references to const selectany globals, so
4479 // all definitions should be the same and ODR linkage should be used.
4480 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4481 if (D->hasAttr<SelectAnyAttr>())
4482 return llvm::GlobalVariable::WeakODRLinkage;
4483
4484 // Otherwise, we have strong external linkage.
4485 assert(Linkage == GVA_StrongExternal);
4486 return llvm::GlobalVariable::ExternalLinkage;
4487 }
4488
getLLVMLinkageVarDefinition(const VarDecl * VD,bool IsConstant)4489 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4490 const VarDecl *VD, bool IsConstant) {
4491 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4492 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4493 }
4494
4495 /// Replace the uses of a function that was declared with a non-proto type.
4496 /// We want to silently drop extra arguments from call sites
replaceUsesOfNonProtoConstant(llvm::Constant * old,llvm::Function * newFn)4497 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4498 llvm::Function *newFn) {
4499 // Fast path.
4500 if (old->use_empty()) return;
4501
4502 llvm::Type *newRetTy = newFn->getReturnType();
4503 SmallVector<llvm::Value*, 4> newArgs;
4504 SmallVector<llvm::OperandBundleDef, 1> newBundles;
4505
4506 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4507 ui != ue; ) {
4508 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4509 llvm::User *user = use->getUser();
4510
4511 // Recognize and replace uses of bitcasts. Most calls to
4512 // unprototyped functions will use bitcasts.
4513 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4514 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4515 replaceUsesOfNonProtoConstant(bitcast, newFn);
4516 continue;
4517 }
4518
4519 // Recognize calls to the function.
4520 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4521 if (!callSite) continue;
4522 if (!callSite->isCallee(&*use))
4523 continue;
4524
4525 // If the return types don't match exactly, then we can't
4526 // transform this call unless it's dead.
4527 if (callSite->getType() != newRetTy && !callSite->use_empty())
4528 continue;
4529
4530 // Get the call site's attribute list.
4531 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4532 llvm::AttributeList oldAttrs = callSite->getAttributes();
4533
4534 // If the function was passed too few arguments, don't transform.
4535 unsigned newNumArgs = newFn->arg_size();
4536 if (callSite->arg_size() < newNumArgs)
4537 continue;
4538
4539 // If extra arguments were passed, we silently drop them.
4540 // If any of the types mismatch, we don't transform.
4541 unsigned argNo = 0;
4542 bool dontTransform = false;
4543 for (llvm::Argument &A : newFn->args()) {
4544 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4545 dontTransform = true;
4546 break;
4547 }
4548
4549 // Add any parameter attributes.
4550 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4551 argNo++;
4552 }
4553 if (dontTransform)
4554 continue;
4555
4556 // Okay, we can transform this. Create the new call instruction and copy
4557 // over the required information.
4558 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4559
4560 // Copy over any operand bundles.
4561 callSite->getOperandBundlesAsDefs(newBundles);
4562
4563 llvm::CallBase *newCall;
4564 if (dyn_cast<llvm::CallInst>(callSite)) {
4565 newCall =
4566 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4567 } else {
4568 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4569 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4570 oldInvoke->getUnwindDest(), newArgs,
4571 newBundles, "", callSite);
4572 }
4573 newArgs.clear(); // for the next iteration
4574
4575 if (!newCall->getType()->isVoidTy())
4576 newCall->takeName(callSite);
4577 newCall->setAttributes(llvm::AttributeList::get(
4578 newFn->getContext(), oldAttrs.getFnAttributes(),
4579 oldAttrs.getRetAttributes(), newArgAttrs));
4580 newCall->setCallingConv(callSite->getCallingConv());
4581
4582 // Finally, remove the old call, replacing any uses with the new one.
4583 if (!callSite->use_empty())
4584 callSite->replaceAllUsesWith(newCall);
4585
4586 // Copy debug location attached to CI.
4587 if (callSite->getDebugLoc())
4588 newCall->setDebugLoc(callSite->getDebugLoc());
4589
4590 callSite->eraseFromParent();
4591 }
4592 }
4593
4594 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4595 /// implement a function with no prototype, e.g. "int foo() {}". If there are
4596 /// existing call uses of the old function in the module, this adjusts them to
4597 /// call the new function directly.
4598 ///
4599 /// This is not just a cleanup: the always_inline pass requires direct calls to
4600 /// functions to be able to inline them. If there is a bitcast in the way, it
4601 /// won't inline them. Instcombine normally deletes these calls, but it isn't
4602 /// run at -O0.
ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue * Old,llvm::Function * NewFn)4603 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4604 llvm::Function *NewFn) {
4605 // If we're redefining a global as a function, don't transform it.
4606 if (!isa<llvm::Function>(Old)) return;
4607
4608 replaceUsesOfNonProtoConstant(Old, NewFn);
4609 }
4610
HandleCXXStaticMemberVarInstantiation(VarDecl * VD)4611 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4612 auto DK = VD->isThisDeclarationADefinition();
4613 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4614 return;
4615
4616 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4617 // If we have a definition, this might be a deferred decl. If the
4618 // instantiation is explicit, make sure we emit it at the end.
4619 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4620 GetAddrOfGlobalVar(VD);
4621
4622 EmitTopLevelDecl(VD);
4623 }
4624
EmitGlobalFunctionDefinition(GlobalDecl GD,llvm::GlobalValue * GV)4625 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4626 llvm::GlobalValue *GV) {
4627 const auto *D = cast<FunctionDecl>(GD.getDecl());
4628
4629 // Compute the function info and LLVM type.
4630 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4631 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4632
4633 // Get or create the prototype for the function.
4634 if (!GV || (GV->getValueType() != Ty))
4635 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4636 /*DontDefer=*/true,
4637 ForDefinition));
4638
4639 // Already emitted.
4640 if (!GV->isDeclaration())
4641 return;
4642
4643 // We need to set linkage and visibility on the function before
4644 // generating code for it because various parts of IR generation
4645 // want to propagate this information down (e.g. to local static
4646 // declarations).
4647 auto *Fn = cast<llvm::Function>(GV);
4648 setFunctionLinkage(GD, Fn);
4649
4650 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4651 setGVProperties(Fn, GD);
4652
4653 MaybeHandleStaticInExternC(D, Fn);
4654
4655
4656 maybeSetTrivialComdat(*D, *Fn);
4657
4658 CodeGenFunction(*this).GenerateCode(GD, Fn, FI);
4659
4660 setNonAliasAttributes(GD, Fn);
4661 SetLLVMFunctionAttributesForDefinition(D, Fn);
4662
4663 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4664 AddGlobalCtor(Fn, CA->getPriority());
4665 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4666 AddGlobalDtor(Fn, DA->getPriority());
4667 if (D->hasAttr<AnnotateAttr>())
4668 AddGlobalAnnotations(D, Fn);
4669 }
4670
EmitAliasDefinition(GlobalDecl GD)4671 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4672 const auto *D = cast<ValueDecl>(GD.getDecl());
4673 const AliasAttr *AA = D->getAttr<AliasAttr>();
4674 assert(AA && "Not an alias?");
4675
4676 StringRef MangledName = getMangledName(GD);
4677
4678 if (AA->getAliasee() == MangledName) {
4679 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4680 return;
4681 }
4682
4683 // If there is a definition in the module, then it wins over the alias.
4684 // This is dubious, but allow it to be safe. Just ignore the alias.
4685 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4686 if (Entry && !Entry->isDeclaration())
4687 return;
4688
4689 Aliases.push_back(GD);
4690
4691 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4692
4693 // Create a reference to the named value. This ensures that it is emitted
4694 // if a deferred decl.
4695 llvm::Constant *Aliasee;
4696 llvm::GlobalValue::LinkageTypes LT;
4697 if (isa<llvm::FunctionType>(DeclTy)) {
4698 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4699 /*ForVTable=*/false);
4700 LT = getFunctionLinkage(GD);
4701 } else {
4702 unsigned AS = getDataLayout().getGlobalsAddressSpace();
4703 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4704 llvm::PointerType::get(DeclTy, AS),
4705 /*D=*/nullptr);
4706 LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
4707 D->getType().isConstQualified());
4708 }
4709
4710 // Create the new alias itself, but don't set a name yet.
4711 unsigned AS = Aliasee->getType()->getPointerAddressSpace();
4712 auto *GA =
4713 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule());
4714
4715 if (Entry) {
4716 if (GA->getAliasee() == Entry) {
4717 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4718 return;
4719 }
4720
4721 assert(Entry->isDeclaration());
4722
4723 // If there is a declaration in the module, then we had an extern followed
4724 // by the alias, as in:
4725 // extern int test6();
4726 // ...
4727 // int test6() __attribute__((alias("test7")));
4728 //
4729 // Remove it and replace uses of it with the alias.
4730 GA->takeName(Entry);
4731
4732 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4733 Entry->getType()));
4734 Entry->eraseFromParent();
4735 } else {
4736 GA->setName(MangledName);
4737 }
4738
4739 // Set attributes which are particular to an alias; this is a
4740 // specialization of the attributes which may be set on a global
4741 // variable/function.
4742 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4743 D->isWeakImported()) {
4744 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4745 }
4746
4747 if (const auto *VD = dyn_cast<VarDecl>(D))
4748 if (VD->getTLSKind())
4749 setTLSMode(GA, *VD);
4750
4751 SetCommonAttributes(GD, GA);
4752 }
4753
emitIFuncDefinition(GlobalDecl GD)4754 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4755 const auto *D = cast<ValueDecl>(GD.getDecl());
4756 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4757 assert(IFA && "Not an ifunc?");
4758
4759 StringRef MangledName = getMangledName(GD);
4760
4761 if (IFA->getResolver() == MangledName) {
4762 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4763 return;
4764 }
4765
4766 // Report an error if some definition overrides ifunc.
4767 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4768 if (Entry && !Entry->isDeclaration()) {
4769 GlobalDecl OtherGD;
4770 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4771 DiagnosedConflictingDefinitions.insert(GD).second) {
4772 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4773 << MangledName;
4774 Diags.Report(OtherGD.getDecl()->getLocation(),
4775 diag::note_previous_definition);
4776 }
4777 return;
4778 }
4779
4780 Aliases.push_back(GD);
4781
4782 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4783 llvm::Constant *Resolver =
4784 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4785 /*ForVTable=*/false);
4786 llvm::GlobalIFunc *GIF =
4787 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4788 "", Resolver, &getModule());
4789 if (Entry) {
4790 if (GIF->getResolver() == Entry) {
4791 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4792 return;
4793 }
4794 assert(Entry->isDeclaration());
4795
4796 // If there is a declaration in the module, then we had an extern followed
4797 // by the ifunc, as in:
4798 // extern int test();
4799 // ...
4800 // int test() __attribute__((ifunc("resolver")));
4801 //
4802 // Remove it and replace uses of it with the ifunc.
4803 GIF->takeName(Entry);
4804
4805 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4806 Entry->getType()));
4807 Entry->eraseFromParent();
4808 } else
4809 GIF->setName(MangledName);
4810
4811 SetCommonAttributes(GD, GIF);
4812 }
4813
getIntrinsic(unsigned IID,ArrayRef<llvm::Type * > Tys)4814 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4815 ArrayRef<llvm::Type*> Tys) {
4816 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4817 Tys);
4818 }
4819
4820 static llvm::StringMapEntry<llvm::GlobalVariable *> &
GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable * > & Map,const StringLiteral * Literal,bool TargetIsLSB,bool & IsUTF16,unsigned & StringLength)4821 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4822 const StringLiteral *Literal, bool TargetIsLSB,
4823 bool &IsUTF16, unsigned &StringLength) {
4824 StringRef String = Literal->getString();
4825 unsigned NumBytes = String.size();
4826
4827 // Check for simple case.
4828 if (!Literal->containsNonAsciiOrNull()) {
4829 StringLength = NumBytes;
4830 return *Map.insert(std::make_pair(String, nullptr)).first;
4831 }
4832
4833 // Otherwise, convert the UTF8 literals into a string of shorts.
4834 IsUTF16 = true;
4835
4836 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4837 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4838 llvm::UTF16 *ToPtr = &ToBuf[0];
4839
4840 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4841 ToPtr + NumBytes, llvm::strictConversion);
4842
4843 // ConvertUTF8toUTF16 returns the length in ToPtr.
4844 StringLength = ToPtr - &ToBuf[0];
4845
4846 // Add an explicit null.
4847 *ToPtr = 0;
4848 return *Map.insert(std::make_pair(
4849 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4850 (StringLength + 1) * 2),
4851 nullptr)).first;
4852 }
4853
4854 ConstantAddress
GetAddrOfConstantCFString(const StringLiteral * Literal)4855 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4856 unsigned StringLength = 0;
4857 bool isUTF16 = false;
4858 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4859 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4860 getDataLayout().isLittleEndian(), isUTF16,
4861 StringLength);
4862
4863 if (auto *C = Entry.second)
4864 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4865
4866 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4867 llvm::Constant *Zeros[] = { Zero, Zero };
4868
4869 const ASTContext &Context = getContext();
4870 const llvm::Triple &Triple = getTriple();
4871
4872 const auto CFRuntime = getLangOpts().CFRuntime;
4873 const bool IsSwiftABI =
4874 static_cast<unsigned>(CFRuntime) >=
4875 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4876 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4877
4878 // If we don't already have it, get __CFConstantStringClassReference.
4879 if (!CFConstantStringClassRef) {
4880 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
4881 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4882 Ty = llvm::ArrayType::get(Ty, 0);
4883
4884 switch (CFRuntime) {
4885 default: break;
4886 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
4887 case LangOptions::CoreFoundationABI::Swift5_0:
4888 CFConstantStringClassName =
4889 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4890 : "$s10Foundation19_NSCFConstantStringCN";
4891 Ty = IntPtrTy;
4892 break;
4893 case LangOptions::CoreFoundationABI::Swift4_2:
4894 CFConstantStringClassName =
4895 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4896 : "$S10Foundation19_NSCFConstantStringCN";
4897 Ty = IntPtrTy;
4898 break;
4899 case LangOptions::CoreFoundationABI::Swift4_1:
4900 CFConstantStringClassName =
4901 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4902 : "__T010Foundation19_NSCFConstantStringCN";
4903 Ty = IntPtrTy;
4904 break;
4905 }
4906
4907 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4908
4909 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4910 llvm::GlobalValue *GV = nullptr;
4911
4912 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4913 IdentifierInfo &II = Context.Idents.get(GV->getName());
4914 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4915 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4916
4917 const VarDecl *VD = nullptr;
4918 for (const auto &Result : DC->lookup(&II))
4919 if ((VD = dyn_cast<VarDecl>(Result)))
4920 break;
4921
4922 if (Triple.isOSBinFormatELF()) {
4923 if (!VD)
4924 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4925 } else {
4926 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4927 if (!VD || !VD->hasAttr<DLLExportAttr>())
4928 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4929 else
4930 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4931 }
4932
4933 setDSOLocal(GV);
4934 }
4935 }
4936
4937 // Decay array -> ptr
4938 CFConstantStringClassRef =
4939 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4940 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4941 }
4942
4943 QualType CFTy = Context.getCFConstantStringType();
4944
4945 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4946
4947 ConstantInitBuilder Builder(*this);
4948 auto Fields = Builder.beginStruct(STy);
4949
4950 // Class pointer.
4951 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4952
4953 // Flags.
4954 if (IsSwiftABI) {
4955 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4956 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4957 } else {
4958 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4959 }
4960
4961 // String pointer.
4962 llvm::Constant *C = nullptr;
4963 if (isUTF16) {
4964 auto Arr = llvm::makeArrayRef(
4965 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4966 Entry.first().size() / 2);
4967 C = llvm::ConstantDataArray::get(VMContext, Arr);
4968 } else {
4969 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4970 }
4971
4972 // Note: -fwritable-strings doesn't make the backing store strings of
4973 // CFStrings writable. (See <rdar://problem/10657500>)
4974 auto GV =
4975 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4976 llvm::GlobalValue::PrivateLinkage, C, ".str", nullptr,
4977 llvm::GlobalVariable::NotThreadLocal,
4978 getTargetCodeGenInfo().getDefaultAS());
4979 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4980 // Don't enforce the target's minimum global alignment, since the only use
4981 // of the string is via this class initializer.
4982 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4983 : Context.getTypeAlignInChars(Context.CharTy);
4984 GV->setAlignment(Align.getAsAlign());
4985
4986 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4987 // Without it LLVM can merge the string with a non unnamed_addr one during
4988 // LTO. Doing that changes the section it ends in, which surprises ld64.
4989 if (Triple.isOSBinFormatMachO())
4990 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4991 : "__TEXT,__cstring,cstring_literals");
4992 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4993 // the static linker to adjust permissions to read-only later on.
4994 else if (Triple.isOSBinFormatELF())
4995 GV->setSection(".rodata");
4996
4997 // String.
4998 llvm::Constant *Str =
4999 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
5000
5001 if (isUTF16)
5002 // Cast the UTF16 string to the correct type.
5003 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
5004 Fields.add(Str);
5005
5006 // String length.
5007 llvm::IntegerType *LengthTy =
5008 llvm::IntegerType::get(getModule().getContext(),
5009 Context.getTargetInfo().getLongWidth());
5010 if (IsSwiftABI) {
5011 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
5012 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
5013 LengthTy = Int32Ty;
5014 else
5015 LengthTy = IntPtrTy;
5016 }
5017 Fields.addInt(LengthTy, StringLength);
5018
5019 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
5020 // properly aligned on 32-bit platforms.
5021 CharUnits Alignment =
5022 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
5023
5024 // The struct.
5025 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
5026 /*isConstant=*/false,
5027 llvm::GlobalVariable::PrivateLinkage);
5028 GV->addAttribute("objc_arc_inert");
5029 switch (Triple.getObjectFormat()) {
5030 case llvm::Triple::UnknownObjectFormat:
5031 llvm_unreachable("unknown file format");
5032 case llvm::Triple::XCOFF:
5033 llvm_unreachable("XCOFF is not yet implemented");
5034 case llvm::Triple::COFF:
5035 case llvm::Triple::ELF:
5036 case llvm::Triple::Wasm:
5037 GV->setSection("cfstring");
5038 break;
5039 case llvm::Triple::MachO:
5040 GV->setSection("__DATA,__cfstring");
5041 break;
5042 }
5043 Entry.second = GV;
5044
5045 return ConstantAddress(GV, Alignment);
5046 }
5047
getExpressionLocationsEnabled() const5048 bool CodeGenModule::getExpressionLocationsEnabled() const {
5049 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
5050 }
5051
getObjCFastEnumerationStateType()5052 QualType CodeGenModule::getObjCFastEnumerationStateType() {
5053 if (ObjCFastEnumerationStateType.isNull()) {
5054 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
5055 D->startDefinition();
5056
5057 QualType FieldTypes[] = {
5058 Context.UnsignedLongTy,
5059 Context.getPointerType(Context.getObjCIdType()),
5060 Context.getPointerType(Context.UnsignedLongTy),
5061 Context.getConstantArrayType(Context.UnsignedLongTy,
5062 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
5063 };
5064
5065 for (size_t i = 0; i < 4; ++i) {
5066 FieldDecl *Field = FieldDecl::Create(Context,
5067 D,
5068 SourceLocation(),
5069 SourceLocation(), nullptr,
5070 FieldTypes[i], /*TInfo=*/nullptr,
5071 /*BitWidth=*/nullptr,
5072 /*Mutable=*/false,
5073 ICIS_NoInit);
5074 Field->setAccess(AS_public);
5075 D->addDecl(Field);
5076 }
5077
5078 D->completeDefinition();
5079 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
5080 }
5081
5082 return ObjCFastEnumerationStateType;
5083 }
5084
5085 llvm::Constant *
GetConstantArrayFromStringLiteral(const StringLiteral * E)5086 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
5087 assert(!E->getType()->isPointerType() && "Strings are always arrays");
5088
5089 // Don't emit it as the address of the string, emit the string data itself
5090 // as an inline array.
5091 if (E->getCharByteWidth() == 1) {
5092 SmallString<64> Str(E->getString());
5093
5094 // Resize the string to the right size, which is indicated by its type.
5095 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
5096 Str.resize(CAT->getSize().getZExtValue());
5097 return llvm::ConstantDataArray::getString(VMContext, Str, false);
5098 }
5099
5100 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
5101 llvm::Type *ElemTy = AType->getElementType();
5102 unsigned NumElements = AType->getNumElements();
5103
5104 // Wide strings have either 2-byte or 4-byte elements.
5105 if (ElemTy->getPrimitiveSizeInBits() == 16) {
5106 SmallVector<uint16_t, 32> Elements;
5107 Elements.reserve(NumElements);
5108
5109 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5110 Elements.push_back(E->getCodeUnit(i));
5111 Elements.resize(NumElements);
5112 return llvm::ConstantDataArray::get(VMContext, Elements);
5113 }
5114
5115 assert(ElemTy->getPrimitiveSizeInBits() == 32);
5116 SmallVector<uint32_t, 32> Elements;
5117 Elements.reserve(NumElements);
5118
5119 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
5120 Elements.push_back(E->getCodeUnit(i));
5121 Elements.resize(NumElements);
5122 return llvm::ConstantDataArray::get(VMContext, Elements);
5123 }
5124
5125 static llvm::GlobalVariable *
GenerateStringLiteral(llvm::Constant * C,llvm::GlobalValue::LinkageTypes LT,CodeGenModule & CGM,StringRef GlobalName,CharUnits Alignment)5126 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
5127 CodeGenModule &CGM, StringRef GlobalName,
5128 CharUnits Alignment) {
5129 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
5130 CGM.getStringLiteralAddressSpace());
5131
5132 llvm::Module &M = CGM.getModule();
5133 // Create a global variable for this string
5134 auto *GV = new llvm::GlobalVariable(
5135 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
5136 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
5137 GV->setAlignment(Alignment.getAsAlign());
5138 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
5139 if (GV->isWeakForLinker()) {
5140 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
5141 GV->setComdat(M.getOrInsertComdat(GV->getName()));
5142 }
5143 CGM.setDSOLocal(GV);
5144
5145 return GV;
5146 }
5147
5148 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
5149 /// constant array for the given string literal.
5150 ConstantAddress
GetAddrOfConstantStringFromLiteral(const StringLiteral * S,StringRef Name)5151 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
5152 StringRef Name) {
5153 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
5154
5155 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
5156 llvm::GlobalVariable **Entry = nullptr;
5157 if (!LangOpts.WritableStrings) {
5158 Entry = &ConstantStringMap[C];
5159 if (auto GV = *Entry) {
5160 if (Alignment.getQuantity() > GV->getAlignment())
5161 GV->setAlignment(Alignment.getAsAlign());
5162 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5163 Alignment);
5164 }
5165 }
5166
5167 SmallString<256> MangledNameBuffer;
5168 StringRef GlobalVariableName;
5169 llvm::GlobalValue::LinkageTypes LT;
5170
5171 // Mangle the string literal if that's how the ABI merges duplicate strings.
5172 // Don't do it if they are writable, since we don't want writes in one TU to
5173 // affect strings in another.
5174 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
5175 !LangOpts.WritableStrings) {
5176 llvm::raw_svector_ostream Out(MangledNameBuffer);
5177 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
5178 LT = llvm::GlobalValue::LinkOnceODRLinkage;
5179 GlobalVariableName = MangledNameBuffer;
5180 } else {
5181 LT = llvm::GlobalValue::PrivateLinkage;
5182 GlobalVariableName = Name;
5183 }
5184
5185 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
5186 if (Entry)
5187 *Entry = GV;
5188
5189 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
5190 QualType());
5191
5192 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5193 Alignment);
5194 }
5195
5196 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5197 /// array for the given ObjCEncodeExpr node.
5198 ConstantAddress
GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr * E)5199 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5200 std::string Str;
5201 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5202
5203 return GetAddrOfConstantCString(Str);
5204 }
5205
5206 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5207 /// the literal and a terminating '\0' character.
5208 /// The result has pointer to array type.
GetAddrOfConstantCString(const std::string & Str,const char * GlobalName)5209 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5210 const std::string &Str, const char *GlobalName) {
5211 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5212 CharUnits Alignment =
5213 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5214
5215 llvm::Constant *C =
5216 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5217
5218 // Don't share any string literals if strings aren't constant.
5219 llvm::GlobalVariable **Entry = nullptr;
5220 if (!LangOpts.WritableStrings) {
5221 Entry = &ConstantStringMap[C];
5222 if (auto GV = *Entry) {
5223 if (Alignment.getQuantity() > GV->getAlignment())
5224 GV->setAlignment(Alignment.getAsAlign());
5225 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5226 Alignment);
5227 }
5228 }
5229
5230 // Get the default prefix if a name wasn't specified.
5231 if (!GlobalName)
5232 GlobalName = ".str";
5233 // Create a global variable for this.
5234 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5235 GlobalName, Alignment);
5236 if (Entry)
5237 *Entry = GV;
5238
5239 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5240 Alignment);
5241 }
5242
GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr * E,const Expr * Init)5243 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5244 const MaterializeTemporaryExpr *E, const Expr *Init) {
5245 assert((E->getStorageDuration() == SD_Static ||
5246 E->getStorageDuration() == SD_Thread) && "not a global temporary");
5247 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5248
5249 // If we're not materializing a subobject of the temporary, keep the
5250 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5251 QualType MaterializedType = Init->getType();
5252 if (Init == E->getSubExpr())
5253 MaterializedType = E->getType();
5254
5255 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5256
5257 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
5258 return ConstantAddress(Slot, Align);
5259
5260 // FIXME: If an externally-visible declaration extends multiple temporaries,
5261 // we need to give each temporary the same name in every translation unit (and
5262 // we also need to make the temporaries externally-visible).
5263 SmallString<256> Name;
5264 llvm::raw_svector_ostream Out(Name);
5265 getCXXABI().getMangleContext().mangleReferenceTemporary(
5266 VD, E->getManglingNumber(), Out);
5267
5268 APValue *Value = nullptr;
5269 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5270 // If the initializer of the extending declaration is a constant
5271 // initializer, we should have a cached constant initializer for this
5272 // temporary. Note that this might have a different value from the value
5273 // computed by evaluating the initializer if the surrounding constant
5274 // expression modifies the temporary.
5275 Value = E->getOrCreateValue(false);
5276 }
5277
5278 // Try evaluating it now, it might have a constant initializer.
5279 Expr::EvalResult EvalResult;
5280 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5281 !EvalResult.hasSideEffects())
5282 Value = &EvalResult.Val;
5283
5284 LangAS AddrSpace =
5285 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5286
5287 Optional<ConstantEmitter> emitter;
5288 llvm::Constant *InitialValue = nullptr;
5289 bool Constant = false;
5290 llvm::Type *Type;
5291 if (Value) {
5292 // The temporary has a constant initializer, use it.
5293 emitter.emplace(*this);
5294 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5295 MaterializedType);
5296 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5297 Type = InitialValue->getType();
5298 } else {
5299 // No initializer, the initialization will be provided when we
5300 // initialize the declaration which performed lifetime extension.
5301 Type = getTypes().ConvertTypeForMem(MaterializedType);
5302 }
5303
5304 // Create a global variable for this lifetime-extended temporary.
5305 llvm::GlobalValue::LinkageTypes Linkage =
5306 getLLVMLinkageVarDefinition(VD, Constant);
5307 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5308 const VarDecl *InitVD;
5309 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5310 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5311 // Temporaries defined inside a class get linkonce_odr linkage because the
5312 // class can be defined in multiple translation units.
5313 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5314 } else {
5315 // There is no need for this temporary to have external linkage if the
5316 // VarDecl has external linkage.
5317 Linkage = llvm::GlobalVariable::InternalLinkage;
5318 }
5319 }
5320 auto TargetAS = getTargetAddressSpace(AddrSpace);
5321 auto *GV = new llvm::GlobalVariable(
5322 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5323 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5324 if (emitter) emitter->finalize(GV);
5325 setGVProperties(GV, VD);
5326 GV->setAlignment(Align.getAsAlign());
5327 if (supportsCOMDAT() && GV->isWeakForLinker())
5328 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5329 if (VD->getTLSKind())
5330 setTLSMode(GV, *VD);
5331 llvm::Constant *CV = GV;
5332 if (AddrSpace != LangAS::Default)
5333 CV = getTargetCodeGenInfo().performAddrSpaceCast(
5334 *this, GV, AddrSpace, LangAS::Default,
5335 Type->getPointerTo(getTargetAddressSpace(LangAS::Default)));
5336 MaterializedGlobalTemporaryMap[E] = CV;
5337 return ConstantAddress(CV, Align);
5338 }
5339
5340 /// EmitObjCPropertyImplementations - Emit information for synthesized
5341 /// properties for an implementation.
EmitObjCPropertyImplementations(const ObjCImplementationDecl * D)5342 void CodeGenModule::EmitObjCPropertyImplementations(const
5343 ObjCImplementationDecl *D) {
5344 for (const auto *PID : D->property_impls()) {
5345 // Dynamic is just for type-checking.
5346 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5347 ObjCPropertyDecl *PD = PID->getPropertyDecl();
5348
5349 // Determine which methods need to be implemented, some may have
5350 // been overridden. Note that ::isPropertyAccessor is not the method
5351 // we want, that just indicates if the decl came from a
5352 // property. What we want to know is if the method is defined in
5353 // this implementation.
5354 auto *Getter = PID->getGetterMethodDecl();
5355 if (!Getter || Getter->isSynthesizedAccessorStub())
5356 CodeGenFunction(*this).GenerateObjCGetter(
5357 const_cast<ObjCImplementationDecl *>(D), PID);
5358 auto *Setter = PID->getSetterMethodDecl();
5359 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5360 CodeGenFunction(*this).GenerateObjCSetter(
5361 const_cast<ObjCImplementationDecl *>(D), PID);
5362 }
5363 }
5364 }
5365
needsDestructMethod(ObjCImplementationDecl * impl)5366 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5367 const ObjCInterfaceDecl *iface = impl->getClassInterface();
5368 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5369 ivar; ivar = ivar->getNextIvar())
5370 if (ivar->getType().isDestructedType())
5371 return true;
5372
5373 return false;
5374 }
5375
AllTrivialInitializers(CodeGenModule & CGM,ObjCImplementationDecl * D)5376 static bool AllTrivialInitializers(CodeGenModule &CGM,
5377 ObjCImplementationDecl *D) {
5378 CodeGenFunction CGF(CGM);
5379 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5380 E = D->init_end(); B != E; ++B) {
5381 CXXCtorInitializer *CtorInitExp = *B;
5382 Expr *Init = CtorInitExp->getInit();
5383 if (!CGF.isTrivialInitializer(Init))
5384 return false;
5385 }
5386 return true;
5387 }
5388
5389 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5390 /// for an implementation.
EmitObjCIvarInitializations(ObjCImplementationDecl * D)5391 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5392 // We might need a .cxx_destruct even if we don't have any ivar initializers.
5393 if (needsDestructMethod(D)) {
5394 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5395 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5396 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5397 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5398 getContext().VoidTy, nullptr, D,
5399 /*isInstance=*/true, /*isVariadic=*/false,
5400 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5401 /*isImplicitlyDeclared=*/true,
5402 /*isDefined=*/false, ObjCMethodDecl::Required);
5403 D->addInstanceMethod(DTORMethod);
5404 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5405 D->setHasDestructors(true);
5406 }
5407
5408 // If the implementation doesn't have any ivar initializers, we don't need
5409 // a .cxx_construct.
5410 if (D->getNumIvarInitializers() == 0 ||
5411 AllTrivialInitializers(*this, D))
5412 return;
5413
5414 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5415 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5416 // The constructor returns 'self'.
5417 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5418 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5419 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5420 /*isVariadic=*/false,
5421 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5422 /*isImplicitlyDeclared=*/true,
5423 /*isDefined=*/false, ObjCMethodDecl::Required);
5424 D->addInstanceMethod(CTORMethod);
5425 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5426 D->setHasNonZeroConstructors(true);
5427 }
5428
5429 // EmitLinkageSpec - Emit all declarations in a linkage spec.
EmitLinkageSpec(const LinkageSpecDecl * LSD)5430 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5431 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5432 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5433 ErrorUnsupported(LSD, "linkage spec");
5434 return;
5435 }
5436
5437 EmitDeclContext(LSD);
5438 }
5439
EmitDeclContext(const DeclContext * DC)5440 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5441 for (auto *I : DC->decls()) {
5442 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5443 // are themselves considered "top-level", so EmitTopLevelDecl on an
5444 // ObjCImplDecl does not recursively visit them. We need to do that in
5445 // case they're nested inside another construct (LinkageSpecDecl /
5446 // ExportDecl) that does stop them from being considered "top-level".
5447 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5448 for (auto *M : OID->methods())
5449 EmitTopLevelDecl(M);
5450 }
5451
5452 EmitTopLevelDecl(I);
5453 }
5454 }
5455
5456 /// EmitTopLevelDecl - Emit code for a single top level declaration.
EmitTopLevelDecl(Decl * D)5457 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5458 // Ignore dependent declarations.
5459 if (D->isTemplated())
5460 return;
5461
5462 // Consteval function shouldn't be emitted.
5463 if (auto *FD = dyn_cast<FunctionDecl>(D))
5464 if (FD->isConsteval())
5465 return;
5466
5467 switch (D->getKind()) {
5468 case Decl::CXXConversion:
5469 case Decl::CXXMethod:
5470 case Decl::Function:
5471 EmitGlobal(cast<FunctionDecl>(D));
5472 // Always provide some coverage mapping
5473 // even for the functions that aren't emitted.
5474 AddDeferredUnusedCoverageMapping(D);
5475 break;
5476
5477 case Decl::CXXDeductionGuide:
5478 // Function-like, but does not result in code emission.
5479 break;
5480
5481 case Decl::Var:
5482 case Decl::Decomposition:
5483 case Decl::VarTemplateSpecialization:
5484 EmitGlobal(cast<VarDecl>(D));
5485 if (auto *DD = dyn_cast<DecompositionDecl>(D))
5486 for (auto *B : DD->bindings())
5487 if (auto *HD = B->getHoldingVar())
5488 EmitGlobal(HD);
5489 break;
5490
5491 // Indirect fields from global anonymous structs and unions can be
5492 // ignored; only the actual variable requires IR gen support.
5493 case Decl::IndirectField:
5494 break;
5495
5496 // C++ Decls
5497 case Decl::Namespace:
5498 EmitDeclContext(cast<NamespaceDecl>(D));
5499 break;
5500 case Decl::ClassTemplateSpecialization: {
5501 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5502 if (CGDebugInfo *DI = getModuleDebugInfo())
5503 if (Spec->getSpecializationKind() ==
5504 TSK_ExplicitInstantiationDefinition &&
5505 Spec->hasDefinition())
5506 DI->completeTemplateDefinition(*Spec);
5507 } LLVM_FALLTHROUGH;
5508 case Decl::CXXRecord:
5509 if (CGDebugInfo *DI = getModuleDebugInfo())
5510 if (auto *ES = D->getASTContext().getExternalSource())
5511 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5512 DI->completeUnusedClass(cast<CXXRecordDecl>(*D));
5513 // Emit any static data members, they may be definitions.
5514 for (auto *I : cast<CXXRecordDecl>(D)->decls())
5515 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5516 EmitTopLevelDecl(I);
5517 break;
5518 // No code generation needed.
5519 case Decl::UsingShadow:
5520 case Decl::ClassTemplate:
5521 case Decl::VarTemplate:
5522 case Decl::Concept:
5523 case Decl::VarTemplatePartialSpecialization:
5524 case Decl::FunctionTemplate:
5525 case Decl::TypeAliasTemplate:
5526 case Decl::Block:
5527 case Decl::Empty:
5528 case Decl::Binding:
5529 break;
5530 case Decl::Using: // using X; [C++]
5531 if (CGDebugInfo *DI = getModuleDebugInfo())
5532 DI->EmitUsingDecl(cast<UsingDecl>(*D));
5533 break;
5534 case Decl::NamespaceAlias:
5535 if (CGDebugInfo *DI = getModuleDebugInfo())
5536 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5537 break;
5538 case Decl::UsingDirective: // using namespace X; [C++]
5539 if (CGDebugInfo *DI = getModuleDebugInfo())
5540 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5541 break;
5542 case Decl::CXXConstructor:
5543 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5544 break;
5545 case Decl::CXXDestructor:
5546 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5547 break;
5548
5549 case Decl::StaticAssert:
5550 // Nothing to do.
5551 break;
5552
5553 // Objective-C Decls
5554
5555 // Forward declarations, no (immediate) code generation.
5556 case Decl::ObjCInterface:
5557 case Decl::ObjCCategory:
5558 break;
5559
5560 case Decl::ObjCProtocol: {
5561 auto *Proto = cast<ObjCProtocolDecl>(D);
5562 if (Proto->isThisDeclarationADefinition())
5563 ObjCRuntime->GenerateProtocol(Proto);
5564 break;
5565 }
5566
5567 case Decl::ObjCCategoryImpl:
5568 // Categories have properties but don't support synthesize so we
5569 // can ignore them here.
5570 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5571 break;
5572
5573 case Decl::ObjCImplementation: {
5574 auto *OMD = cast<ObjCImplementationDecl>(D);
5575 EmitObjCPropertyImplementations(OMD);
5576 EmitObjCIvarInitializations(OMD);
5577 ObjCRuntime->GenerateClass(OMD);
5578 // Emit global variable debug information.
5579 if (CGDebugInfo *DI = getModuleDebugInfo())
5580 if (getCodeGenOpts().hasReducedDebugInfo())
5581 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5582 OMD->getClassInterface()), OMD->getLocation());
5583 break;
5584 }
5585 case Decl::ObjCMethod: {
5586 auto *OMD = cast<ObjCMethodDecl>(D);
5587 // If this is not a prototype, emit the body.
5588 if (OMD->getBody())
5589 CodeGenFunction(*this).GenerateObjCMethod(OMD);
5590 break;
5591 }
5592 case Decl::ObjCCompatibleAlias:
5593 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5594 break;
5595
5596 case Decl::PragmaComment: {
5597 const auto *PCD = cast<PragmaCommentDecl>(D);
5598 switch (PCD->getCommentKind()) {
5599 case PCK_Unknown:
5600 llvm_unreachable("unexpected pragma comment kind");
5601 case PCK_Linker:
5602 AppendLinkerOptions(PCD->getArg());
5603 break;
5604 case PCK_Lib:
5605 AddDependentLib(PCD->getArg());
5606 break;
5607 case PCK_Compiler:
5608 case PCK_ExeStr:
5609 case PCK_User:
5610 break; // We ignore all of these.
5611 }
5612 break;
5613 }
5614
5615 case Decl::PragmaDetectMismatch: {
5616 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5617 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5618 break;
5619 }
5620
5621 case Decl::LinkageSpec:
5622 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5623 break;
5624
5625 case Decl::FileScopeAsm: {
5626 // File-scope asm is ignored during device-side CUDA compilation.
5627 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5628 break;
5629 // File-scope asm is ignored during device-side OpenMP compilation.
5630 if (LangOpts.OpenMPIsDevice)
5631 break;
5632 auto *AD = cast<FileScopeAsmDecl>(D);
5633 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5634 break;
5635 }
5636
5637 case Decl::Import: {
5638 auto *Import = cast<ImportDecl>(D);
5639
5640 // If we've already imported this module, we're done.
5641 if (!ImportedModules.insert(Import->getImportedModule()))
5642 break;
5643
5644 // Emit debug information for direct imports.
5645 if (!Import->getImportedOwningModule()) {
5646 if (CGDebugInfo *DI = getModuleDebugInfo())
5647 DI->EmitImportDecl(*Import);
5648 }
5649
5650 // Find all of the submodules and emit the module initializers.
5651 llvm::SmallPtrSet<clang::Module *, 16> Visited;
5652 SmallVector<clang::Module *, 16> Stack;
5653 Visited.insert(Import->getImportedModule());
5654 Stack.push_back(Import->getImportedModule());
5655
5656 while (!Stack.empty()) {
5657 clang::Module *Mod = Stack.pop_back_val();
5658 if (!EmittedModuleInitializers.insert(Mod).second)
5659 continue;
5660
5661 for (auto *D : Context.getModuleInitializers(Mod))
5662 EmitTopLevelDecl(D);
5663
5664 // Visit the submodules of this module.
5665 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5666 SubEnd = Mod->submodule_end();
5667 Sub != SubEnd; ++Sub) {
5668 // Skip explicit children; they need to be explicitly imported to emit
5669 // the initializers.
5670 if ((*Sub)->IsExplicit)
5671 continue;
5672
5673 if (Visited.insert(*Sub).second)
5674 Stack.push_back(*Sub);
5675 }
5676 }
5677 break;
5678 }
5679
5680 case Decl::Export:
5681 EmitDeclContext(cast<ExportDecl>(D));
5682 break;
5683
5684 case Decl::OMPThreadPrivate:
5685 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5686 break;
5687
5688 case Decl::OMPAllocate:
5689 break;
5690
5691 case Decl::OMPDeclareReduction:
5692 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5693 break;
5694
5695 case Decl::OMPDeclareMapper:
5696 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5697 break;
5698
5699 case Decl::OMPRequires:
5700 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5701 break;
5702
5703 default:
5704 // Make sure we handled everything we should, every other kind is a
5705 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
5706 // function. Need to recode Decl::Kind to do that easily.
5707 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5708 break;
5709 }
5710 }
5711
AddDeferredUnusedCoverageMapping(Decl * D)5712 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5713 // Do we need to generate coverage mapping?
5714 if (!CodeGenOpts.CoverageMapping)
5715 return;
5716 switch (D->getKind()) {
5717 case Decl::CXXConversion:
5718 case Decl::CXXMethod:
5719 case Decl::Function:
5720 case Decl::ObjCMethod:
5721 case Decl::CXXConstructor:
5722 case Decl::CXXDestructor: {
5723 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5724 break;
5725 SourceManager &SM = getContext().getSourceManager();
5726 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5727 break;
5728 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5729 if (I == DeferredEmptyCoverageMappingDecls.end())
5730 DeferredEmptyCoverageMappingDecls[D] = true;
5731 break;
5732 }
5733 default:
5734 break;
5735 };
5736 }
5737
ClearUnusedCoverageMapping(const Decl * D)5738 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5739 // Do we need to generate coverage mapping?
5740 if (!CodeGenOpts.CoverageMapping)
5741 return;
5742 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5743 if (Fn->isTemplateInstantiation())
5744 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5745 }
5746 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5747 if (I == DeferredEmptyCoverageMappingDecls.end())
5748 DeferredEmptyCoverageMappingDecls[D] = false;
5749 else
5750 I->second = false;
5751 }
5752
EmitDeferredUnusedCoverageMappings()5753 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5754 // We call takeVector() here to avoid use-after-free.
5755 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5756 // we deserialize function bodies to emit coverage info for them, and that
5757 // deserializes more declarations. How should we handle that case?
5758 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5759 if (!Entry.second)
5760 continue;
5761 const Decl *D = Entry.first;
5762 switch (D->getKind()) {
5763 case Decl::CXXConversion:
5764 case Decl::CXXMethod:
5765 case Decl::Function:
5766 case Decl::ObjCMethod: {
5767 CodeGenPGO PGO(*this);
5768 GlobalDecl GD(cast<FunctionDecl>(D));
5769 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5770 getFunctionLinkage(GD));
5771 break;
5772 }
5773 case Decl::CXXConstructor: {
5774 CodeGenPGO PGO(*this);
5775 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5776 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5777 getFunctionLinkage(GD));
5778 break;
5779 }
5780 case Decl::CXXDestructor: {
5781 CodeGenPGO PGO(*this);
5782 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5783 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5784 getFunctionLinkage(GD));
5785 break;
5786 }
5787 default:
5788 break;
5789 };
5790 }
5791 }
5792
EmitMainVoidAlias()5793 void CodeGenModule::EmitMainVoidAlias() {
5794 // In order to transition away from "__original_main" gracefully, emit an
5795 // alias for "main" in the no-argument case so that libc can detect when
5796 // new-style no-argument main is in used.
5797 if (llvm::Function *F = getModule().getFunction("main")) {
5798 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() &&
5799 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth()))
5800 addUsedGlobal(llvm::GlobalAlias::create("__main_void", F));
5801 }
5802 }
5803
5804 /// Turns the given pointer into a constant.
GetPointerConstant(llvm::LLVMContext & Context,const void * Ptr)5805 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5806 const void *Ptr) {
5807 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5808 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5809 return llvm::ConstantInt::get(i64, PtrInt);
5810 }
5811
EmitGlobalDeclMetadata(CodeGenModule & CGM,llvm::NamedMDNode * & GlobalMetadata,GlobalDecl D,llvm::GlobalValue * Addr)5812 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5813 llvm::NamedMDNode *&GlobalMetadata,
5814 GlobalDecl D,
5815 llvm::GlobalValue *Addr) {
5816 if (!GlobalMetadata)
5817 GlobalMetadata =
5818 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5819
5820 // TODO: should we report variant information for ctors/dtors?
5821 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5822 llvm::ConstantAsMetadata::get(GetPointerConstant(
5823 CGM.getLLVMContext(), D.getDecl()))};
5824 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5825 }
5826
5827 /// For each function which is declared within an extern "C" region and marked
5828 /// as 'used', but has internal linkage, create an alias from the unmangled
5829 /// name to the mangled name if possible. People expect to be able to refer
5830 /// to such functions with an unmangled name from inline assembly within the
5831 /// same translation unit.
EmitStaticExternCAliases()5832 void CodeGenModule::EmitStaticExternCAliases() {
5833 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5834 return;
5835 for (auto &I : StaticExternCValues) {
5836 IdentifierInfo *Name = I.first;
5837 llvm::GlobalValue *Val = I.second;
5838 if (Val && !getModule().getNamedValue(Name->getName()))
5839 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5840 }
5841 }
5842
lookupRepresentativeDecl(StringRef MangledName,GlobalDecl & Result) const5843 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5844 GlobalDecl &Result) const {
5845 auto Res = Manglings.find(MangledName);
5846 if (Res == Manglings.end())
5847 return false;
5848 Result = Res->getValue();
5849 return true;
5850 }
5851
5852 /// Emits metadata nodes associating all the global values in the
5853 /// current module with the Decls they came from. This is useful for
5854 /// projects using IR gen as a subroutine.
5855 ///
5856 /// Since there's currently no way to associate an MDNode directly
5857 /// with an llvm::GlobalValue, we create a global named metadata
5858 /// with the name 'clang.global.decl.ptrs'.
EmitDeclMetadata()5859 void CodeGenModule::EmitDeclMetadata() {
5860 llvm::NamedMDNode *GlobalMetadata = nullptr;
5861
5862 for (auto &I : MangledDeclNames) {
5863 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
5864 // Some mangled names don't necessarily have an associated GlobalValue
5865 // in this module, e.g. if we mangled it for DebugInfo.
5866 if (Addr)
5867 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5868 }
5869 }
5870
5871 /// Emits metadata nodes for all the local variables in the current
5872 /// function.
EmitDeclMetadata()5873 void CodeGenFunction::EmitDeclMetadata() {
5874 if (LocalDeclMap.empty()) return;
5875
5876 llvm::LLVMContext &Context = getLLVMContext();
5877
5878 // Find the unique metadata ID for this name.
5879 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5880
5881 llvm::NamedMDNode *GlobalMetadata = nullptr;
5882
5883 for (auto &I : LocalDeclMap) {
5884 const Decl *D = I.first;
5885 llvm::Value *Addr = I.second.getPointer();
5886 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5887 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5888 Alloca->setMetadata(
5889 DeclPtrKind, llvm::MDNode::get(
5890 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5891 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5892 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5893 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5894 }
5895 }
5896 }
5897
EmitVersionIdentMetadata()5898 void CodeGenModule::EmitVersionIdentMetadata() {
5899 llvm::NamedMDNode *IdentMetadata =
5900 TheModule.getOrInsertNamedMetadata("llvm.ident");
5901 std::string Version = getClangFullVersion();
5902 llvm::LLVMContext &Ctx = TheModule.getContext();
5903
5904 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5905 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5906 }
5907
EmitCommandLineMetadata()5908 void CodeGenModule::EmitCommandLineMetadata() {
5909 llvm::NamedMDNode *CommandLineMetadata =
5910 TheModule.getOrInsertNamedMetadata("llvm.commandline");
5911 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5912 llvm::LLVMContext &Ctx = TheModule.getContext();
5913
5914 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5915 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5916 }
5917
EmitCoverageFile()5918 void CodeGenModule::EmitCoverageFile() {
5919 if (getCodeGenOpts().CoverageDataFile.empty() &&
5920 getCodeGenOpts().CoverageNotesFile.empty())
5921 return;
5922
5923 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5924 if (!CUNode)
5925 return;
5926
5927 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5928 llvm::LLVMContext &Ctx = TheModule.getContext();
5929 auto *CoverageDataFile =
5930 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5931 auto *CoverageNotesFile =
5932 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5933 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5934 llvm::MDNode *CU = CUNode->getOperand(i);
5935 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5936 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5937 }
5938 }
5939
GetAddrOfRTTIDescriptor(QualType Ty,bool ForEH)5940 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5941 bool ForEH) {
5942 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5943 // FIXME: should we even be calling this method if RTTI is disabled
5944 // and it's not for EH?
5945 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice ||
5946 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
5947 getTriple().isNVPTX()))
5948 return llvm::Constant::getNullValue(Int8PtrTy);
5949
5950 if (ForEH && Ty->isObjCObjectPointerType() &&
5951 LangOpts.ObjCRuntime.isGNUFamily())
5952 return ObjCRuntime->GetEHType(Ty);
5953
5954 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5955 }
5956
EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl * D)5957 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5958 // Do not emit threadprivates in simd-only mode.
5959 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5960 return;
5961 for (auto RefExpr : D->varlists()) {
5962 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5963 bool PerformInit =
5964 VD->getAnyInitializer() &&
5965 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5966 /*ForRef=*/false);
5967
5968 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5969 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5970 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5971 CXXGlobalInits.push_back(InitFunction);
5972 }
5973 }
5974
5975 llvm::Metadata *
CreateMetadataIdentifierImpl(QualType T,MetadataTypeMap & Map,StringRef Suffix)5976 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5977 StringRef Suffix) {
5978 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5979 if (InternalId)
5980 return InternalId;
5981
5982 if (isExternallyVisible(T->getLinkage())) {
5983 std::string OutName;
5984 llvm::raw_string_ostream Out(OutName);
5985 getCXXABI().getMangleContext().mangleTypeName(T, Out);
5986 Out << Suffix;
5987
5988 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5989 } else {
5990 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5991 llvm::ArrayRef<llvm::Metadata *>());
5992 }
5993
5994 return InternalId;
5995 }
5996
CreateMetadataIdentifierForType(QualType T)5997 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5998 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5999 }
6000
6001 llvm::Metadata *
CreateMetadataIdentifierForVirtualMemPtrType(QualType T)6002 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
6003 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
6004 }
6005
6006 // Generalize pointer types to a void pointer with the qualifiers of the
6007 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
6008 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
6009 // 'void *'.
GeneralizeType(ASTContext & Ctx,QualType Ty)6010 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
6011 if (!Ty->isPointerType())
6012 return Ty;
6013
6014 return Ctx.getPointerType(
6015 QualType(Ctx.VoidTy).withCVRQualifiers(
6016 Ty->getPointeeType().getCVRQualifiers()));
6017 }
6018
6019 // Apply type generalization to a FunctionType's return and argument types
GeneralizeFunctionType(ASTContext & Ctx,QualType Ty)6020 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
6021 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
6022 SmallVector<QualType, 8> GeneralizedParams;
6023 for (auto &Param : FnType->param_types())
6024 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
6025
6026 return Ctx.getFunctionType(
6027 GeneralizeType(Ctx, FnType->getReturnType()),
6028 GeneralizedParams, FnType->getExtProtoInfo());
6029 }
6030
6031 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
6032 return Ctx.getFunctionNoProtoType(
6033 GeneralizeType(Ctx, FnType->getReturnType()));
6034
6035 llvm_unreachable("Encountered unknown FunctionType");
6036 }
6037
CreateMetadataIdentifierGeneralized(QualType T)6038 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
6039 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
6040 GeneralizedMetadataIdMap, ".generalized");
6041 }
6042
6043 /// Returns whether this module needs the "all-vtables" type identifier.
NeedAllVtablesTypeId() const6044 bool CodeGenModule::NeedAllVtablesTypeId() const {
6045 // Returns true if at least one of vtable-based CFI checkers is enabled and
6046 // is not in the trapping mode.
6047 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
6048 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
6049 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
6050 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
6051 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
6052 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
6053 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
6054 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
6055 }
6056
AddVTableTypeMetadata(llvm::GlobalVariable * VTable,CharUnits Offset,const CXXRecordDecl * RD)6057 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
6058 CharUnits Offset,
6059 const CXXRecordDecl *RD) {
6060 llvm::Metadata *MD =
6061 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
6062 VTable->addTypeMetadata(Offset.getQuantity(), MD);
6063
6064 if (CodeGenOpts.SanitizeCfiCrossDso)
6065 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
6066 VTable->addTypeMetadata(Offset.getQuantity(),
6067 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
6068
6069 if (NeedAllVtablesTypeId()) {
6070 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
6071 VTable->addTypeMetadata(Offset.getQuantity(), MD);
6072 }
6073 }
6074
6075 static llvm::GlobalVariable *
GenerateAS0StringLiteral(CodeGenModule & CGM,StringRef Str)6076 GenerateAS0StringLiteral(CodeGenModule &CGM, StringRef Str) {
6077 llvm::SmallString<128> StrWithNull(Str);
6078 StrWithNull.push_back('\0');
6079
6080 llvm::Constant *C = llvm::ConstantDataArray::getString(CGM.getLLVMContext(),
6081 StrWithNull, false);
6082
6083 auto *GV = new llvm::GlobalVariable( CGM.getModule(), C->getType(), true,
6084 llvm::GlobalValue::PrivateLinkage, C);
6085 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
6086
6087 return GV;
6088 }
6089
EmitSandboxRequiredMethod(StringRef Cls,StringRef Fn)6090 llvm::Value *CodeGenModule::EmitSandboxRequiredMethod(StringRef Cls,
6091 StringRef Fn) {
6092 // We're going to emit a structure of the following form:
6093 // struct sandbox_required_method {
6094 // int64_t flags;
6095 // char *class;
6096 // char *method;
6097 // int64_t *method_number_var;
6098 // int64_t method_number;
6099 // };
6100 // The class and method fields point to the names of the class and method.
6101 // The method_number_var field is temporary and points to the
6102 // __cheri_method.{class}.{function} variable that older versions of the
6103 // sandbox interface ABI used.
6104 // The method number is the new method number variable.
6105 // The low 32 bits of the flags field are reserved for the compiler, the high
6106 // 32 bits for the runtime. The runtime uses one of these to indicate a
6107 // resolved method.
6108 // At some point, the compiler will use the low 1 bit of flags to indicate
6109 // that the `method_number_var` field is not present and that the compiled
6110 // code uses the method_number field directly.
6111
6112
6113 // Emit a global of the form __cheri_method.{class}.{function}
6114 auto GlobalName = (StringRef("__cheri_method.") + Cls + "." + Fn).str();
6115
6116 auto *MethodNumVar = getModule().getNamedGlobal(GlobalName);
6117 auto *Zero64 = llvm::ConstantInt::get(Int64Ty, 0);
6118 if (!MethodNumVar) {
6119 MethodNumVar = new llvm::GlobalVariable(getModule(), Int64Ty,
6120 /*isConstant*/false, llvm::GlobalValue::LinkOnceODRLinkage,
6121 Zero64, GlobalName);
6122 MethodNumVar->setSection(".CHERI_CALLER");
6123 addUsedGlobal(MethodNumVar);
6124 }
6125
6126 auto GlobalStructName = (StringRef(".sandbox_required_method.") + Cls + "." +
6127 Fn).str();
6128 if (!getModule().getNamedGlobal(GlobalStructName)) {
6129 auto *ClsName = GenerateAS0StringLiteral(*this, Cls);
6130 auto *MethodName = GenerateAS0StringLiteral(*this, Fn);
6131 auto StructTy = llvm::StructType::get(Int64Ty,
6132 ClsName->getType(), MethodName->getType(),
6133 MethodNumVar->getType(), Int64Ty);
6134
6135 auto *StructInit = llvm::ConstantStruct::get(StructTy, {Zero64,
6136 ClsName, MethodName, MethodNumVar, Zero64});
6137 auto *MetadataGV = new llvm::GlobalVariable(getModule(), StructTy,
6138 /*isConstant*/false, llvm::GlobalValue::ExternalLinkage, StructInit,
6139 GlobalStructName);
6140 MetadataGV->setSection("__cheri_sandbox_required_methods");
6141 MetadataGV->setComdat(getModule().getOrInsertComdat(GlobalStructName));
6142 addUsedGlobal(MetadataGV);
6143 }
6144
6145 return MethodNumVar;
6146 }
6147
EmitSandboxDefinedMethod(StringRef Cls,StringRef Method,llvm::Function * Fn)6148 void CodeGenModule::EmitSandboxDefinedMethod(StringRef Cls, StringRef
6149 Method, llvm::Function *Fn) {
6150 // For each defined method, we emit a structure of the following form:
6151 // struct sandbox_provided_method {
6152 // int64_t flags;
6153 // char *class;
6154 // char *method;
6155 // void *method_ptr;
6156 // };
6157 // The flags field is always zero. The class and method give the name of the
6158 // class and method. The method_ptr field includes the sandbox-relative
6159 // address of the method.
6160
6161 // Emit a global of the form __cheri_callee_method.{class}.{function}
6162 // containing the sandbox-relative address of the function.
6163 auto GlobalName = (StringRef("__cheri_callee_method.") + Cls + "." +
6164 Method).str();
6165 auto *MethodPtrVar = getModule().getNamedGlobal(GlobalName);
6166 if (!MethodPtrVar) {
6167 llvm::Constant *FnAS0;
6168 if (Fn->getType()->getAddressSpace() != 0)
6169 FnAS0 = llvm::ConstantExpr::getAddrSpaceCast(Fn,
6170 llvm::PointerType::get(Fn->getType(), 0));
6171 else
6172 FnAS0 = Fn;
6173
6174 MethodPtrVar = new llvm::GlobalVariable(getModule(),
6175 FnAS0->getType(),
6176 /*isConstant*/false, llvm::GlobalValue::ExternalLinkage,
6177 FnAS0, GlobalName);
6178 MethodPtrVar->setSection(".CHERI_CALLEE");
6179 addUsedGlobal(MethodPtrVar);
6180 }
6181
6182 auto GlobalStructName = (StringRef(".sandbox_provided_method.") + Cls + "." +
6183 Method).str();
6184 if (!getModule().getNamedGlobal(GlobalStructName)) {
6185 auto *ClsName = GenerateAS0StringLiteral(*this, Cls);
6186 auto *MethodName = GenerateAS0StringLiteral(*this, Method);
6187 auto *StructTy = llvm::StructType::get(Int64Ty, ClsName->getType(),
6188 MethodName->getType(),
6189 MethodPtrVar->getType());
6190 auto *Zero64 = llvm::ConstantInt::get(Int64Ty, 0);
6191
6192 auto *StructInit = llvm::ConstantStruct::get(StructTy, {Zero64,
6193 ClsName, MethodName, MethodPtrVar});
6194 auto *MetadataGV = new llvm::GlobalVariable(getModule(), StructTy,
6195 /*isConstant*/false, llvm::GlobalValue::ExternalLinkage, StructInit,
6196 GlobalStructName);
6197 MetadataGV->setSection("__cheri_sandbox_provided_methods");
6198 MetadataGV->setComdat(getModule().getOrInsertComdat(StringRef(GlobalStructName)));
6199 addUsedGlobal(MetadataGV);
6200 }
6201 }
6202
getPointerInDefaultAS(llvm::Type * T)6203 llvm::PointerType* CodeGenModule::getPointerInDefaultAS(llvm::Type* T) {
6204 return llvm::PointerType::get(T, getTargetCodeGenInfo().getDefaultAS());
6205 }
6206
getSanStats()6207 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
6208 if (!SanStats)
6209 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
6210
6211 return *SanStats;
6212 }
6213 llvm::Value *
createOpenCLIntToSamplerConversion(const Expr * E,CodeGenFunction & CGF)6214 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
6215 CodeGenFunction &CGF) {
6216 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
6217 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
6218 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
6219 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
6220 "__translate_sampler_initializer"),
6221 {C});
6222 }
6223
getNaturalPointeeTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo)6224 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment(
6225 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) {
6226 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo,
6227 /* forPointeeType= */ true);
6228 }
6229
getNaturalTypeAlignment(QualType T,LValueBaseInfo * BaseInfo,TBAAAccessInfo * TBAAInfo,bool forPointeeType)6230 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T,
6231 LValueBaseInfo *BaseInfo,
6232 TBAAAccessInfo *TBAAInfo,
6233 bool forPointeeType) {
6234 if (TBAAInfo)
6235 *TBAAInfo = getTBAAAccessInfo(T);
6236
6237 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But
6238 // that doesn't return the information we need to compute BaseInfo.
6239
6240 // Honor alignment typedef attributes even on incomplete types.
6241 // We also honor them straight for C++ class types, even as pointees;
6242 // there's an expressivity gap here.
6243 if (auto TT = T->getAs<TypedefType>()) {
6244 if (auto Align = TT->getDecl()->getMaxAlignment()) {
6245 if (BaseInfo)
6246 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType);
6247 return getContext().toCharUnitsFromBits(Align);
6248 }
6249 }
6250
6251 bool AlignForArray = T->isArrayType();
6252
6253 // Analyze the base element type, so we don't get confused by incomplete
6254 // array types.
6255 T = getContext().getBaseElementType(T);
6256
6257 if (T->isIncompleteType()) {
6258 // We could try to replicate the logic from
6259 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the
6260 // type is incomplete, so it's impossible to test. We could try to reuse
6261 // getTypeAlignIfKnown, but that doesn't return the information we need
6262 // to set BaseInfo. So just ignore the possibility that the alignment is
6263 // greater than one.
6264 if (BaseInfo)
6265 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6266 return CharUnits::One();
6267 }
6268
6269 if (BaseInfo)
6270 *BaseInfo = LValueBaseInfo(AlignmentSource::Type);
6271
6272 CharUnits Alignment;
6273 // For C++ class pointees, we don't know whether we're pointing at a
6274 // base or a complete object, so we generally need to use the
6275 // non-virtual alignment.
6276 const CXXRecordDecl *RD;
6277 if (forPointeeType && !AlignForArray && (RD = T->getAsCXXRecordDecl())) {
6278 Alignment = getClassPointerAlignment(RD);
6279 } else {
6280 Alignment = getContext().getTypeAlignInChars(T);
6281 if (T.getQualifiers().hasUnaligned())
6282 Alignment = CharUnits::One();
6283 }
6284
6285 // Cap to the global maximum type alignment unless the alignment
6286 // was somehow explicit on the type.
6287 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) {
6288 if (Alignment.getQuantity() > MaxAlign &&
6289 !getContext().isAlignmentRequired(T))
6290 Alignment = CharUnits::fromQuantity(MaxAlign);
6291 }
6292 return Alignment;
6293 }
6294
stopAutoInit()6295 bool CodeGenModule::stopAutoInit() {
6296 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter;
6297 if (StopAfter) {
6298 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is
6299 // used
6300 if (NumAutoVarInit >= StopAfter) {
6301 return true;
6302 }
6303 if (!NumAutoVarInit) {
6304 unsigned DiagID = getDiags().getCustomDiagID(
6305 DiagnosticsEngine::Warning,
6306 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the "
6307 "number of times ftrivial-auto-var-init=%1 gets applied.");
6308 getDiags().Report(DiagID)
6309 << StopAfter
6310 << (getContext().getLangOpts().getTrivialAutoVarInit() ==
6311 LangOptions::TrivialAutoVarInitKind::Zero
6312 ? "zero"
6313 : "pattern");
6314 }
6315 ++NumAutoVarInit;
6316 }
6317 return false;
6318 }
6319