blob: 427eabc36d0a4ee2d2ef5fd19733e7ce30d5ad9a [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnerbed31442007-05-28 01:07:47 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This coordinates the per-module state used while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenModule.h"
John McCall7f416cc2015-09-08 08:05:57 +000014#include "CGBlocks.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "CGOpenMPRuntime.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000022#include "CGOpenMPRuntimeNVPTX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000024#include "CodeGenPGO.h"
John McCallde0fe072017-08-15 21:42:52 +000025#include "ConstantEmitter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "CoverageMappingGen.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000027#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000028#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000029#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000030#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000032#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000033#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000034#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000035#include "clang/AST/RecursiveASTVisitor.h"
Reid Klecknerf09c19c2019-01-25 19:18:40 +000036#include "clang/AST/StmtVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000037#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000038#include "clang/Basic/CharInfo.h"
Richard Trieu63688182018-12-11 03:18:39 +000039#include "clang/Basic/CodeGenOptions.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000040#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000041#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000042#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000043#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000044#include "clang/Basic/Version.h"
John McCall5ad74072017-03-02 20:04:19 +000045#include "clang/CodeGen/ConstantInitBuilder.h"
Richard Trieu5337c742018-12-06 06:12:20 +000046#include "clang/Frontend/FrontendDiagnostic.h"
Caroline Tice62279732018-09-21 18:34:59 +000047#include "llvm/ADT/StringSwitch.h"
John McCallbeec5a02010-03-06 00:35:14 +000048#include "llvm/ADT/Triple.h"
Matthias Brauna4519532017-05-20 01:29:55 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000050#include "llvm/IR/CallingConv.h"
51#include "llvm/IR/DataLayout.h"
52#include "llvm/IR/Intrinsics.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/Module.h"
Rong Xu39f6d7e2019-03-01 17:50:20 +000055#include "llvm/IR/ProfileSummary.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000056#include "llvm/ProfileData/InstrProfReader.h"
Caroline Tice62279732018-09-21 18:34:59 +000057#include "llvm/Support/CodeGen.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000058#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000059#include "llvm/Support/ErrorHandling.h"
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +000060#include "llvm/Support/MD5.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000061#include "llvm/Support/TimeProfiler.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000062
Chris Lattnerbed31442007-05-28 01:07:47 +000063using namespace clang;
64using namespace CodeGen;
65
Vedant Kumar0acf3432017-09-22 18:23:04 +000066static llvm::cl::opt<bool> LimitedCoverage(
Zachary Turner8065f0b2017-12-01 00:53:10 +000067 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
Vedant Kumar0acf3432017-09-22 18:23:04 +000068 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
69 llvm::cl::init(false));
70
Julien Lerouge5a6b6982011-09-09 22:41:49 +000071static const char AnnotationSection[] = "llvm.metadata";
72
Alp Toker82862252013-12-28 21:58:40 +000073static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000074 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000075 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000076 case TargetCXXABI::GenericARM:
77 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000078 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +000079 case TargetCXXABI::WatchOS:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000080 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000081 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +000082 case TargetCXXABI::WebAssembly:
Alp Toker82862252013-12-28 21:58:40 +000083 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000084 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000085 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000086 }
87
88 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000089}
90
Adrian Prantle74f5252015-06-30 02:26:03 +000091CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
92 const PreprocessorOptions &PPO,
93 const CodeGenOptions &CGO, llvm::Module &M,
Alex Lorenzee024992014-08-04 18:41:51 +000094 DiagnosticsEngine &diags,
95 CoverageSourceInfo *CoverageInfo)
Adrian Prantle74f5252015-06-30 02:26:03 +000096 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
97 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Mehdi Aminica3cf9e2015-07-24 16:04:29 +000098 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Reid Kleckner9305fd12016-04-13 23:37:17 +000099 VMContext(M.getContext()), Types(*this), VTables(*this),
Peter Collingbourne3afb2662016-04-28 17:09:37 +0000100 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +0000101
Chris Lattnerece04092012-02-07 00:39:47 +0000102 // Initialize the type cache.
103 llvm::LLVMContext &LLVMContext = M.getContext();
104 VoidTy = llvm::Type::getVoidTy(LLVMContext);
105 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
106 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
107 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
108 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
Abderrazek Zaafranif58a1322017-12-21 19:20:01 +0000109 HalfTy = llvm::Type::getHalfTy(LLVMContext);
Chris Lattnerece04092012-02-07 00:39:47 +0000110 FloatTy = llvm::Type::getFloatTy(LLVMContext);
111 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
112 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
113 PointerAlignInBytes =
John McCall7f416cc2015-09-08 08:05:57 +0000114 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
Yaxun Liu26f75662016-08-19 05:17:25 +0000115 SizeSizeInBytes =
116 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +0000117 IntAlignInBytes =
118 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
Chris Lattnerece04092012-02-07 00:39:47 +0000119 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
Yaxun Liu26f75662016-08-19 05:17:25 +0000120 IntPtrTy = llvm::IntegerType::get(LLVMContext,
121 C.getTargetInfo().getMaxPointerWidth());
Chris Lattnerece04092012-02-07 00:39:47 +0000122 Int8PtrTy = Int8Ty->getPointerTo(0);
123 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000124 AllocaInt8PtrTy = Int8Ty->getPointerTo(
125 M.getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000126 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
Chris Lattnerece04092012-02-07 00:39:47 +0000127
John McCall882987f2013-02-28 19:01:20 +0000128 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
129
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000130 if (LangOpts.ObjC)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000131 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000132 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000133 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000134 if (LangOpts.OpenMP)
135 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000136 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000137 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000138
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000139 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000140 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Peter Collingbournee9f52102019-01-15 20:59:59 +0000141 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000142 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
Reid Kleckner9305fd12016-04-13 23:37:17 +0000143 getCXXABI().getMangleContext()));
Peter Collingbournee9f52102019-01-15 20:59:59 +0000144
Nick Lewycky207bce32011-04-21 23:44:07 +0000145 // If debug info or coverage generation is enabled, create the CGDebugInfo
146 // object.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000147 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
148 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000149 DebugInfo.reset(new CGDebugInfo(*this));
John McCallad7c5c12011-02-08 08:22:06 +0000150
151 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000152
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000153 if (C.getLangOpts().ObjC)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000154 ObjCData.reset(new ObjCEntrypoints());
Justin Bogneref512b92014-01-06 22:27:43 +0000155
Rong Xu9c6f1532016-03-02 20:59:36 +0000156 if (CodeGenOpts.hasProfileClangUse()) {
157 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
Richard Smith8654ae52018-10-10 23:13:35 +0000158 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000159 if (auto E = ReaderOrErr.takeError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000160 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Diego Novillo5aecacb2015-06-25 22:56:00 +0000161 "Could not read profile %0: %1");
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000162 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
163 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
164 << EI.message();
165 });
Nico Weber176efac2015-04-06 04:16:48 +0000166 } else
167 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000168 }
Alex Lorenzee024992014-08-04 18:41:51 +0000169
170 // If coverage mapping generation is enabled, create the
171 // CoverageMappingModuleGen object.
172 if (CodeGenOpts.CoverageMapping)
173 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000174}
175
Reid Kleckner9305fd12016-04-13 23:37:17 +0000176CodeGenModule::~CodeGenModule() {}
Ted Kremenek2c674f62008-08-05 18:50:11 +0000177
David Chisnall481e3a82010-01-23 02:40:42 +0000178void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000179 // This is just isGNUFamily(), but we want to force implementors of
180 // new ABIs to decide how best to do this.
181 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000182 case ObjCRuntime::GNUstep:
183 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000184 case ObjCRuntime::ObjFW:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000185 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000186 return;
187
188 case ObjCRuntime::FragileMacOSX:
189 case ObjCRuntime::MacOSX:
190 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000191 case ObjCRuntime::WatchOS:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000192 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000193 return;
194 }
195 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000196}
197
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000198void CodeGenModule::createOpenCLRuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000199 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000200}
201
Alexey Bataev9959db52014-05-06 10:08:46 +0000202void CodeGenModule::createOpenMPRuntime() {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000203 // Select a specialized code generation class based on the target, if any.
204 // If it does not exist use the default implementation.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000205 switch (getTriple().getArch()) {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000206 case llvm::Triple::nvptx:
207 case llvm::Triple::nvptx64:
208 assert(getLangOpts().OpenMPIsDevice &&
209 "OpenMP NVPTX is only prepared to deal with device code.");
Reid Kleckner9305fd12016-04-13 23:37:17 +0000210 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000211 break;
212 default:
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000213 if (LangOpts.OpenMPSimd)
214 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
215 else
216 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000217 break;
218 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000219}
220
Peter Collingbournefe883422011-10-06 18:29:37 +0000221void CodeGenModule::createCUDARuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000222 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbournefe883422011-10-06 18:29:37 +0000223}
224
Rafael Espindola1e4df922014-09-16 15:18:21 +0000225void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
226 Replacements[Name] = C;
227}
228
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000229void CodeGenModule::applyReplacements() {
Yaron Kerenb54db522015-06-11 12:33:25 +0000230 for (auto &I : Replacements) {
231 StringRef MangledName = I.first();
232 llvm::Constant *Replacement = I.second;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000233 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
234 if (!Entry)
235 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000236 auto *OldF = cast<llvm::Function>(Entry);
237 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000238 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000239 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000240 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000241 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000242 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000243 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
244 CE->getOpcode() == llvm::Instruction::GetElementPtr);
245 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
246 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000247 }
248
249 // Replace old with new, but keep the old order.
250 OldF->replaceAllUsesWith(Replacement);
251 if (NewF) {
252 NewF->removeFromParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000253 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
254 NewF);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000255 }
256 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000257 }
258}
259
Andrey Bokhankocab58582015-08-31 13:20:44 +0000260void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
261 GlobalValReplacements.push_back(std::make_pair(GV, C));
262}
263
264void CodeGenModule::applyGlobalValReplacements() {
265 for (auto &I : GlobalValReplacements) {
266 llvm::GlobalValue *GV = I.first;
267 llvm::Constant *C = I.second;
268
269 GV->replaceAllUsesWith(C);
270 GV->eraseFromParent();
271 }
272}
273
Rafael Espindola27c60b52014-06-03 02:42:01 +0000274// This is only used in aliases that we created and we know they have a
275// linear structure.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000276static const llvm::GlobalObject *getAliasedGlobal(
277 const llvm::GlobalIndirectSymbol &GIS) {
278 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
279 const llvm::Constant *C = &GIS;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000280 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000281 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000282 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
283 return GO;
284 // stripPointerCasts will not walk over weak aliases.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000285 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
286 if (!GIS2)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000287 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000288 if (!Visited.insert(GIS2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000289 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000290 C = GIS2->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000291 }
292}
293
Rafael Espindola208b5c02013-10-22 19:26:13 +0000294void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000295 // Check if the constructed aliases are well formed. It is really unfortunate
296 // that we have to do this in CodeGen, but we only construct mangled names
297 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000298 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000299 DiagnosticsEngine &Diags = getDiags();
Yaron Kerenb54db522015-06-11 12:33:25 +0000300 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000301 const auto *D = cast<ValueDecl>(GD.getDecl());
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000302 SourceLocation Location;
303 bool IsIFunc = D->hasAttr<IFuncAttr>();
304 if (const Attr *A = D->getDefiningAttr())
305 Location = A->getLocation();
306 else
307 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindola208b5c02013-10-22 19:26:13 +0000308 StringRef MangledName = getMangledName(GD);
309 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000310 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000311 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
312 if (!GV) {
313 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000314 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000315 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000316 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000317 Diags.Report(Location, diag::err_alias_to_undefined)
318 << IsIFunc << IsIFunc;
319 } else if (IsIFunc) {
320 // Check resolver function type.
321 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
322 GV->getType()->getPointerElementType());
323 assert(FTy);
324 if (!FTy->getReturnType()->isPointerTy())
325 Diags.Report(Location, diag::err_ifunc_resolver_return);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000326 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000327
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000328 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000329 llvm::GlobalValue *AliaseeGV;
330 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
331 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
332 else
333 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
334
Rafael Espindola502f65a2014-05-05 20:21:03 +0000335 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
336 StringRef AliasSection = SA->getName();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000337 if (AliasSection != AliaseeGV->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000338 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000339 << AliasSection << IsIFunc << IsIFunc;
Rafael Espindola502f65a2014-05-05 20:21:03 +0000340 }
Rafael Espindola27c60b52014-06-03 02:42:01 +0000341
342 // We have to handle alias to weak aliases in here. LLVM itself disallows
343 // this since the object semantics would not match the IL one. For
344 // compatibility with gcc we implement it by just pointing the alias
345 // to its aliasee's aliasee. We also warn, since the user is probably
346 // expecting the link to be weak.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000347 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
Sanjoy Dasf60a0d72016-04-08 01:31:02 +0000348 if (GA->isInterposable()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000349 Diags.Report(Location, diag::warn_alias_to_weak_alias)
350 << GV->getName() << GA->getName() << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000351 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000352 GA->getIndirectSymbol(), Alias->getType());
353 Alias->setIndirectSymbol(Aliasee);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000354 }
355 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000356 }
357 if (!Error)
358 return;
359
Yaron Kerenb54db522015-06-11 12:33:25 +0000360 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000361 StringRef MangledName = getMangledName(GD);
362 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000363 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000364 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
365 Alias->eraseFromParent();
366 }
367}
368
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000369void CodeGenModule::clear() {
370 DeferredDeclsToEmit.clear();
Alexey Bataev91797552015-03-18 04:13:55 +0000371 if (OpenMPRuntime)
372 OpenMPRuntime->clear();
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000373}
374
Justin Bogner40b8ba12014-06-26 01:45:07 +0000375void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
376 StringRef MainFile) {
377 if (!hasDiagnostics())
378 return;
379 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
380 if (MainFile.empty())
381 MainFile = "<stdin>";
382 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
Vedant Kumar96d6ca72017-04-27 17:30:58 +0000383 } else {
384 if (Mismatched > 0)
385 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
386
387 if (Missing > 0)
388 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
389 }
Justin Bogner40b8ba12014-06-26 01:45:07 +0000390}
391
Ted Kremenek2c674f62008-08-05 18:50:11 +0000392void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000393 EmitDeferred();
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000394 EmitVTablesOpportunistically();
Andrey Bokhankocab58582015-08-31 13:20:44 +0000395 applyGlobalValReplacements();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000396 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000397 checkAliases();
Erich Keane281d20b2018-01-08 21:34:17 +0000398 emitMultiVersionFunctions();
Eli Friedman5866fe32010-01-08 00:50:11 +0000399 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000400 EmitCXXGlobalDtorFunc();
Akira Hatanaka617e2612018-04-17 18:41:52 +0000401 registerGlobalDtorsWithAtExit();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000402 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000403 if (ObjCRuntime)
404 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000405 AddGlobalCtor(ObjCInitFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000406 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
407 CUDARuntime) {
Artem Belevichc66d2542018-06-27 18:32:51 +0000408 if (llvm::Function *CudaCtorFunction =
409 CUDARuntime->makeModuleCtorFunction())
Artem Belevich52cc4872015-05-07 19:34:16 +0000410 AddGlobalCtor(CudaCtorFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000411 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000412 if (OpenMPRuntime) {
Samuel Antaoee8fb302016-01-06 13:42:12 +0000413 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000414 OpenMPRuntime->emitRegistrationFunction()) {
415 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
416 OpenMPRegistrationFunction : nullptr;
417 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
418 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000419 OpenMPRuntime->clear();
420 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000421 if (PGOReader) {
Rong Xu39f6d7e2019-03-01 17:50:20 +0000422 getModule().setProfileSummary(
423 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
424 llvm::ProfileSummary::PSK_Instr);
Easwaran Raman695890c2015-12-17 19:14:27 +0000425 if (PGOStats.hasDiagnostics())
426 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
427 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000428 EmitCtorList(GlobalCtors, "llvm.global_ctors");
429 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000430 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000431 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000432 EmitDeferredUnusedCoverageMappings();
433 if (CoverageMapping)
434 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000435 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000436 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000437 CodeGenFunction(*this).EmitCfiCheckStub();
438 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000439 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000440 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000441 if (SanStats)
442 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000443
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000444 if (CodeGenOpts.Autolink &&
445 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000446 EmitModuleLinkOptions();
447 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000448
Nirav Dave741dea02017-03-30 13:41:44 +0000449 // Record mregparm value now so it is visible through rest of codegen.
450 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
451 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
452 CodeGenOpts.NumRegisterParameters);
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000453
Reid Kleckner124955a2015-08-05 18:51:13 +0000454 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000455 // We actually want the latest version when there are conflicts.
456 // We can change from Warning to Latest if such mode is supported.
457 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
458 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000459 }
460 if (CodeGenOpts.EmitCodeView) {
461 // Indicate that we want CodeView in the metadata.
462 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
463 }
Reid Kleckner75557712018-11-16 18:47:41 +0000464 if (CodeGenOpts.CodeViewGHash) {
465 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
466 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000467 if (CodeGenOpts.ControlFlowGuard) {
468 // We want function ID tables for Control Flow Guard.
Hans Wennborga912e3e2018-08-10 09:49:21 +0000469 getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000470 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000471 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
472 // We don't support LTO with 2 with different StrictVTablePointers
473 // FIXME: we could support it by stripping all the information introduced
474 // by StrictVTablePointers.
475
476 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
477
478 llvm::Metadata *Ops[2] = {
479 llvm::MDString::get(VMContext, "StrictVTablePointers"),
480 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
481 llvm::Type::getInt32Ty(VMContext), 1))};
482
483 getModule().addModuleFlag(llvm::Module::Require,
484 "StrictVTablePointersRequirement",
485 llvm::MDNode::get(VMContext, Ops));
486 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000487 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000488 // We support a single version in the linked module. The LLVM
489 // parser will drop debug info with a different version number
490 // (and warn about it, too).
491 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000492 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000493
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000494 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000495 // the correct build attributes in the ARM backend. wchar_size is also used by
496 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000497 uint64_t WCharWidth =
498 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000499 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
500
Justin Bogner9bb7f152014-06-23 20:03:28 +0000501 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000502 if ( Arch == llvm::Triple::arm
503 || Arch == llvm::Triple::armeb
504 || Arch == llvm::Triple::thumb
505 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000506 // The minimum width of an enum in bytes
507 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
508 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
509 }
510
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000511 if (CodeGenOpts.SanitizeCfiCrossDso) {
512 // Indicate that we want cross-DSO control flow integrity checks.
513 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
514 }
515
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000516 if (CodeGenOpts.CFProtectionReturn &&
517 Target.checkCFProtectionReturnSupported(getDiags())) {
518 // Indicate that we want to instrument return control flow protection.
519 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
520 1);
521 }
522
523 if (CodeGenOpts.CFProtectionBranch &&
524 Target.checkCFProtectionBranchSupported(getDiags())) {
525 // Indicate that we want to instrument branch control flow protection.
526 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
527 1);
528 }
529
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000530 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000531 // Indicate whether __nvvm_reflect should be configured to flush denormal
532 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
533 // property.)
534 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
Yaxun Liue1bfbc52018-07-21 02:02:22 +0000535 CodeGenOpts.FlushDenorm ? 1 : 0);
Justin Lebard3a44f62016-04-05 18:26:20 +0000536 }
537
Alexey Bader364a1162017-06-20 14:30:18 +0000538 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
539 if (LangOpts.OpenCL) {
540 EmitOpenCLMetadata();
541 // Emit SPIR version.
542 if (getTriple().getArch() == llvm::Triple::spir ||
543 getTriple().getArch() == llvm::Triple::spir64) {
544 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
545 // opencl.spir.version named metadata.
546 llvm::Metadata *SPIRVerElts[] = {
547 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
548 Int32Ty, LangOpts.OpenCLVersion / 100)),
549 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
550 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
551 llvm::NamedMDNode *SPIRVerMD =
552 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
553 llvm::LLVMContext &Ctx = TheModule.getContext();
554 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
555 }
556 }
557
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000558 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000559 assert(PLevel < 3 && "Invalid PIC Level");
560 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000561 if (Context.getLangOpts().PIE)
562 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000563 }
564
Caroline Tice62279732018-09-21 18:34:59 +0000565 if (getCodeGenOpts().CodeModel.size() > 0) {
566 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
567 .Case("tiny", llvm::CodeModel::Tiny)
568 .Case("small", llvm::CodeModel::Small)
569 .Case("kernel", llvm::CodeModel::Kernel)
570 .Case("medium", llvm::CodeModel::Medium)
571 .Case("large", llvm::CodeModel::Large)
572 .Default(~0u);
573 if (CM != ~0u) {
574 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
575 getModule().setCodeModel(codeModel);
576 }
577 }
578
Sriraman Tallam80af0052018-02-23 21:27:33 +0000579 if (CodeGenOpts.NoPLT)
580 getModule().setRtLibUseGOT();
581
John McCall0bdb1fd2010-09-16 06:16:50 +0000582 SimplifyPersonality();
583
John McCall09ae0322010-07-06 23:57:41 +0000584 if (getCodeGenOpts().EmitDeclMetadata)
585 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000586
587 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000588 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000589
590 if (DebugInfo)
591 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000592
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +0000593 if (getCodeGenOpts().EmitVersionIdentMetadata)
594 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000595
Scott Linderde6beb02018-12-14 15:38:15 +0000596 if (!getCodeGenOpts().RecordCommandLine.empty())
597 EmitCommandLineMetadata();
598
Robert Lytton57765d52014-07-03 09:30:33 +0000599 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000600}
601
Alexey Bader364a1162017-06-20 14:30:18 +0000602void CodeGenModule::EmitOpenCLMetadata() {
603 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
604 // opencl.ocl.version named metadata node.
605 llvm::Metadata *OCLVerElts[] = {
606 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
607 Int32Ty, LangOpts.OpenCLVersion / 100)),
608 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
609 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
610 llvm::NamedMDNode *OCLVerMD =
611 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
612 llvm::LLVMContext &Ctx = TheModule.getContext();
613 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
614}
615
Devang Patel945b8ae2011-03-23 16:29:39 +0000616void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
617 // Make sure that this type is translated.
618 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000619}
620
David Majnemer929025d2016-01-26 19:30:26 +0000621void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
622 // Make sure that this type is translated.
623 Types.RefreshTypeCacheForClass(RD);
624}
625
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000626llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
Dan Gohman947c9af2010-10-14 23:06:10 +0000627 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000628 return nullptr;
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000629 return TBAA->getTypeInfo(QTy);
Dan Gohman947c9af2010-10-14 23:06:10 +0000630}
631
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000632TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
Ivan A. Kosarev124a2182018-02-20 12:33:04 +0000633 if (!TBAA)
634 return TBAAAccessInfo();
635 return TBAA->getAccessInfo(AccessType);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000636}
637
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000638TBAAAccessInfo
639CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000640 if (!TBAA)
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000641 return TBAAAccessInfo();
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000642 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000643}
644
Dan Gohman22695fc2012-09-28 21:58:29 +0000645llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
646 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000647 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000648 return TBAA->getTBAAStructInfo(QTy);
649}
650
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000651llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
652 if (!TBAA)
653 return nullptr;
654 return TBAA->getBaseTypeInfo(QTy);
655}
656
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000657llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
Manman Renc451e572013-04-04 21:53:22 +0000658 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000659 return nullptr;
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000660 return TBAA->getAccessTagInfo(Info);
Manman Renc451e572013-04-04 21:53:22 +0000661}
662
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000663TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
664 TBAAAccessInfo TargetInfo) {
665 if (!TBAA)
666 return TBAAAccessInfo();
667 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
668}
669
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000670TBAAAccessInfo
671CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
672 TBAAAccessInfo InfoB) {
673 if (!TBAA)
674 return TBAAAccessInfo();
675 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
676}
677
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000678TBAAAccessInfo
679CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
680 TBAAAccessInfo SrcInfo) {
681 if (!TBAA)
682 return TBAAAccessInfo();
683 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
684}
685
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000686void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000687 TBAAAccessInfo TBAAInfo) {
688 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
689 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
Dan Gohman947c9af2010-10-14 23:06:10 +0000690}
691
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000692void CodeGenModule::DecorateInstructionWithInvariantGroup(
693 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000694 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
695 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000696}
697
Alp Toker29cb66b2014-01-26 06:17:37 +0000698void CodeGenModule::Error(SourceLocation loc, StringRef message) {
699 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
700 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000701}
702
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000703/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000704/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000705void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000706 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000707 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000708 std::string Msg = Type;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000709 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
710 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000711}
Chris Lattner41af8182007-12-02 06:27:33 +0000712
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000713/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000714/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000715void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000716 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000717 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000718 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000719 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000720}
721
John McCall23c29fe2011-06-24 21:55:10 +0000722llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
723 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
724}
725
Mike Stump11289f42009-09-09 15:08:12 +0000726void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000727 const NamedDecl *D) const {
Rafael Espindola123ce972018-01-24 18:58:32 +0000728 if (GV->hasDLLImportStorageClass())
729 return;
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000730 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000731 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000732 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000733 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000734 }
Rafael Espindola3f727a82018-03-14 18:14:46 +0000735 if (!D)
736 return;
Scott Linderbef26632019-01-28 17:12:19 +0000737 // Set visibility for definitions, and for declarations if requested globally
738 // or set explicitly.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000739 LinkageInfo LV = D->getLinkageAndVisibility();
Scott Linderbef26632019-01-28 17:12:19 +0000740 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
741 !GV->isDeclarationForLinker())
Rafael Espindola4a5da442013-02-27 02:56:45 +0000742 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000743}
744
Rafael Espindola699f5d62018-02-07 22:15:33 +0000745static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
Rafael Espindola3dd49812018-02-23 00:22:15 +0000746 llvm::GlobalValue *GV) {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000747 if (GV->hasLocalLinkage())
748 return true;
749
750 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
751 return true;
752
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000753 // DLLImport explicitly marks the GV as external.
754 if (GV->hasDLLImportStorageClass())
755 return false;
756
Rafael Espindola699f5d62018-02-07 22:15:33 +0000757 const llvm::Triple &TT = CGM.getTriple();
Martin Storsjo5ff7a8e2018-08-29 17:26:58 +0000758 if (TT.isWindowsGNUEnvironment()) {
759 // In MinGW, variables without DLLImport can still be automatically
760 // imported from a DLL by the linker; don't mark variables that
761 // potentially could come from another DLL as DSO local.
762 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
763 !GV->isThreadLocal())
764 return false;
765 }
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000766 // Every other GV is local on COFF.
767 // Make an exception for windows OS in the triple: Some firmware builds use
768 // *-win32-macho triples. This (accidentally?) produced windows relocations
769 // without GOT tables in older clang versions; Keep this behaviour.
770 // FIXME: even thread local variables?
771 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
772 return true;
773
774 // Only handle COFF and ELF for now.
Rafael Espindola699f5d62018-02-07 22:15:33 +0000775 if (!TT.isOSBinFormatELF())
776 return false;
777
778 // If this is not an executable, don't assume anything is local.
779 const auto &CGOpts = CGM.getCodeGenOpts();
780 llvm::Reloc::Model RM = CGOpts.RelocationModel;
781 const auto &LOpts = CGM.getLangOpts();
782 if (RM != llvm::Reloc::Static && !LOpts.PIE)
783 return false;
784
785 // A definition cannot be preempted from an executable.
786 if (!GV->isDeclarationForLinker())
787 return true;
788
789 // Most PIC code sequences that assume that a symbol is local cannot produce a
790 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
791 // depended, it seems worth it to handle it here.
792 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
793 return false;
794
795 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
796 llvm::Triple::ArchType Arch = TT.getArch();
797 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
798 Arch == llvm::Triple::ppc64le)
799 return false;
800
801 // If we can use copy relocations we can assume it is local.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000802 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
803 if (!Var->isThreadLocal() &&
Rafael Espindola75e57362018-02-07 23:04:06 +0000804 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
805 return true;
Rafael Espindola699f5d62018-02-07 22:15:33 +0000806
807 // If we can use a plt entry as the symbol address we can assume it
808 // is local.
809 // FIXME: This should work for PIE, but the gold linker doesn't support it.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000810 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000811 return true;
812
813 // Otherwise don't assue it is local.
814 return false;
815}
816
Rafael Espindola3dd49812018-02-23 00:22:15 +0000817void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000818 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
Rafael Espindola699f5d62018-02-07 22:15:33 +0000819}
820
Rafael Espindolab7350042018-03-01 00:35:47 +0000821void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
822 GlobalDecl GD) const {
823 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
Reid Klecknerae9b0702018-03-16 19:40:50 +0000824 // C++ destructors have a few C++ ABI specific special cases.
Rafael Espindolab7350042018-03-01 00:35:47 +0000825 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
Reid Klecknerae9b0702018-03-16 19:40:50 +0000826 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
827 return;
Rafael Espindolab7350042018-03-01 00:35:47 +0000828 }
829 setDLLImportDLLExport(GV, D);
830}
831
832void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
833 const NamedDecl *D) const {
Rafael Espindola3f727a82018-03-14 18:14:46 +0000834 if (D && D->isExternallyVisible()) {
Rafael Espindolab7350042018-03-01 00:35:47 +0000835 if (D->hasAttr<DLLImportAttr>())
836 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
837 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
838 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
839 }
840}
841
842void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
843 GlobalDecl GD) const {
844 setDLLImportDLLExport(GV, GD);
845 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
846}
847
Rafael Espindola699f5d62018-02-07 22:15:33 +0000848void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
849 const NamedDecl *D) const {
Rafael Espindolab7350042018-03-01 00:35:47 +0000850 setDLLImportDLLExport(GV, D);
851 setGlobalVisibilityAndLocal(GV, D);
852}
853
854void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
855 const NamedDecl *D) const {
Rafael Espindola699f5d62018-02-07 22:15:33 +0000856 setGlobalVisibility(GV, D);
Rafael Espindola3dd49812018-02-23 00:22:15 +0000857 setDSOLocal(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000858}
859
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000860static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
861 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
862 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
863 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
864 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
865 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
866}
867
868static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
869 CodeGenOptions::TLSModel M) {
870 switch (M) {
871 case CodeGenOptions::GeneralDynamicTLSModel:
872 return llvm::GlobalVariable::GeneralDynamicTLSModel;
873 case CodeGenOptions::LocalDynamicTLSModel:
874 return llvm::GlobalVariable::LocalDynamicTLSModel;
875 case CodeGenOptions::InitialExecTLSModel:
876 return llvm::GlobalVariable::InitialExecTLSModel;
877 case CodeGenOptions::LocalExecTLSModel:
878 return llvm::GlobalVariable::LocalExecTLSModel;
879 }
880 llvm_unreachable("Invalid TLS model!");
881}
882
David Majnemerbb525f7c2014-10-15 22:38:23 +0000883void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000884 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000885
David Majnemerbb525f7c2014-10-15 22:38:23 +0000886 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000887 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000888
889 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000890 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000891 TLM = GetLLVMTLSModel(Attr->getModel());
892 }
893
894 GV->setThreadLocalMode(TLM);
895}
896
Erich Keane3efe0022018-07-20 14:13:28 +0000897static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
898 StringRef Name) {
899 const TargetInfo &Target = CGM.getTarget();
900 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
901}
902
903static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
904 const CPUSpecificAttr *Attr,
Erich Keanede6480a32018-11-13 15:48:08 +0000905 unsigned CPUIndex,
Erich Keane3efe0022018-07-20 14:13:28 +0000906 raw_ostream &Out) {
Erich Keane19a8adc2018-10-25 18:57:19 +0000907 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
908 // supported.
Erich Keane3efe0022018-07-20 14:13:28 +0000909 if (Attr)
Erich Keanede6480a32018-11-13 15:48:08 +0000910 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
Erich Keane19a8adc2018-10-25 18:57:19 +0000911 else if (CGM.getTarget().supportsIFunc())
Erich Keane3efe0022018-07-20 14:13:28 +0000912 Out << ".resolver";
913}
914
Erich Keane281d20b2018-01-08 21:34:17 +0000915static void AppendTargetMangling(const CodeGenModule &CGM,
916 const TargetAttr *Attr, raw_ostream &Out) {
917 if (Attr->isDefaultVersion())
918 return;
919
920 Out << '.';
Erich Keane3efe0022018-07-20 14:13:28 +0000921 const TargetInfo &Target = CGM.getTarget();
Erich Keane281d20b2018-01-08 21:34:17 +0000922 TargetAttr::ParsedTargetAttr Info =
923 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
Erich Keane3efe0022018-07-20 14:13:28 +0000924 // Multiversioning doesn't allow "no-${feature}", so we can
925 // only have "+" prefixes here.
926 assert(LHS.startswith("+") && RHS.startswith("+") &&
927 "Features should always have a prefix.");
928 return Target.multiVersionSortPriority(LHS.substr(1)) >
929 Target.multiVersionSortPriority(RHS.substr(1));
930 });
Erich Keane281d20b2018-01-08 21:34:17 +0000931
932 bool IsFirst = true;
933
934 if (!Info.Architecture.empty()) {
935 IsFirst = false;
936 Out << "arch_" << Info.Architecture;
937 }
938
939 for (StringRef Feat : Info.Features) {
940 if (!IsFirst)
941 Out << '_';
942 IsFirst = false;
943 Out << Feat.substr(1);
944 }
945}
946
947static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
948 const NamedDecl *ND,
Erich Keane3efe0022018-07-20 14:13:28 +0000949 bool OmitMultiVersionMangling = false) {
Erich Keane281d20b2018-01-08 21:34:17 +0000950 SmallString<256> Buffer;
951 llvm::raw_svector_ostream Out(Buffer);
952 MangleContext &MC = CGM.getCXXABI().getMangleContext();
953 if (MC.shouldMangleDeclName(ND)) {
954 llvm::raw_svector_ostream Out(Buffer);
955 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
956 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
957 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
958 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
959 else
960 MC.mangleName(ND, Out);
961 } else {
962 IdentifierInfo *II = ND->getIdentifier();
963 assert(II && "Attempt to mangle unnamed decl.");
964 const auto *FD = dyn_cast<FunctionDecl>(ND);
965
966 if (FD &&
967 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
968 llvm::raw_svector_ostream Out(Buffer);
969 Out << "__regcall3__" << II->getName();
970 } else {
971 Out << II->getName();
972 }
973 }
974
975 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Erich Keane3efe0022018-07-20 14:13:28 +0000976 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
Erich Keane5c0d1922018-11-28 18:34:14 +0000977 switch (FD->getMultiVersionKind()) {
978 case MultiVersionKind::CPUDispatch:
979 case MultiVersionKind::CPUSpecific:
Erich Keanede6480a32018-11-13 15:48:08 +0000980 AppendCPUSpecificCPUDispatchMangling(CGM,
981 FD->getAttr<CPUSpecificAttr>(),
982 GD.getMultiVersionIndex(), Out);
Erich Keane5c0d1922018-11-28 18:34:14 +0000983 break;
984 case MultiVersionKind::Target:
Erich Keane3efe0022018-07-20 14:13:28 +0000985 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
Erich Keane5c0d1922018-11-28 18:34:14 +0000986 break;
987 case MultiVersionKind::None:
988 llvm_unreachable("None multiversion type isn't valid here");
989 }
Erich Keane3efe0022018-07-20 14:13:28 +0000990 }
991
Erich Keane281d20b2018-01-08 21:34:17 +0000992 return Out.str();
993}
994
995void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
996 const FunctionDecl *FD) {
997 if (!FD->isMultiVersion())
998 return;
999
1000 // Get the name of what this would be without the 'target' attribute. This
1001 // allows us to lookup the version that was emitted when this wasn't a
1002 // multiversion function.
1003 std::string NonTargetName =
Erich Keane3efe0022018-07-20 14:13:28 +00001004 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane281d20b2018-01-08 21:34:17 +00001005 GlobalDecl OtherGD;
1006 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1007 assert(OtherGD.getCanonicalDecl()
1008 .getDecl()
1009 ->getAsFunction()
1010 ->isMultiVersion() &&
1011 "Other GD should now be a multiversioned function");
1012 // OtherFD is the version of this function that was mangled BEFORE
1013 // becoming a MultiVersion function. It potentially needs to be updated.
Erich Keane7304f0a2018-11-28 20:58:43 +00001014 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1015 .getDecl()
1016 ->getAsFunction()
1017 ->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00001018 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1019 // This is so that if the initial version was already the 'default'
1020 // version, we don't try to update it.
1021 if (OtherName != NonTargetName) {
Erich Keanebc40c5c2018-01-09 01:09:12 +00001022 // Remove instead of erase, since others may have stored the StringRef
1023 // to this.
1024 const auto ExistingRecord = Manglings.find(NonTargetName);
1025 if (ExistingRecord != std::end(Manglings))
1026 Manglings.remove(&(*ExistingRecord));
Erich Keane281d20b2018-01-08 21:34:17 +00001027 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1028 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1029 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1030 Entry->setName(OtherName);
1031 }
1032 }
1033}
1034
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001035StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +00001036 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1037
1038 // Some ABIs don't have constructor variants. Make sure that base and
1039 // complete constructors get mangled the same.
1040 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1041 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1042 CXXCtorType OrigCtorType = GD.getCtorType();
1043 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1044 if (OrigCtorType == Ctor_Base)
1045 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1046 }
1047 }
1048
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001049 auto FoundName = MangledDeclNames.find(CanonicalGD);
1050 if (FoundName != MangledDeclNames.end())
1051 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001052
Richard Smith6d0e97a2014-08-02 00:50:16 +00001053 // Keep the first result in the case of a mangling collision.
Erich Keane281d20b2018-01-08 21:34:17 +00001054 const auto *ND = cast<NamedDecl>(GD.getDecl());
Yaxun Liue739ac02019-02-27 02:02:52 +00001055 std::string MangledName = getMangledNameImpl(*this, GD, ND);
1056
1057 // Postfix kernel stub names with .stub to differentiate them from kernel
1058 // names in device binaries. This is to facilitate the debugger to find
1059 // the correct symbols for kernels in the device binary.
1060 if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
1061 if (getLangOpts().HIP && !getLangOpts().CUDAIsDevice &&
1062 FD->hasAttr<CUDAGlobalAttr>())
1063 MangledName = MangledName + ".stub";
1064
1065 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001066 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +00001067}
1068
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001069StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1070 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001071 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1072 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +00001073
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001074 SmallString<256> Buffer;
1075 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +00001076 if (!D)
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001077 MangleCtx.mangleGlobalBlock(BD,
Fariborz Jahanian63628032012-06-26 16:06:38 +00001078 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001079 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001080 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001081 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001082 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001083 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001084 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001085
Richard Smith6d0e97a2014-08-02 00:50:16 +00001086 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1087 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +00001088}
1089
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001090llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +00001091 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +00001092}
1093
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001094/// AddGlobalCtor - Add a function to the list that will be called before
1095/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001096void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1097 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001098 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001099 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001100}
1101
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001102/// AddGlobalDtor - Add a function to the list that will be called
1103/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001104void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Akira Hatanaka617e2612018-04-17 18:41:52 +00001105 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1106 DtorsUsingAtExit[Priority].push_back(Dtor);
1107 return;
1108 }
1109
Daniel Dunbardec798b2009-01-13 02:25:00 +00001110 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +00001111 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001112}
1113
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001114void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001115 if (Fns.empty()) return;
1116
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001117 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +00001118 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Dylan McKay21e7f5e2018-11-09 17:15:06 +00001119 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1120 TheModule.getDataLayout().getProgramAddressSpace());
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001121
Reid Kleckner563f0e82014-05-23 21:13:45 +00001122 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1123 llvm::StructType *CtorStructTy = llvm::StructType::get(
Dylan McKay21e7f5e2018-11-09 17:15:06 +00001124 Int32Ty, CtorPFTy, VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001125
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001126 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +00001127 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001128 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +00001129 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001130 auto ctor = ctors.beginStruct(CtorStructTy);
1131 ctor.addInt(Int32Ty, I.Priority);
1132 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1133 if (I.AssociatedData)
1134 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1135 else
1136 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +00001137 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001138 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001139
John McCall18081af2016-11-19 20:12:25 +00001140 auto list =
1141 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1142 /*constant*/ false,
1143 llvm::GlobalValue::AppendingLinkage);
1144
1145 // The LTO linker doesn't seem to like it when we set an alignment
1146 // on appending variables. Take it off as a workaround.
1147 list->setAlignment(0);
1148
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001149 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001150}
1151
John McCalld4324142010-02-19 01:32:20 +00001152llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001153CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001154 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +00001155
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001156 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +00001157
Reid Klecknerae9b0702018-03-16 19:40:50 +00001158 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1159 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
Reid Klecknera283e482017-12-21 19:44:23 +00001160
Richard Smith5179eb72016-06-28 19:03:57 +00001161 if (isa<CXXConstructorDecl>(D) &&
1162 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1163 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1164 // Our approach to inheriting constructors is fundamentally different from
1165 // that used by the MS ABI, so keep our inheriting constructor thunks
1166 // internal rather than trying to pick an unambiguous mangling for them.
1167 return llvm::GlobalValue::InternalLinkage;
1168 }
1169
Hans Wennborg275efb92014-05-28 01:52:23 +00001170 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +00001171}
Nuno Lopesb6f79532008-06-08 15:45:52 +00001172
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001173llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001174 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1175 if (!MDS) return nullptr;
1176
Benjamin Kramer630cf8c2016-11-23 11:20:27 +00001177 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001178}
1179
Erich Keanede6480a32018-11-13 15:48:08 +00001180void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
Mike Stump11289f42009-09-09 15:08:12 +00001181 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001182 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001183 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00001184 llvm::AttributeList PAL;
Erich Keanede6480a32018-11-13 15:48:08 +00001185 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
Reid Klecknercdd26792017-04-18 23:50:03 +00001186 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001187 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +00001188}
1189
John McCall9b0a7ce2011-10-02 01:16:38 +00001190/// Determines whether the language options require us to model
1191/// unwind exceptions. We treat -fexceptions as mandating this
1192/// except under the fragile ObjC ABI with only ObjC exceptions
1193/// enabled. This means, for example, that C with -fexceptions
1194/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001195static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +00001196 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001197 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +00001198
1199 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001200 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +00001201
1202 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001203 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +00001204 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +00001205 }
1206
1207 return true;
1208}
1209
Peter Collingbournee44acad2018-06-26 02:15:47 +00001210static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1211 const CXXMethodDecl *MD) {
1212 // Check that the type metadata can ever actually be used by a call.
1213 if (!CGM.getCodeGenOpts().LTOUnit ||
1214 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1215 return false;
1216
1217 // Only functions whose address can be taken with a member function pointer
1218 // need this sort of type metadata.
1219 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1220 !isa<CXXDestructorDecl>(MD);
1221}
1222
1223std::vector<const CXXRecordDecl *>
1224CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1225 llvm::SetVector<const CXXRecordDecl *> MostBases;
1226
1227 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1228 CollectMostBases = [&](const CXXRecordDecl *RD) {
1229 if (RD->getNumBases() == 0)
1230 MostBases.insert(RD);
1231 for (const CXXBaseSpecifier &B : RD->bases())
1232 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1233 };
1234 CollectMostBases(RD);
1235 return MostBases.takeVector();
1236}
1237
Daniel Dunbar38932572009-04-14 08:05:55 +00001238void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1239 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001240 llvm::AttrBuilder B;
1241
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001242 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001243 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001244
David Blaikiebbafb8a2012-03-11 07:00:24 +00001245 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001246 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +00001247
Manoj Gupta4fbf84c2018-05-09 21:41:18 +00001248 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1249 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1250 B.addAttribute(llvm::Attribute::StackProtect);
1251 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1252 B.addAttribute(llvm::Attribute::StackProtectStrong);
1253 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1254 B.addAttribute(llvm::Attribute::StackProtectReq);
1255 }
Akira Hatanaka200500d2015-10-08 19:30:57 +00001256
1257 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001258 // If we don't have a declaration to control inlining, the function isn't
1259 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1260 // disabled, mark the function as noinline.
1261 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1262 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1263 B.addAttribute(llvm::Attribute::NoInline);
1264
Reid Kleckneree4930b2017-05-02 22:07:37 +00001265 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +00001266 return;
1267 }
1268
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001269 // Track whether we need to add the optnone LLVM attribute,
1270 // starting with the default for this optimization level.
1271 bool ShouldAddOptNone =
1272 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1273 // We can't add optnone in the following cases, it won't pass the verifier.
1274 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1275 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1276 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1277
1278 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001279 B.addAttribute(llvm::Attribute::OptimizeNone);
1280
1281 // OptimizeNone implies noinline; we should not be inlining such functions.
1282 B.addAttribute(llvm::Attribute::NoInline);
1283 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1284 "OptimizeNone and AlwaysInline on same function!");
1285
1286 // We still need to handle naked functions even though optnone subsumes
1287 // much of their semantics.
1288 if (D->hasAttr<NakedAttr>())
1289 B.addAttribute(llvm::Attribute::Naked);
1290
1291 // OptimizeNone wins over OptimizeForSize and MinSize.
1292 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1293 F->removeFnAttr(llvm::Attribute::MinSize);
1294 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +00001295 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001296 B.addAttribute(llvm::Attribute::Naked);
1297 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001298 } else if (D->hasAttr<NoDuplicateAttr>()) {
1299 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001300 } else if (D->hasAttr<NoInlineAttr>()) {
1301 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +00001302 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +00001303 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001304 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001305 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001306 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1307 // If we're not inlining, then force everything that isn't always_inline to
1308 // carry an explicit noinline attribute.
1309 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1310 B.addAttribute(llvm::Attribute::NoInline);
1311 } else {
1312 // Otherwise, propagate the inline hint attribute and potentially use its
1313 // absence to mark things as noinline.
1314 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Trieu9b36a9c2018-10-23 01:26:28 +00001315 // Search function and template pattern redeclarations for inline.
1316 auto CheckForInline = [](const FunctionDecl *FD) {
1317 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1318 return Redecl->isInlineSpecified();
1319 };
1320 if (any_of(FD->redecls(), CheckRedeclForInline))
1321 return true;
1322 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1323 if (!Pattern)
1324 return false;
1325 return any_of(Pattern->redecls(), CheckRedeclForInline);
1326 };
1327 if (CheckForInline(FD)) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001328 B.addAttribute(llvm::Attribute::InlineHint);
1329 } else if (CodeGenOpts.getInlining() ==
1330 CodeGenOptions::OnlyHintInlining &&
1331 !FD->isInlined() &&
1332 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1333 B.addAttribute(llvm::Attribute::NoInline);
1334 }
1335 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001336 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001337
Chandler Carruthfcd33142016-12-23 01:24:49 +00001338 // Add other optimization related attributes if we are optimizing this
1339 // function.
1340 if (!D->hasAttr<OptimizeNoneAttr>()) {
1341 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001342 if (!ShouldAddOptNone)
1343 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001344 B.addAttribute(llvm::Attribute::Cold);
1345 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001346
Chandler Carruthfcd33142016-12-23 01:24:49 +00001347 if (D->hasAttr<MinSizeAttr>())
1348 B.addAttribute(llvm::Attribute::MinSize);
1349 }
Richard Smithb555a762012-09-28 22:46:07 +00001350
Reid Kleckneree4930b2017-05-02 22:07:37 +00001351 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001352
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001353 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1354 if (alignment)
1355 F->setAlignment(alignment);
1356
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001357 if (!D->hasAttr<AlignedAttr>())
1358 if (LangOpts.FunctionAlignment)
1359 F->setAlignment(1 << LangOpts.FunctionAlignment);
1360
Dan Gohmanc2853072015-09-03 22:51:53 +00001361 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1362 // reserve a bit for differentiating between virtual and non-virtual member
1363 // functions. If the current target's C++ ABI requires this and this is a
1364 // member function, set its alignment accordingly.
1365 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1366 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1367 F->setAlignment(2);
1368 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001369
1370 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1371 if (CodeGenOpts.SanitizeCfiCrossDso)
1372 if (auto *FD = dyn_cast<FunctionDecl>(D))
Peter Collingbournee44acad2018-06-26 02:15:47 +00001373 CreateFunctionTypeMetadataForIcall(FD, F);
1374
1375 // Emit type metadata on member functions for member function pointer checks.
1376 // These are only ever necessary on definitions; we're guaranteed that the
1377 // definition will be present in the LTO unit as a result of LTO visibility.
1378 auto *MD = dyn_cast<CXXMethodDecl>(D);
1379 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1380 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1381 llvm::Metadata *Id =
1382 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1383 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1384 F->addTypeMetadata(0, Id);
1385 }
1386 }
Daniel Dunbar449a3392008-09-04 23:41:35 +00001387}
1388
Rafael Espindola75c649c2018-03-01 00:06:55 +00001389void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1390 const Decl *D = GD.getDecl();
Rafael Espindolab7350042018-03-01 00:35:47 +00001391 if (dyn_cast_or_null<NamedDecl>(D))
1392 setGVProperties(GV, GD);
John McCall457a04e2010-10-22 21:05:15 +00001393 else
1394 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001395
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001396 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001397 addUsedGlobal(GV);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001398
1399 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1400 const auto *VD = cast<VarDecl>(D);
Erich Keane85822b32018-10-25 19:13:46 +00001401 if (VD->getType().isConstQualified() &&
1402 VD->getStorageDuration() == SD_Static)
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001403 addUsedGlobal(GV);
1404 }
Rafael Espindola502f65a2014-05-05 20:21:03 +00001405}
1406
Erich Keanede6480a32018-11-13 15:48:08 +00001407bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
Erich Keane93e58662018-02-12 17:01:41 +00001408 llvm::AttrBuilder &Attrs) {
1409 // Add target-cpu and target-features attributes to functions. If
1410 // we have a decl for the function and it has a target attribute then
1411 // parse that and add it to the feature set.
1412 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1413 std::vector<std::string> Features;
Erich Keanede6480a32018-11-13 15:48:08 +00001414 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
Erich Keane93e58662018-02-12 17:01:41 +00001415 FD = FD ? FD->getMostRecentDecl() : FD;
1416 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
Erich Keane3efe0022018-07-20 14:13:28 +00001417 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
Erich Keane93e58662018-02-12 17:01:41 +00001418 bool AddedAttr = false;
Erich Keane3efe0022018-07-20 14:13:28 +00001419 if (TD || SD) {
Erich Keane93e58662018-02-12 17:01:41 +00001420 llvm::StringMap<bool> FeatureMap;
Erich Keanede6480a32018-11-13 15:48:08 +00001421 getFunctionFeatureMap(FeatureMap, GD);
Erich Keane93e58662018-02-12 17:01:41 +00001422
1423 // Produce the canonical string for this set of features.
1424 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1425 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1426
1427 // Now add the target-cpu and target-features to the function.
1428 // While we populated the feature map above, we still need to
1429 // get and parse the target attribute so we can get the cpu for
1430 // the function.
Erich Keane3efe0022018-07-20 14:13:28 +00001431 if (TD) {
1432 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1433 if (ParsedAttr.Architecture != "" &&
1434 getTarget().isValidCPUName(ParsedAttr.Architecture))
1435 TargetCPU = ParsedAttr.Architecture;
1436 }
Erich Keane93e58662018-02-12 17:01:41 +00001437 } else {
1438 // Otherwise just add the existing target cpu and target features to the
1439 // function.
1440 Features = getTarget().getTargetOpts().Features;
1441 }
1442
1443 if (TargetCPU != "") {
1444 Attrs.addAttribute("target-cpu", TargetCPU);
1445 AddedAttr = true;
1446 }
1447 if (!Features.empty()) {
Fangrui Song55fab262018-09-26 22:16:28 +00001448 llvm::sort(Features);
Erich Keane93e58662018-02-12 17:01:41 +00001449 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1450 AddedAttr = true;
1451 }
1452
1453 return AddedAttr;
1454}
1455
Rafael Espindola285271c2018-02-28 23:54:23 +00001456void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001457 llvm::GlobalObject *GO) {
Rafael Espindola285271c2018-02-28 23:54:23 +00001458 const Decl *D = GD.getDecl();
Rafael Espindola75c649c2018-03-01 00:06:55 +00001459 SetCommonAttributes(GD, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001460
Javed Absar2a67c9e2017-06-05 10:11:57 +00001461 if (D) {
1462 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1463 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1464 GV->addAttribute("bss-section", SA->getName());
1465 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1466 GV->addAttribute("data-section", SA->getName());
1467 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1468 GV->addAttribute("rodata-section", SA->getName());
1469 }
1470
1471 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1472 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
Erich Keane30994d22018-02-08 20:04:22 +00001473 if (!D->getAttr<SectionAttr>())
1474 F->addFnAttr("implicit-section-name", SA->getName());
Erich Keane93e58662018-02-12 17:01:41 +00001475
1476 llvm::AttrBuilder Attrs;
Erich Keanede6480a32018-11-13 15:48:08 +00001477 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
Erich Keane93e58662018-02-12 17:01:41 +00001478 // We know that GetCPUAndFeaturesAttributes will always have the
1479 // newest set, since it has the newest possible FunctionDecl, so the
1480 // new ones should replace the old.
1481 F->removeFnAttr("target-cpu");
1482 F->removeFnAttr("target-features");
1483 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1484 }
Javed Absar2a67c9e2017-06-05 10:11:57 +00001485 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001486
Erich Keane7963e8b2018-07-18 20:04:48 +00001487 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1488 GO->setSection(CSA->getName());
1489 else if (const auto *SA = D->getAttr<SectionAttr>())
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001490 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001491 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001492
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001493 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001494}
1495
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001496void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001497 llvm::Function *F,
1498 const CGFunctionInfo &FI) {
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001499 const Decl *D = GD.getDecl();
Erich Keanede6480a32018-11-13 15:48:08 +00001500 SetLLVMFunctionAttributes(GD, FI, F);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001501 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001502
1503 F->setLinkage(llvm::Function::InternalLinkage);
1504
Rafael Espindola285271c2018-02-28 23:54:23 +00001505 setNonAliasAttributes(GD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001506}
1507
Rafael Espindolab7350042018-03-01 00:35:47 +00001508static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
David Majnemerf6acb762014-04-25 17:07:16 +00001509 // Set linkage and visibility in case we never see a definition.
1510 LinkageInfo LV = ND->getLinkageAndVisibility();
Rafael Espindolab7350042018-03-01 00:35:47 +00001511 // Don't set internal linkage on declarations.
1512 // "extern_weak" is overloaded in LLVM; we probably should have
1513 // separate linkage types for this.
1514 if (isExternallyVisible(LV.getLinkage()) &&
1515 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1516 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001517}
1518
Peter Collingbournee44acad2018-06-26 02:15:47 +00001519void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1520 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001521 // Only if we are checking indirect calls.
1522 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1523 return;
1524
Peter Collingbournee44acad2018-06-26 02:15:47 +00001525 // Non-static class methods are handled via vtable or member function pointer
1526 // checks elsewhere.
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001527 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1528 return;
1529
1530 // Additionally, if building with cross-DSO support...
1531 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001532 // Skip available_externally functions. They won't be codegen'ed in the
1533 // current module anyway.
1534 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1535 return;
1536 }
1537
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001538 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001539 F->addTypeMetadata(0, MD);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001540 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001541
1542 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001543 if (CodeGenOpts.SanitizeCfiCrossDso)
1544 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1545 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001546}
1547
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001548void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1549 bool IsIncompleteFunction,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001550 bool IsThunk) {
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001551
Pete Cooper2f1637a2015-05-20 17:17:45 +00001552 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001553 // If this is an intrinsic function, set the function's attributes
1554 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001555 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001556 return;
1557 }
1558
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001559 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001560
Scott Linderfb59fef2019-04-23 21:50:11 +00001561 if (!IsIncompleteFunction)
Erich Keanede6480a32018-11-13 15:48:08 +00001562 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +00001563
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001564 // Add the Returned attribute for "this", except for iOS 5 and earlier
1565 // where substantial code, including the libstdc++ dylib, was compiled with
1566 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001567 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001568 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001569 assert(!F->arg_empty() &&
1570 F->arg_begin()->getType()
1571 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1572 "unexpected this return");
1573 F->addAttribute(1, llvm::Attribute::Returned);
1574 }
1575
Daniel Dunbar38932572009-04-14 08:05:55 +00001576 // Only a few attributes are set on declarations; these may later be
1577 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001578
Jake Ehrlichba874ad2017-11-29 00:54:20 +00001579 setLinkageForGV(F, FD);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001580 setGVProperties(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001581
Scott Linderfb59fef2019-04-23 21:50:11 +00001582 // Setup target-specific attributes.
1583 if (!IsIncompleteFunction && F->isDeclaration())
1584 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1585
Erich Keane7963e8b2018-07-18 20:04:48 +00001586 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1587 F->setSection(CSA->getName());
1588 else if (const auto *SA = FD->getAttr<SectionAttr>())
1589 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001590
Richard Smith351241c2016-04-07 21:46:12 +00001591 if (FD->isReplaceableGlobalAllocationFunction()) {
1592 // A replaceable global allocation function does not act like a builtin by
1593 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001594 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001595 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001596
Richard Smith351241c2016-04-07 21:46:12 +00001597 // A sane operator new returns a non-aliasing pointer.
1598 // FIXME: Also add NonNull attribute to the return value
1599 // for the non-nothrow forms?
1600 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1601 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1602 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001603 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001604 llvm::Attribute::NoAlias);
1605 }
1606
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001607 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001608 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001609 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1610 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001611 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001612
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001613 // Don't emit entries for function declarations in the cross-DSO mode. This
1614 // is handled with better precision by the receiving DSO.
1615 if (!CodeGenOpts.SanitizeCfiCrossDso)
Peter Collingbournee44acad2018-06-26 02:15:47 +00001616 CreateFunctionTypeMetadataForIcall(FD, F);
Alexey Bataevb952e632017-12-15 16:28:31 +00001617
1618 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1619 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001620
1621 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
1622 // Annotate the callback behavior as metadata:
1623 // - The callback callee (as argument number).
1624 // - The callback payloads (as argument numbers).
1625 llvm::LLVMContext &Ctx = F->getContext();
1626 llvm::MDBuilder MDB(Ctx);
1627
1628 // The payload indices are all but the first one in the encoding. The first
1629 // identifies the callback callee.
1630 int CalleeIdx = *CB->encoding_begin();
1631 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
1632 F->addMetadata(llvm::LLVMContext::MD_callback,
1633 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1634 CalleeIdx, PayloadIndices,
1635 /* VarArgsArePassed */ false)}));
1636 }
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001637}
1638
Rafael Espindola060062a2014-03-06 22:15:10 +00001639void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001640 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001641 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001642 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001643}
1644
Rafael Espindola060062a2014-03-06 22:15:10 +00001645void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1646 assert(!GV->isDeclaration() &&
1647 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001648 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001649}
1650
1651static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001652 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001653 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001654 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001655 return;
1656
Rafael Espindola060062a2014-03-06 22:15:10 +00001657 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001658 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001659 UsedArray.resize(List.size());
1660 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001661 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001662 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1663 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001666 if (UsedArray.empty())
1667 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001668 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001669
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001670 auto *GV = new llvm::GlobalVariable(
1671 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1672 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001673
1674 GV->setSection("llvm.metadata");
1675}
1676
Rafael Espindola060062a2014-03-06 22:15:10 +00001677void CodeGenModule::emitLLVMUsed() {
1678 emitUsed(*this, "llvm.used", LLVMUsed);
1679 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1680}
1681
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001682void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001683 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001684 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1685}
1686
Aaron Ballman5d041be2013-06-04 02:07:14 +00001687void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1688 llvm::SmallString<32> Opt;
1689 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001690 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001691 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1692}
1693
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00001694void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1695 auto &C = getLLVMContext();
1696 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1697 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1698}
1699
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001700void CodeGenModule::AddDependentLib(StringRef Lib) {
1701 llvm::SmallString<24> Opt;
1702 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001703 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001704 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1705}
1706
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001707/// Add link options implied by the given module, including modules
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001708/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001709static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001710 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001711 llvm::SmallPtrSet<Module *, 16> &Visited) {
1712 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001713 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001714 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001715 }
1716
1717 // Import this module's dependencies.
1718 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001719 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001720 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001721 }
1722
1723 // Add linker options to link against the libraries/frameworks
1724 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001725 llvm::LLVMContext &Context = CGM.getLLVMContext();
Saleem Abdulrasool175890e2019-01-05 19:27:12 +00001726 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
1727 bool IsPS4 = CGM.getTarget().getTriple().isPS4();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00001728
1729 // For modules that use export_as for linking, use that module
1730 // name instead.
1731 if (Mod->UseExportAsModuleLinkName)
1732 return;
1733
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001734 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001735 // Link against a framework. Frameworks are currently Darwin only, so we
1736 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001737 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001738 llvm::Metadata *Args[2] = {
1739 llvm::MDString::get(Context, "-framework"),
1740 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001741
1742 Metadata.push_back(llvm::MDNode::get(Context, Args));
1743 continue;
1744 }
1745
1746 // Link against a library.
Saleem Abdulrasool175890e2019-01-05 19:27:12 +00001747 if (IsELF && !IsPS4) {
1748 llvm::Metadata *Args[2] = {
1749 llvm::MDString::get(Context, "lib"),
1750 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
1751 };
1752 Metadata.push_back(llvm::MDNode::get(Context, Args));
1753 } else {
1754 llvm::SmallString<24> Opt;
1755 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1756 Mod->LinkLibraries[I - 1].Library, Opt);
1757 auto *OptString = llvm::MDString::get(Context, Opt);
1758 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1759 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001760 }
1761}
1762
1763void CodeGenModule::EmitModuleLinkOptions() {
1764 // Collect the set of all of the modules we want to visit to emit link
1765 // options, which is essentially the imported modules and all of their
1766 // non-explicit child modules.
1767 llvm::SetVector<clang::Module *> LinkModules;
1768 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1769 SmallVector<clang::Module *, 16> Stack;
1770
1771 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001772 for (Module *M : ImportedModules) {
1773 // Do not add any link flags when an implementation TU of a module imports
1774 // a header of that same module.
1775 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1776 !getLangOpts().isCompilingModule())
1777 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001778 if (Visited.insert(M).second)
1779 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001780 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001781
1782 // Find all of the modules to import, making a little effort to prune
1783 // non-leaf modules.
1784 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001785 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001786
1787 bool AnyChildren = false;
1788
1789 // Visit the submodules of this module.
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00001790 for (const auto &SM : Mod->submodules()) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001791 // Skip explicit children; they need to be explicitly imported to be
1792 // linked against.
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00001793 if (SM->IsExplicit)
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001794 continue;
1795
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00001796 if (Visited.insert(SM).second) {
1797 Stack.push_back(SM);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001798 AnyChildren = true;
1799 }
1800 }
1801
1802 // We didn't find any children, so add this module to the list of
1803 // modules to link against.
1804 if (!AnyChildren) {
1805 LinkModules.insert(Mod);
1806 }
1807 }
1808
1809 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001810 // order. We don't do anything to try to order import link flags with respect
1811 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00001812 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001813 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001814 for (Module *M : LinkModules)
1815 if (Visited.insert(M).second)
1816 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001817 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001818 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001819
Daniel Dunbar69e47462013-01-17 01:35:06 +00001820 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00001821 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1822 for (auto *MD : LinkerOptionsMetadata)
1823 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001824}
1825
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001826void CodeGenModule::EmitDeferred() {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001827 // Emit deferred declare target declarations.
1828 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1829 getOpenMPRuntime().emitDeferredTargetDecls();
1830
Chris Lattner45470942009-03-21 09:44:56 +00001831 // Emit code for any potentially referenced deferred decls. Since a
1832 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001833 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001834
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001835 if (!DeferredVTables.empty()) {
1836 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001837
Eric Christopherd160c502016-01-29 01:35:53 +00001838 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001839 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001840 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001841 assert(DeferredVTables.empty());
1842 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001843
Eric Christopherd160c502016-01-29 01:35:53 +00001844 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001845 if (DeferredDeclsToEmit.empty())
1846 return;
John McCall6bd2a892013-01-25 22:31:03 +00001847
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001848 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1849 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001850 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001851 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1852
Sanjoy Das70a60512017-05-01 06:12:13 +00001853 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001854 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1855 // to get GlobalValue with exactly the type we need, not something that
1856 // might had been created for another decl with the same mangled name but
1857 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001858 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001859 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001860
1861 // In case of different address spaces, we may still get a cast, even with
1862 // IsForDefinition equal to true. Query mangled names table to get
1863 // GlobalValue.
1864 if (!GV)
1865 GV = GetGlobalValue(getMangledName(D));
1866
1867 // Make sure GetGlobalValue returned non-null.
1868 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001869
John McCallc2af9392010-05-27 01:45:30 +00001870 // Check to see if we've already emitted this. This is necessary
1871 // for a couple of reasons: first, decls can end up in the
1872 // deferred-decls queue multiple times, and second, decls can end
1873 // up with definitions in unusual ways (e.g. by an extern inline
1874 // function acquiring a strong function redefinition). Just
1875 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001876 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001877 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001878
Chris Lattner45470942009-03-21 09:44:56 +00001879 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001880 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001881
1882 // If we found out that we need to emit more decls, do that recursively.
1883 // This has the advantage that the decls are emitted in a DFS and related
1884 // ones are close together, which is convenient for testing.
1885 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1886 EmitDeferred();
1887 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1888 }
Chris Lattner45470942009-03-21 09:44:56 +00001889 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001890}
Chris Lattner09153c02007-06-22 18:48:09 +00001891
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001892void CodeGenModule::EmitVTablesOpportunistically() {
1893 // Try to emit external vtables as available_externally if they have emitted
1894 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1895 // is not allowed to create new references to things that need to be emitted
1896 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1897
Piotr Padlewski05547742017-06-01 09:24:36 +00001898 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1899 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001900
1901 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1902 assert(getVTables().isVTableExternal(RD) &&
1903 "This queue should only contain external vtables");
1904 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1905 VTables.GenerateClassData(RD);
1906 }
1907 OpportunisticVTables.clear();
1908}
1909
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001910void CodeGenModule::EmitGlobalAnnotations() {
1911 if (Annotations.empty())
1912 return;
1913
1914 // Create a new global variable for the ConstantStruct in the Module.
1915 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1916 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001917 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1918 llvm::GlobalValue::AppendingLinkage,
1919 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001920 gv->setSection(AnnotationSection);
1921}
1922
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001923llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001924 llvm::Constant *&AStr = AnnotationStrings[Str];
1925 if (AStr)
1926 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001927
1928 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001929 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001930 auto *gv =
1931 new llvm::GlobalVariable(getModule(), s->getType(), true,
1932 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001933 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001934 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001935 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001936 return gv;
1937}
1938
1939llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1940 SourceManager &SM = getContext().getSourceManager();
1941 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1942 if (PLoc.isValid())
1943 return EmitAnnotationString(PLoc.getFilename());
1944 return EmitAnnotationString(SM.getBufferName(Loc));
1945}
1946
1947llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1948 SourceManager &SM = getContext().getSourceManager();
1949 PresumedLoc PLoc = SM.getPresumedLoc(L);
1950 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1951 SM.getExpansionLineNumber(L);
1952 return llvm::ConstantInt::get(Int32Ty, LineNo);
1953}
1954
Mike Stump11289f42009-09-09 15:08:12 +00001955llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001956 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001957 SourceLocation L) {
1958 // Get the globals for file name, annotation, and the line number.
1959 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1960 *UnitGV = EmitAnnotationUnit(L),
1961 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001962
Daniel Dunbar346892a2009-04-14 22:41:13 +00001963 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001964 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001965 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1966 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1967 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1968 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001969 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001970 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001971}
1972
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001973void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1974 llvm::GlobalValue *GV) {
1975 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1976 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001977 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1978 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001979}
1980
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001981bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1982 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001983 SourceLocation Loc) const {
1984 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1985 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001986 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001987 return true;
1988 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001989 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001990 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001991 // If location is unknown, this may be a compiler-generated function. Assume
1992 // it's located in the main file.
1993 auto &SM = Context.getSourceManager();
1994 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001995 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001996 }
1997 return false;
1998}
1999
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002000bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
2001 SourceLocation Loc, QualType Ty,
2002 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002003 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002004 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +00002005 (SanitizerKind::Address | SanitizerKind::KernelAddress |
2006 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002007 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002008 return false;
2009 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002010 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002011 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002012 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002013 return true;
2014 // Check global type.
2015 if (!Ty.isNull()) {
2016 // Drill down the array types: if global variable of a fixed type is
2017 // blacklisted, we also don't instrument arrays of them.
2018 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2019 Ty = AT->getElementType();
2020 Ty = Ty.getCanonicalType().getUnqualifiedType();
2021 // We allow to blacklist only record types (classes, structs etc.)
2022 if (Ty->isRecordType()) {
2023 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002024 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002025 return true;
2026 }
2027 }
2028 return false;
2029}
2030
Dean Michael Berris835832d2017-03-30 00:29:36 +00002031bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2032 StringRef Category) const {
Dean Michael Berris835832d2017-03-30 00:29:36 +00002033 const auto &XRayFilter = getContext().getXRayFilter();
2034 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00002035 auto Attr = ImbueAttr::NONE;
Dean Michael Berris835832d2017-03-30 00:29:36 +00002036 if (Loc.isValid())
2037 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2038 if (Attr == ImbueAttr::NONE)
2039 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2040 switch (Attr) {
2041 case ImbueAttr::NONE:
2042 return false;
2043 case ImbueAttr::ALWAYS:
2044 Fn->addFnAttr("function-instrument", "xray-always");
2045 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00002046 case ImbueAttr::ALWAYS_ARG1:
2047 Fn->addFnAttr("function-instrument", "xray-always");
2048 Fn->addFnAttr("xray-log-args", "1");
2049 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00002050 case ImbueAttr::NEVER:
2051 Fn->addFnAttr("function-instrument", "xray-never");
2052 break;
2053 }
2054 return true;
2055}
2056
Hans Wennborg43a0f992015-01-10 01:19:48 +00002057bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00002058 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002059 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00002060 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002061
Elizabeth Andrews6593df22018-08-22 19:05:19 +00002062 if (CodeGenOpts.KeepStaticConsts) {
2063 const auto *VD = dyn_cast<VarDecl>(Global);
2064 if (VD && VD->getType().isConstQualified() &&
Erich Keane85822b32018-10-25 19:13:46 +00002065 VD->getStorageDuration() == SD_Static)
Elizabeth Andrews6593df22018-08-22 19:05:19 +00002066 return true;
2067 }
2068
Hans Wennborg43a0f992015-01-10 01:19:48 +00002069 return getContext().DeclMustBeEmitted(Global);
2070}
2071
2072bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2073 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
2074 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2075 // Implicit template instantiations may change linkage if they are later
2076 // explicitly instantiated, so they should not be emitted eagerly.
2077 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00002078 if (const auto *VD = dyn_cast<VarDecl>(Global))
2079 if (Context.getInlineVariableDefinitionKind(VD) ==
2080 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2081 // A definition of an inline constexpr static data member may change
2082 // linkage later if it's redeclared outside the class.
2083 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00002084 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2085 // codegen for global variables, because they may be marked as threadprivate.
2086 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
Alexey Bataev96edb2e2018-06-25 15:32:05 +00002087 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
Alexey Bataevd01b7492018-08-15 19:45:12 +00002088 !isTypeConstant(Global->getType(), false) &&
2089 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
Samuel Antaof8b50122015-07-13 22:54:53 +00002090 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00002091
2092 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002093}
2094
John McCall7f416cc2015-09-08 08:05:57 +00002095ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00002096 const CXXUuidofExpr* E) {
2097 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2098 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00002099 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00002100 std::string Name = "_GUID_" + Uuid.lower();
2101 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00002102
David Majnemer65687602016-03-27 04:46:14 +00002103 // The UUID descriptor should be pointer aligned.
2104 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00002105
Nico Webercf4ff5862012-10-11 10:13:44 +00002106 // Look for an existing global.
2107 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00002108 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002109
Nico Weber17d3a2c2014-09-08 16:26:36 +00002110 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00002111 assert(Init && "failed to initialize as constant");
2112
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002113 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00002114 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00002115 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002116 if (supportsCOMDAT())
2117 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolaca08d242018-03-20 15:42:58 +00002118 setDSOLocal(GV);
John McCall7f416cc2015-09-08 08:05:57 +00002119 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002120}
2121
John McCall7f416cc2015-09-08 08:05:57 +00002122ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002123 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2124 assert(AA && "No alias?");
2125
John McCall7f416cc2015-09-08 08:05:57 +00002126 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002127 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002128
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002129 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00002130 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002131 if (Entry) {
2132 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00002133 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2134 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002135 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002136
2137 llvm::Constant *Aliasee;
2138 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002139 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2140 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00002141 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002142 else
John McCall7ec50432010-03-19 23:29:14 +00002143 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00002144 llvm::PointerType::getUnqual(DeclTy),
2145 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002146
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002147 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002148 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2149 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002150
John McCall7f416cc2015-09-08 08:05:57 +00002151 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002152}
2153
Chris Lattnere0be0df2009-05-12 21:21:08 +00002154void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002155 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002156
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002157 // Weak references don't produce any output by themselves.
2158 if (Global->hasAttr<WeakRefAttr>())
2159 return;
2160
Chris Lattner54041692009-03-22 21:47:11 +00002161 // If this is an alias definition (which otherwise looks like a declaration)
2162 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002163 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00002164 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002165
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002166 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2167 if (Global->hasAttr<IFuncAttr>())
2168 return emitIFuncDefinition(GD);
2169
Erich Keane3efe0022018-07-20 14:13:28 +00002170 // If this is a cpu_dispatch multiversion function, emit the resolver.
2171 if (Global->hasAttr<CPUDispatchAttr>())
2172 return emitCPUDispatchDefinition(GD);
2173
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002174 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002175 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00002176 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002177 if (!Global->hasAttr<CUDADeviceAttr>() &&
2178 !Global->hasAttr<CUDAGlobalAttr>() &&
2179 !Global->hasAttr<CUDAConstantAttr>() &&
2180 !Global->hasAttr<CUDASharedAttr>())
2181 return;
2182 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00002183 // We need to emit host-side 'shadows' for all global
2184 // device-side variables because the CUDA runtime needs their
2185 // size and host-side address in order to provide access to
2186 // their device-side incarnations.
2187
2188 // So device-only functions are the only things we skip.
2189 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2190 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002191 return;
Artem Belevich42e19492016-03-02 18:28:50 +00002192
2193 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2194 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002195 }
2196 }
2197
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002198 if (LangOpts.OpenMP) {
2199 // If this is OpenMP device, check if it is legal to emit this global
2200 // normally.
2201 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2202 return;
2203 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2204 if (MustBeEmitted(Global))
2205 EmitOMPDeclareReduction(DRD);
2206 return;
Michael Kruse251e1482019-02-01 20:25:04 +00002207 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2208 if (MustBeEmitted(Global))
2209 EmitOMPDeclareMapper(DMD);
2210 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002211 }
2212 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002213
Chris Lattner45470942009-03-21 09:44:56 +00002214 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002215 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002216 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002217 if (!FD->doesThisDeclarationHaveABody()) {
2218 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2219 return;
2220
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002221 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00002222
2223 // Compute the function info and LLVM type.
2224 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2225 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2226
2227 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2228 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002229 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002230 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002231 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002232 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002233 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich99535772018-12-22 01:11:09 +00002234 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00002235 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00002236 if (LangOpts.OpenMP) {
2237 // Emit declaration of the must-be-emitted declare target variable.
2238 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2239 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2240 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
2241 (void)GetAddrOfGlobalVar(VD);
2242 } else {
2243 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
2244 "link claue expected.");
2245 (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
2246 }
2247 return;
2248 }
2249 }
Richard Smithd9b90092016-07-02 01:32:16 +00002250 // If this declaration may have caused an inline variable definition to
2251 // change linkage, make sure that it's emitted.
2252 if (Context.getInlineVariableDefinitionKind(VD) ==
2253 ASTContext::InlineVariableDefinitionKind::Strong)
2254 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00002255 return;
Richard Smithd9b90092016-07-02 01:32:16 +00002256 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002257 }
2258
Hans Wennborg43a0f992015-01-10 01:19:48 +00002259 // Defer code generation to first use when possible, e.g. if this is an inline
2260 // function. If the global must always be emitted, do it eagerly if possible
2261 // to benefit from cache locality.
2262 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002263 // Emit the definition if it can't be deferred.
2264 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002265 return;
2266 }
John McCall70013b62010-07-15 23:40:35 +00002267
2268 // If we're deferring emission of a C++ variable with an
2269 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002270 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00002271 cast<VarDecl>(Global)->hasInit()) {
2272 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00002273 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00002274 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00002275
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002276 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00002277 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00002278 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00002279 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002280 } else if (MustBeEmitted(Global)) {
2281 // The value must be emitted, but cannot be emitted eagerly.
2282 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00002283 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002284 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002285 // Otherwise, remember that we saw a deferred decl with this name. The
2286 // first use of the mangled name will cause it to move into
2287 // DeferredDeclsToEmit.
2288 DeferredDecls[MangledName] = GD;
2289 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002290}
2291
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002292// Check if T is a class type with a destructor that's not dllimport.
2293static bool HasNonDllImportDtor(QualType T) {
2294 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2295 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2296 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2297 return true;
2298
2299 return false;
2300}
2301
Rafael Espindolac5941352011-10-26 20:41:06 +00002302namespace {
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002303 struct FunctionIsDirectlyRecursive
2304 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
Rafael Espindolac5941352011-10-26 20:41:06 +00002305 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002306 const Builtin::Context &BI;
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002307 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
2308 : Name(N), BI(C) {}
Rafael Espindolac5941352011-10-26 20:41:06 +00002309
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002310 bool VisitCallExpr(const CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002311 const FunctionDecl *FD = E->getDirectCallee();
2312 if (!FD)
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002313 return false;
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002314 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2315 if (Attr && Name == Attr->getLabel())
2316 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002317 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00002318 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002319 return false;
Eric Christopher02d5d862015-08-06 01:01:12 +00002320 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00002321 if (BuiltinName.startswith("__builtin_") &&
2322 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002323 return true;
Rafael Espindolac5941352011-10-26 20:41:06 +00002324 }
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002325 return false;
2326 }
2327
2328 bool VisitStmt(const Stmt *S) {
2329 for (const Stmt *Child : S->children())
2330 if (Child && this->Visit(Child))
2331 return true;
2332 return false;
Rafael Espindolac5941352011-10-26 20:41:06 +00002333 }
2334 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002335
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002336 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002337 struct DLLImportFunctionVisitor
2338 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2339 bool SafeToInline = true;
2340
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002341 bool shouldVisitImplicitCode() const { return true; }
2342
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002343 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002344 if (VD->getTLSKind()) {
2345 // A thread-local variable cannot be imported.
2346 SafeToInline = false;
2347 return SafeToInline;
2348 }
2349
2350 // A variable definition might imply a destructor call.
2351 if (VD->isThisDeclarationADefinition())
2352 SafeToInline = !HasNonDllImportDtor(VD->getType());
2353
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002354 return SafeToInline;
2355 }
2356
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002357 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2358 if (const auto *D = E->getTemporary()->getDestructor())
2359 SafeToInline = D->hasAttr<DLLImportAttr>();
2360 return SafeToInline;
2361 }
2362
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002363 bool VisitDeclRefExpr(DeclRefExpr *E) {
2364 ValueDecl *VD = E->getDecl();
2365 if (isa<FunctionDecl>(VD))
2366 SafeToInline = VD->hasAttr<DLLImportAttr>();
2367 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2368 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2369 return SafeToInline;
2370 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002371
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002372 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2373 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2374 return SafeToInline;
2375 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002376
Hans Wennborg251c2042017-01-23 23:57:50 +00002377 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2378 CXXMethodDecl *M = E->getMethodDecl();
2379 if (!M) {
2380 // Call through a pointer to member function. This is safe to inline.
2381 SafeToInline = true;
2382 } else {
2383 SafeToInline = M->hasAttr<DLLImportAttr>();
2384 }
2385 return SafeToInline;
2386 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002387
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002388 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2389 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2390 return SafeToInline;
2391 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002392
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002393 bool VisitCXXNewExpr(CXXNewExpr *E) {
2394 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2395 return SafeToInline;
2396 }
2397 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002398}
Rafael Espindolac5941352011-10-26 20:41:06 +00002399
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002400// isTriviallyRecursive - Check if this function calls another
2401// decl that, because of the asm attribute or the other decl being a builtin,
2402// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00002403bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002404CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2405 StringRef Name;
2406 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00002407 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002408 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2409 if (!Attr)
2410 return false;
2411 Name = Attr->getLabel();
2412 } else {
2413 Name = FD->getName();
2414 }
Rafael Espindolac5941352011-10-26 20:41:06 +00002415
David Majnemer64b0bdf2015-06-30 04:41:18 +00002416 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002417 const Stmt *Body = FD->getBody();
2418 return Body ? Walker.Visit(Body) : false;
Rafael Espindolac5941352011-10-26 20:41:06 +00002419}
2420
Hans Wennborg93f75472016-09-13 21:08:20 +00002421bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002422 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00002423 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002424 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00002425 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00002426 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002427
2428 if (F->hasAttr<DLLImportAttr>()) {
2429 // Check whether it would be safe to inline this dllimport function.
2430 DLLImportFunctionVisitor Visitor;
2431 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2432 if (!Visitor.SafeToInline)
2433 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00002434
2435 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2436 // Implicit destructor invocations aren't captured in the AST, so the
2437 // check above can't see them. Check for them manually here.
2438 for (const Decl *Member : Dtor->getParent()->decls())
2439 if (isa<FieldDecl>(Member))
2440 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2441 return false;
2442 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2443 if (HasNonDllImportDtor(B.getType()))
2444 return false;
2445 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002446 }
2447
Rafael Espindolac5941352011-10-26 20:41:06 +00002448 // PR9614. Avoid cases where the source code is lying to us. An available
2449 // externally function should have an equivalent function somewhere else,
2450 // but a function that calls itself is clearly not equivalent to the real
2451 // implementation.
2452 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002453 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00002454}
2455
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002456bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2457 return CodeGenOpts.OptimizationLevel > 0;
2458}
2459
Erich Keanede6480a32018-11-13 15:48:08 +00002460void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2461 llvm::GlobalValue *GV) {
2462 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2463
2464 if (FD->isCPUSpecificMultiVersion()) {
2465 auto *Spec = FD->getAttr<CPUSpecificAttr>();
2466 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2467 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2468 // Requires multiple emits.
2469 } else
2470 EmitGlobalFunctionDefinition(GD, GV);
2471}
2472
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002473void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002474 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002475
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002476 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00002477 Context.getSourceManager(),
2478 "Generating code for declaration");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002479
Erich Keanede6480a32018-11-13 15:48:08 +00002480 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002481 // At -O0, don't generate IR for functions with available_externally
Douglas Gregora700f682010-07-13 06:02:28 +00002482 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002483 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002484 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002485
Anton Afanasyevd880de22019-03-30 08:42:48 +00002486 llvm::TimeTraceScope TimeScope(
2487 "CodeGen Function", [&]() { return FD->getQualifiedNameAsString(); });
2488
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002489 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002490 // Make sure to emit the definition(s) before we emit the thunks.
2491 // This is necessary for the generation of certain thunks.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00002492 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2493 ABI->emitCXXStructor(GD);
Erich Keanede6480a32018-11-13 15:48:08 +00002494 else if (FD->isMultiVersion())
2495 EmitMultiVersionFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002496 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002497 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002498
Douglas Gregora700f682010-07-13 06:02:28 +00002499 if (Method->isVirtual())
2500 getVTables().EmitThunks(GD);
2501
Eli Friedman49a94b12011-05-06 17:27:27 +00002502 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002503 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002504
Erich Keanede6480a32018-11-13 15:48:08 +00002505 if (FD->isMultiVersion())
2506 return EmitMultiVersionFunctionDefinition(GD, GV);
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002507 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002508 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002509
2510 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002511 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002512
David Blaikie83d382b2011-09-23 05:06:16 +00002513 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002514}
2515
Andrey Bokhankocab58582015-08-31 13:20:44 +00002516static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2517 llvm::Function *NewFn);
2518
Erich Keanef353ae12018-09-13 16:58:24 +00002519static unsigned
2520TargetMVPriority(const TargetInfo &TI,
2521 const CodeGenFunction::MultiVersionResolverOption &RO) {
2522 unsigned Priority = 0;
2523 for (StringRef Feat : RO.Conditions.Features)
2524 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2525
2526 if (!RO.Conditions.Architecture.empty())
2527 Priority = std::max(
2528 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2529 return Priority;
2530}
2531
Erich Keane281d20b2018-01-08 21:34:17 +00002532void CodeGenModule::emitMultiVersionFunctions() {
2533 for (GlobalDecl GD : MultiVersionFuncs) {
Erich Keanef353ae12018-09-13 16:58:24 +00002534 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane281d20b2018-01-08 21:34:17 +00002535 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2536 getContext().forEachMultiversionedFunctionVersion(
2537 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2538 GlobalDecl CurGD{
2539 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2540 StringRef MangledName = getMangledName(CurGD);
2541 llvm::Constant *Func = GetGlobalValue(MangledName);
2542 if (!Func) {
2543 if (CurFD->isDefined()) {
2544 EmitGlobalFunctionDefinition(CurGD, nullptr);
2545 Func = GetGlobalValue(MangledName);
2546 } else {
2547 const CGFunctionInfo &FI =
2548 getTypes().arrangeGlobalDeclaration(GD);
2549 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2550 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2551 /*DontDefer=*/false, ForDefinition);
2552 }
2553 assert(Func && "This should have just been created");
2554 }
Erich Keanef353ae12018-09-13 16:58:24 +00002555
2556 const auto *TA = CurFD->getAttr<TargetAttr>();
2557 llvm::SmallVector<StringRef, 8> Feats;
2558 TA->getAddedFeatures(Feats);
2559
2560 Options.emplace_back(cast<llvm::Function>(Func),
2561 TA->getArchitecture(), Feats);
Erich Keane281d20b2018-01-08 21:34:17 +00002562 });
2563
Erich Keane19a8adc2018-10-25 18:57:19 +00002564 llvm::Function *ResolverFunc;
2565 const TargetInfo &TI = getTarget();
2566
2567 if (TI.supportsIFunc() || FD->isTargetMultiVersion())
2568 ResolverFunc = cast<llvm::Function>(
2569 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2570 else
2571 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2572
Erich Keane0a6fde42018-01-16 19:49:52 +00002573 if (supportsCOMDAT())
2574 ResolverFunc->setComdat(
2575 getModule().getOrInsertComdat(ResolverFunc->getName()));
Erich Keanef353ae12018-09-13 16:58:24 +00002576
Erich Keane281d20b2018-01-08 21:34:17 +00002577 std::stable_sort(
2578 Options.begin(), Options.end(),
Erich Keanef353ae12018-09-13 16:58:24 +00002579 [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2580 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2581 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2582 });
Erich Keane281d20b2018-01-08 21:34:17 +00002583 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002584 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane281d20b2018-01-08 21:34:17 +00002585 }
2586}
2587
Erich Keane3efe0022018-07-20 14:13:28 +00002588void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2589 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2590 assert(FD && "Not a FunctionDecl?");
2591 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2592 assert(DD && "Not a cpu_dispatch Function?");
James Y Knight916db652019-02-02 01:48:23 +00002593 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
Erich Keane9e94c182018-11-01 15:11:41 +00002594
2595 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2596 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
2597 DeclTy = getTypes().GetFunctionType(FInfo);
2598 }
Erich Keane3efe0022018-07-20 14:13:28 +00002599
2600 StringRef ResolverName = getMangledName(GD);
Erich Keane19a8adc2018-10-25 18:57:19 +00002601
2602 llvm::Type *ResolverType;
2603 GlobalDecl ResolverGD;
2604 if (getTarget().supportsIFunc())
2605 ResolverType = llvm::FunctionType::get(
2606 llvm::PointerType::get(DeclTy,
2607 Context.getTargetAddressSpace(FD->getType())),
2608 false);
2609 else {
2610 ResolverType = DeclTy;
2611 ResolverGD = GD;
2612 }
2613
2614 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2615 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
Erich Keane3efe0022018-07-20 14:13:28 +00002616
Erich Keanef353ae12018-09-13 16:58:24 +00002617 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane3efe0022018-07-20 14:13:28 +00002618 const TargetInfo &Target = getTarget();
Erich Keanede6480a32018-11-13 15:48:08 +00002619 unsigned Index = 0;
Erich Keane3efe0022018-07-20 14:13:28 +00002620 for (const IdentifierInfo *II : DD->cpus()) {
2621 // Get the name of the target function so we can look it up/create it.
2622 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2623 getCPUSpecificMangling(*this, II->getName());
Erich Keanede6480a32018-11-13 15:48:08 +00002624
2625 llvm::Constant *Func = GetGlobalValue(MangledName);
2626
Erich Keane248ed072018-12-07 15:31:23 +00002627 if (!Func) {
2628 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
2629 if (ExistingDecl.getDecl() &&
2630 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
2631 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
2632 Func = GetGlobalValue(MangledName);
2633 } else {
2634 if (!ExistingDecl.getDecl())
2635 ExistingDecl = GD.getWithMultiVersionIndex(Index);
2636
Erich Keanede6480a32018-11-13 15:48:08 +00002637 Func = GetOrCreateLLVMFunction(
Erich Keane248ed072018-12-07 15:31:23 +00002638 MangledName, DeclTy, ExistingDecl,
Erich Keanede6480a32018-11-13 15:48:08 +00002639 /*ForVTable=*/false, /*DontDefer=*/true,
2640 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
Erich Keane248ed072018-12-07 15:31:23 +00002641 }
2642 }
Erich Keanede6480a32018-11-13 15:48:08 +00002643
Erich Keane3efe0022018-07-20 14:13:28 +00002644 llvm::SmallVector<StringRef, 32> Features;
2645 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2646 llvm::transform(Features, Features.begin(),
2647 [](StringRef Str) { return Str.substr(1); });
2648 Features.erase(std::remove_if(
2649 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2650 return !Target.validateCpuSupports(Feat);
2651 }), Features.end());
Erich Keanef353ae12018-09-13 16:58:24 +00002652 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
Erich Keanede6480a32018-11-13 15:48:08 +00002653 ++Index;
Erich Keane3efe0022018-07-20 14:13:28 +00002654 }
2655
2656 llvm::sort(
Fangrui Song1d38c132018-09-30 21:41:11 +00002657 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
2658 const CodeGenFunction::MultiVersionResolverOption &RHS) {
Erich Keanef353ae12018-09-13 16:58:24 +00002659 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
2660 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
2661 });
Erich Keane44731c52018-11-01 12:50:37 +00002662
2663 // If the list contains multiple 'default' versions, such as when it contains
2664 // 'pentium' and 'generic', don't emit the call to the generic one (since we
2665 // always run on at least a 'pentium'). We do this by deleting the 'least
2666 // advanced' (read, lowest mangling letter).
2667 while (Options.size() > 1 &&
2668 CodeGenFunction::GetX86CpuSupportsMask(
2669 (Options.end() - 2)->Conditions.Features) == 0) {
2670 StringRef LHSName = (Options.end() - 2)->Function->getName();
2671 StringRef RHSName = (Options.end() - 1)->Function->getName();
2672 if (LHSName.compare(RHSName) < 0)
2673 Options.erase(Options.end() - 2);
2674 else
2675 Options.erase(Options.end() - 1);
2676 }
2677
Erich Keane3efe0022018-07-20 14:13:28 +00002678 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002679 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane3efe0022018-07-20 14:13:28 +00002680}
2681
Erich Keane19a8adc2018-10-25 18:57:19 +00002682/// If a dispatcher for the specified mangled name is not in the module, create
2683/// and return an llvm Function with the specified type.
2684llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2685 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
Erich Keane3efe0022018-07-20 14:13:28 +00002686 std::string MangledName =
2687 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane19a8adc2018-10-25 18:57:19 +00002688
2689 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
2690 // a separate resolver).
2691 std::string ResolverName = MangledName;
2692 if (getTarget().supportsIFunc())
2693 ResolverName += ".ifunc";
2694 else if (FD->isTargetMultiVersion())
2695 ResolverName += ".resolver";
2696
2697 // If this already exists, just return that one.
2698 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
2699 return ResolverGV;
Erich Keane281d20b2018-01-08 21:34:17 +00002700
2701 // Since this is the first time we've created this IFunc, make sure
2702 // that we put this multiversioned function into the list to be
Erich Keane3efe0022018-07-20 14:13:28 +00002703 // replaced later if necessary (target multiversioning only).
2704 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2705 MultiVersionFuncs.push_back(GD);
Erich Keane281d20b2018-01-08 21:34:17 +00002706
Erich Keane19a8adc2018-10-25 18:57:19 +00002707 if (getTarget().supportsIFunc()) {
2708 llvm::Type *ResolverType = llvm::FunctionType::get(
2709 llvm::PointerType::get(
2710 DeclTy, getContext().getTargetAddressSpace(FD->getType())),
2711 false);
2712 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2713 MangledName + ".resolver", ResolverType, GlobalDecl{},
2714 /*ForVTable=*/false);
2715 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2716 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2717 GIF->setName(ResolverName);
2718 SetCommonAttributes(FD, GIF);
Erich Keane281d20b2018-01-08 21:34:17 +00002719
Erich Keane19a8adc2018-10-25 18:57:19 +00002720 return GIF;
2721 }
2722
2723 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2724 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
2725 assert(isa<llvm::GlobalValue>(Resolver) &&
2726 "Resolver should be created for the first time");
2727 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
2728 return Resolver;
Erich Keane281d20b2018-01-08 21:34:17 +00002729}
2730
Chris Lattnerd4808922009-03-22 21:03:39 +00002731/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2732/// module, create and return an llvm Function with the specified type. If there
2733/// is something in the module with the specified name, return it potentially
2734/// bitcasted to the right type.
2735///
2736/// If D is non-null, it specifies a decl that correspond to this. This is used
2737/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002738llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2739 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2740 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2741 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002742 const Decl *D = GD.getDecl();
2743
Erich Keane281d20b2018-01-08 21:34:17 +00002744 // Any attempts to use a MultiVersion function should result in retrieving
2745 // the iFunc instead. Name Mangling will handle the rest of the changes.
2746 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002747 // For the device mark the function as one that should be emitted.
2748 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
Alexey Bataev6d944102018-05-02 15:45:28 +00002749 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002750 !DontDefer && !IsForDefinition) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002751 if (const FunctionDecl *FDDef = FD->getDefinition()) {
2752 GlobalDecl GDDef;
2753 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2754 GDDef = GlobalDecl(CD, GD.getCtorType());
2755 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2756 GDDef = GlobalDecl(DD, GD.getDtorType());
2757 else
2758 GDDef = GlobalDecl(FDDef);
2759 EmitGlobal(GDDef);
2760 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002761 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002762
Erich Keane3efe0022018-07-20 14:13:28 +00002763 if (FD->isMultiVersion()) {
2764 const auto *TA = FD->getAttr<TargetAttr>();
2765 if (TA && TA->isDefaultVersion())
2766 UpdateMultiVersionNames(GD, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00002767 if (!IsForDefinition)
Erich Keane19a8adc2018-10-25 18:57:19 +00002768 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00002769 }
2770 }
2771
Chris Lattnera85d68e2009-03-21 09:25:43 +00002772 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002773 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002774 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002775 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002776 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002777 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002778 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002779 }
2780
Hans Wennborg0a20f542014-08-29 00:16:06 +00002781 // Handle dropped DLL attributes.
Rafael Espindolac9643d82018-03-29 16:45:18 +00002782 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Hans Wennborg0a20f542014-08-29 00:16:06 +00002783 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
Rafael Espindolac9643d82018-03-29 16:45:18 +00002784 setDSOLocal(Entry);
2785 }
Hans Wennborg0a20f542014-08-29 00:16:06 +00002786
Andrey Bokhankocab58582015-08-31 13:20:44 +00002787 // If there are two attempts to define the same mangled name, issue an
2788 // error.
2789 if (IsForDefinition && !Entry->isDeclaration()) {
2790 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002791 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2792 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002793 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2794 (GD.getCanonicalDecl().getDecl() !=
2795 OtherGD.getCanonicalDecl().getDecl()) &&
2796 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00002797 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2798 << MangledName;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002799 getDiags().Report(OtherGD.getDecl()->getLocation(),
2800 diag::note_previous_definition);
2801 }
2802 }
2803
2804 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2805 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002806 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002807 }
Mike Stump11289f42009-09-09 15:08:12 +00002808
Chris Lattnera85d68e2009-03-21 09:25:43 +00002809 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002810 // (If function is requested for a definition, we always need to create a new
2811 // function, not just return a bitcast.)
2812 if (!IsForDefinition)
2813 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002814 }
Mike Stump11289f42009-09-09 15:08:12 +00002815
Eli Friedmancc522d92009-11-09 05:07:37 +00002816 // This function doesn't have a complete type (for example, the return
2817 // type is an incomplete struct). Use a fake type instead, and make
2818 // sure not to try to set attributes.
2819 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002820
Chris Lattner2192fe52011-07-18 04:24:23 +00002821 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002822 if (isa<llvm::FunctionType>(Ty)) {
2823 FTy = cast<llvm::FunctionType>(Ty);
2824 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002825 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002826 IsIncompleteFunction = true;
2827 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002828
2829 llvm::Function *F =
2830 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2831 Entry ? StringRef() : MangledName, &getModule());
2832
2833 // If we already created a function with the same mangled name (but different
2834 // type) before, take its name and add it to the list of functions to be
2835 // replaced with F at the end of CodeGen.
2836 //
2837 // This happens if there is a prototype for a function (e.g. "int f()") and
2838 // then a definition of a different type (e.g. "int f(int x)").
2839 if (Entry) {
2840 F->takeName(Entry);
2841
2842 // This might be an implementation of a function without a prototype, in
2843 // which case, try to do special replacement of calls which match the new
2844 // prototype. The really key thing here is that we also potentially drop
2845 // arguments from the call site so as to make a direct call, which makes the
2846 // inliner happier and suppresses a number of optimizer warnings (!) about
2847 // dropping arguments.
2848 if (!Entry->use_empty()) {
2849 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2850 Entry->removeDeadConstantUsers();
2851 }
2852
2853 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2854 F, Entry->getType()->getElementType()->getPointerTo());
2855 addGlobalValReplacement(Entry, BC);
2856 }
2857
John McCall7ec50432010-03-19 23:29:14 +00002858 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002859 if (D)
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002860 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00002861 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2862 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002863 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002864 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002865
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002866 if (!DontDefer) {
2867 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2868 // each other bottoming out with the base dtor. Therefore we emit non-base
2869 // dtors on usage, even if there is no dtor definition in the TU.
2870 if (D && isa<CXXDestructorDecl>(D) &&
2871 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2872 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002873 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002874
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002875 // This is the first use or definition of a mangled name. If there is a
2876 // deferred decl with this name, remember that we need to emit it at the end
2877 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002878 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002879 if (DDI != DeferredDecls.end()) {
2880 // Move the potentially referenced deferred decl to the
2881 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2882 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002883 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002884 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002885
2886 // Otherwise, there are cases we have to worry about where we're
2887 // using a declaration for which we must emit a definition but where
2888 // we might not find a top-level definition:
2889 // - member functions defined inline in their classes
2890 // - friend functions defined inline in some class
2891 // - special member functions with implicit definitions
2892 // If we ever change our AST traversal to walk into class methods,
2893 // this will be unnecessary.
2894 //
2895 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002896 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002897 } else if (getLangOpts().CPlusPlus && D) {
2898 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002899 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2900 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002901 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002902 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002903 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002904 break;
2905 }
John McCall357d0f32010-12-15 04:00:32 +00002906 }
Richard Smith46bb5812014-08-01 01:56:39 +00002907 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002908 }
Chris Lattner45470942009-03-21 09:44:56 +00002909 }
Mike Stump11289f42009-09-09 15:08:12 +00002910
John McCalld06fb862010-04-28 00:00:30 +00002911 // Make sure the result is of the requested type.
2912 if (!IsIncompleteFunction) {
2913 assert(F->getType()->getElementType() == Ty);
2914 return F;
2915 }
2916
Chris Lattnera5f58b02011-07-09 17:41:47 +00002917 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002918 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002919}
2920
Chris Lattnerd4808922009-03-22 21:03:39 +00002921/// GetAddrOfFunction - Return the address of the given function. If Ty is
2922/// non-null, then this function will use the specified type if it has to
2923/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002924llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002925 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002926 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002927 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002928 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002929 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002930 if (!Ty) {
2931 const auto *FD = cast<FunctionDecl>(GD.getDecl());
James Y Knight916db652019-02-02 01:48:23 +00002932 Ty = getTypes().ConvertType(FD->getType());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002933 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002934
Reid Kleckner28103252018-03-16 22:20:57 +00002935 // Devirtualized destructor calls may come through here instead of via
2936 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2937 // of the complete destructor when necessary.
2938 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2939 if (getTarget().getCXXABI().isMicrosoft() &&
2940 GD.getDtorType() == Dtor_Complete &&
2941 DD->getParent()->getNumVBases() == 0)
2942 GD = GlobalDecl(DD, Dtor_Base);
2943 }
2944
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002945 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002946 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002947 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002948 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002949}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002950
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002951static const FunctionDecl *
2952GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2953 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2954 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2955
2956 IdentifierInfo &CII = C.Idents.get(Name);
2957 for (const auto &Result : DC->lookup(&CII))
2958 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2959 return FD;
2960
2961 if (!C.getLangOpts().CPlusPlus)
2962 return nullptr;
2963
2964 // Demangle the premangled name from getTerminateFn()
2965 IdentifierInfo &CXXII =
Reid Klecknerfb931542018-03-16 20:36:49 +00002966 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002967 ? C.Idents.get("terminate")
2968 : C.Idents.get(Name);
2969
2970 for (const auto &N : {"__cxxabiv1", "std"}) {
2971 IdentifierInfo &NS = C.Idents.get(N);
2972 for (const auto &Result : DC->lookup(&NS)) {
2973 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2974 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2975 for (const auto &Result : LSD->lookup(&NS))
2976 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2977 break;
2978
2979 if (ND)
2980 for (const auto &Result : ND->lookup(&CXXII))
2981 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2982 return FD;
2983 }
2984 }
2985
2986 return nullptr;
2987}
2988
Chris Lattnerd4808922009-03-22 21:03:39 +00002989/// CreateRuntimeFunction - Create a new runtime function with the specified
2990/// type and name.
James Y Knight9871db02019-02-05 16:42:33 +00002991llvm::FunctionCallee
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002992CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002993 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002994 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002995 llvm::Constant *C =
2996 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002997 /*DontDefer=*/false, /*IsThunk=*/false,
2998 ExtraAttrs);
2999
3000 if (auto *F = dyn_cast<llvm::Function>(C)) {
3001 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00003002 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003003
3004 if (!Local && getTriple().isOSBinFormatCOFF() &&
Martell Maloneb22e6002017-11-04 02:15:49 +00003005 !getCodeGenOpts().LTOVisibilityPublicStd &&
3006 !getTriple().isWindowsGNUEnvironment()) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003007 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3008 if (!FD || FD->hasAttr<DLLImportAttr>()) {
3009 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3010 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3011 }
3012 }
Rafael Espindola3c9be622018-03-20 20:27:30 +00003013 setDSOLocal(F);
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003014 }
3015 }
3016
James Y Knight9871db02019-02-05 16:42:33 +00003017 return {FTy, C};
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00003018}
3019
Richard Smithe070fd22012-02-17 06:48:11 +00003020/// isTypeConstant - Determine whether an object of this type can be emitted
3021/// as a constant.
3022///
3023/// If ExcludeCtor is true, the duration when the object's constructor runs
3024/// will not be considered. The caller will need to verify that the object is
3025/// not written to during its construction.
3026bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3027 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00003028 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00003029
David Blaikiebbafb8a2012-03-11 07:00:24 +00003030 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00003031 if (const CXXRecordDecl *Record
3032 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3033 return ExcludeCtor && !Record->hasMutableFields() &&
3034 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00003035 }
Richard Smithe070fd22012-02-17 06:48:11 +00003036
Eli Friedmanb095e152009-12-11 21:23:03 +00003037 return true;
3038}
3039
Chris Lattnerd4808922009-03-22 21:03:39 +00003040/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3041/// create and return an llvm GlobalVariable with the specified type. If there
3042/// is something in the module with the specified name, return it potentially
3043/// bitcasted to the right type.
3044///
3045/// If D is non-null, it specifies a decl that correspond to this. This is used
3046/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003047///
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003048/// If IsForDefinition is true, it is guaranteed that an actual global with
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003049/// type Ty will be returned, not conversion of a variable with the same
3050/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00003051llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003052CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00003053 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003054 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00003055 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00003056 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00003057 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00003058 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00003059 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00003060 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00003061 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00003062 }
3063
Hans Wennborg0a20f542014-08-29 00:16:06 +00003064 // Handle dropped DLL attributes.
3065 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3066 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3067
Alexey Bataev03f270c2018-03-30 18:31:07 +00003068 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3069 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3070
Chris Lattnerd4808922009-03-22 21:03:39 +00003071 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00003072 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00003073
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003074 // If there are two attempts to define the same mangled name, issue an
3075 // error.
3076 if (IsForDefinition && !Entry->isDeclaration()) {
3077 GlobalDecl OtherGD;
3078 const VarDecl *OtherD;
3079
3080 // Check that D is not yet in DiagnosedConflictingDefinitions is required
3081 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00003082 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003083 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3084 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3085 OtherD->hasInit() &&
3086 DiagnosedConflictingDefinitions.insert(D).second) {
Richard Smithb5345102018-05-30 01:52:16 +00003087 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3088 << MangledName;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003089 getDiags().Report(OtherGD.getDecl()->getLocation(),
3090 diag::note_previous_definition);
3091 }
3092 }
3093
Chris Lattner3bfce182009-03-21 08:03:33 +00003094 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00003095 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3096 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3097
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003098 // (If global is requested for a definition, we always need to create a new
3099 // global, not just return a bitcast.)
3100 if (!IsForDefinition)
3101 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00003102 }
Mike Stump11289f42009-09-09 15:08:12 +00003103
Yaxun Liucbf647c2017-07-08 13:24:52 +00003104 auto AddrSpace = GetGlobalVarAddressSpace(D);
3105 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3106
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003107 auto *GV = new llvm::GlobalVariable(
3108 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00003109 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00003110 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00003111
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003112 // If we already created a global with the same mangled name (but different
3113 // type) before, take its name and remove it from its parent.
3114 if (Entry) {
3115 GV->takeName(Entry);
3116
3117 if (!Entry->use_empty()) {
3118 llvm::Constant *NewPtrForOldDecl =
3119 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3120 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3121 }
3122
3123 Entry->eraseFromParent();
3124 }
3125
Chris Lattner45470942009-03-21 09:44:56 +00003126 // This is the first use or definition of a mangled name. If there is a
3127 // deferred decl with this name, remember that we need to emit it at the end
3128 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00003129 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00003130 if (DDI != DeferredDecls.end()) {
3131 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3132 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00003133 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00003134 DeferredDecls.erase(DDI);
3135 }
Mike Stump11289f42009-09-09 15:08:12 +00003136
Chris Lattner3bfce182009-03-21 08:03:33 +00003137 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00003138 if (D) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003139 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3140 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3141
Mike Stump18bb9282009-05-16 07:57:57 +00003142 // FIXME: This code is overly simple and should be merged with other global
3143 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00003144 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00003145
Ulrich Weigand46084382015-04-21 17:27:59 +00003146 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3147
Jake Ehrlichba874ad2017-11-29 00:54:20 +00003148 setLinkageForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00003149
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003150 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00003151 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003152 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00003153 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003154 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00003155
Rafael Espindola3dd49812018-02-23 00:22:15 +00003156 setGVProperties(GV, D);
3157
Hans Wennborgfeedf852013-11-21 00:15:56 +00003158 // If required by the ABI, treat declarations of static data members with
3159 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003160 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00003161 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003162 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00003163
Erich Keane99fdfb62017-09-26 23:42:34 +00003164 // Emit section information for extern variables.
3165 if (D->hasExternalStorage()) {
3166 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3167 GV->setSection(SA->getName());
3168 }
3169
Robert Lyttonf80d6882014-05-02 09:33:30 +00003170 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003171 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00003172 D->getLanguageLinkage() == CLanguageLinkage &&
3173 D->getType().isConstant(Context) &&
3174 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3175 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003176
3177 // Check if we a have a const declaration with an initializer, we may be
3178 // able to emit it as available_externally to expose it's value to the
3179 // optimizer.
3180 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3181 D->getType().isConstQualified() && !GV->hasInitializer() &&
3182 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3183 const auto *Record =
3184 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3185 bool HasMutableFields = Record && Record->hasMutableFields();
3186 if (!HasMutableFields) {
3187 const VarDecl *InitDecl;
3188 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3189 if (InitExpr) {
3190 ConstantEmitter emitter(*this);
3191 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3192 if (Init) {
3193 auto *InitType = Init->getType();
3194 if (GV->getType()->getElementType() != InitType) {
3195 // The type of the initializer does not match the definition.
3196 // This happens when an initializer has a different type from
3197 // the type of the global (because of padding at the end of a
3198 // structure for instance).
3199 GV->setName(StringRef());
3200 // Make a new global with the correct type, this is now guaranteed
3201 // to work.
3202 auto *NewGV = cast<llvm::GlobalVariable>(
3203 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3204
3205 // Erase the old global, since it is no longer used.
George Burgess IV00f70bd2018-03-01 05:43:23 +00003206 GV->eraseFromParent();
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003207 GV = NewGV;
3208 } else {
3209 GV->setInitializer(Init);
3210 GV->setConstant(true);
3211 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3212 }
3213 emitter.finalize(GV);
3214 }
3215 }
3216 }
3217 }
Chris Lattnerd4808922009-03-22 21:03:39 +00003218 }
Mike Stump11289f42009-09-09 15:08:12 +00003219
Alexander Richardson6d989432017-10-15 18:48:14 +00003220 LangAS ExpectedAS =
Yaxun Liucbf647c2017-07-08 13:24:52 +00003221 D ? D->getType().getAddressSpace()
Alexander Richardson6d989432017-10-15 18:48:14 +00003222 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00003223 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3224 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00003225 if (AddrSpace != ExpectedAS)
3226 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3227 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00003228
Scott Linder80a1ee42019-02-12 18:30:38 +00003229 if (GV->isDeclaration())
3230 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3231
Matt Arsenault00e65b22013-11-15 02:19:52 +00003232 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00003233}
3234
Andrey Bokhankocab58582015-08-31 13:20:44 +00003235llvm::Constant *
3236CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00003237 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003238 const Decl *D = GD.getDecl();
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003239 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3240 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
Andrey Bokhankocab58582015-08-31 13:20:44 +00003241 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003242 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003243 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003244 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00003245 auto Ty = getTypes().GetFunctionType(*FInfo);
3246 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3247 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003248 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003249 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3250 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3251 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3252 IsForDefinition);
3253 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003254 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003255 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003256}
Chris Lattnerd4808922009-03-22 21:03:39 +00003257
David Greenbe0c5b62018-09-12 14:09:06 +00003258llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3259 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3260 unsigned Alignment) {
Anders Carlssonda80af32011-01-29 18:20:20 +00003261 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00003262 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00003263
Anders Carlssonda80af32011-01-29 18:20:20 +00003264 if (GV) {
3265 // Check if the variable has the right type.
3266 if (GV->getType()->getElementType() == Ty)
3267 return GV;
3268
3269 // Because C++ name mangling, the only way we can end up with an already
3270 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00003271 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00003272 OldGV = GV;
3273 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003274
Anders Carlssonda80af32011-01-29 18:20:20 +00003275 // Create a new variable.
3276 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00003277 Linkage, nullptr, Name);
3278
Anders Carlssonda80af32011-01-29 18:20:20 +00003279 if (OldGV) {
3280 // Replace occurrences of the old variable if needed.
3281 GV->takeName(OldGV);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003282
Anders Carlssonda80af32011-01-29 18:20:20 +00003283 if (!OldGV->use_empty()) {
3284 llvm::Constant *NewPtrForOldDecl =
3285 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3286 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3287 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003288
Anders Carlssonda80af32011-01-29 18:20:20 +00003289 OldGV->eraseFromParent();
3290 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00003291
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003292 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3293 !GV->hasAvailableExternallyLinkage())
3294 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00003295
David Greenbe0c5b62018-09-12 14:09:06 +00003296 GV->setAlignment(Alignment);
3297
Anders Carlssonda80af32011-01-29 18:20:20 +00003298 return GV;
3299}
3300
Chris Lattnerd4808922009-03-22 21:03:39 +00003301/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3302/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00003303/// then it will be created with the specified type instead of whatever the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003304/// normal requested type would be. If IsForDefinition is true, it is guaranteed
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003305/// that an actual global with type Ty will be returned, not conversion of a
3306/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00003307llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003308 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00003309 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00003310 assert(D->hasGlobalStorage() && "Not a global variable");
3311 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00003312 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00003313 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00003314
Chris Lattner2192fe52011-07-18 04:24:23 +00003315 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003316 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00003317
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003318 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003319 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00003320}
3321
3322/// CreateRuntimeVariable - Create a new runtime global variable with the
3323/// specified type and name.
3324llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00003325CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003326 StringRef Name) {
Rafael Espindola6ab4ae42018-03-21 01:30:16 +00003327 auto *Ret =
3328 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3329 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3330 return Ret;
Chris Lattnerd4808922009-03-22 21:03:39 +00003331}
3332
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003333void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3334 assert(!D->getInit() && "Cannot emit definite definitions here!");
3335
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003336 StringRef MangledName = getMangledName(D);
3337 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3338
3339 // We already have a definition, not declaration, with the same mangled name.
3340 // Emitting of declaration is not required (and actually overwrites emitted
3341 // definition).
3342 if (GV && !GV->isDeclaration())
3343 return;
3344
3345 // If we have not seen a reference to this variable yet, place it into the
3346 // deferred declarations table to be emitted if needed later.
3347 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003348 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003349 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00003350 }
3351
3352 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00003353 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003354}
3355
Chris Lattner2192fe52011-07-18 04:24:23 +00003356CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00003357 return Context.toCharUnitsFromBits(
3358 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00003359}
3360
Alexander Richardson6d989432017-10-15 18:48:14 +00003361LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3362 LangAS AddrSpace = LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003363 if (LangOpts.OpenCL) {
Alexander Richardson6d989432017-10-15 18:48:14 +00003364 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003365 assert(AddrSpace == LangAS::opencl_global ||
3366 AddrSpace == LangAS::opencl_constant ||
3367 AddrSpace == LangAS::opencl_local ||
3368 AddrSpace >= LangAS::FirstTargetAddressSpace);
3369 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003370 }
3371
Yaxun Liucbf647c2017-07-08 13:24:52 +00003372 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3373 if (D && D->hasAttr<CUDAConstantAttr>())
3374 return LangAS::cuda_constant;
3375 else if (D && D->hasAttr<CUDASharedAttr>())
3376 return LangAS::cuda_shared;
Yaxun Liua4005e12018-07-28 03:05:25 +00003377 else if (D && D->hasAttr<CUDADeviceAttr>())
3378 return LangAS::cuda_device;
3379 else if (D && D->getType().isConstQualified())
3380 return LangAS::cuda_constant;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003381 else
3382 return LangAS::cuda_device;
3383 }
3384
Alexey Bataevc5687252019-03-21 19:35:27 +00003385 if (LangOpts.OpenMP) {
3386 LangAS AS;
3387 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3388 return AS;
3389 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00003390 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003391}
3392
Yaxun Liudaceb1e2018-05-14 19:20:12 +00003393LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3394 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3395 if (LangOpts.OpenCL)
3396 return LangAS::opencl_constant;
3397 if (auto AS = getTarget().getConstantAddressSpace())
3398 return AS.getValue();
3399 return LangAS::Default;
3400}
3401
3402// In address space agnostic languages, string literals are in default address
3403// space in AST. However, certain targets (e.g. amdgcn) request them to be
3404// emitted in constant address space in LLVM IR. To be consistent with other
3405// parts of AST, string literal global variables in constant address space
3406// need to be casted to default address space before being put into address
3407// map and referenced by other part of CodeGen.
3408// In OpenCL, string literals are in constant address space in AST, therefore
3409// they should not be casted to default address space.
3410static llvm::Constant *
3411castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3412 llvm::GlobalVariable *GV) {
3413 llvm::Constant *Cast = GV;
3414 if (!CGM.getLangOpts().OpenCL) {
3415 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3416 if (AS != LangAS::Default)
3417 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3418 CGM, GV, AS.getValue(), LangAS::Default,
3419 GV->getValueType()->getPointerTo(
3420 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3421 }
3422 }
3423 return Cast;
3424}
3425
Richard Smithdf931ce2013-04-06 05:00:46 +00003426template<typename SomeDecl>
3427void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3428 llvm::GlobalValue *GV) {
3429 if (!getLangOpts().CPlusPlus)
3430 return;
3431
3432 // Must have 'used' attribute, or else inline assembly can't rely on
3433 // the name existing.
3434 if (!D->template hasAttr<UsedAttr>())
3435 return;
3436
3437 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00003438 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00003439 return;
3440
3441 // Must be in an extern "C" context. Entities declared directly within
3442 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003443 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00003444 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00003445 return;
3446
3447 // OK, this is an internal linkage entity inside an extern "C" linkage
3448 // specification. Make a note of that so we can give it the "expected"
3449 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00003450 std::pair<StaticExternCMap::iterator, bool> R =
3451 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00003452
3453 // If we have multiple internal linkage entities with the same name
3454 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00003455 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00003456 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00003457}
3458
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003459static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3460 if (!CGM.supportsCOMDAT())
3461 return false;
3462
3463 if (D.hasAttr<SelectAnyAttr>())
3464 return true;
3465
3466 GVALinkage Linkage;
3467 if (auto *VD = dyn_cast<VarDecl>(&D))
3468 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3469 else
3470 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3471
3472 switch (Linkage) {
3473 case GVA_Internal:
3474 case GVA_AvailableExternally:
3475 case GVA_StrongExternal:
3476 return false;
3477 case GVA_DiscardableODR:
3478 case GVA_StrongODR:
3479 return true;
3480 }
3481 llvm_unreachable("No such linkage");
3482}
3483
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003484void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3485 llvm::GlobalObject &GO) {
3486 if (!shouldBeInCOMDAT(*this, D))
3487 return;
3488 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3489}
3490
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003491/// Pass IsTentative as true if you want to create a tentative definition.
3492void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3493 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003494 // OpenCL global variables of sampler type are translated to function calls,
3495 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003496 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003497 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3498 return;
3499
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003500 // If this is OpenMP device, check if it is legal to emit this global
3501 // normally.
3502 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3503 OpenMPRuntime->emitTargetGlobalVariable(D))
3504 return;
3505
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003506 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00003507 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3508 bool NeedsGlobalCtor = false;
3509 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00003510
Richard Smithdafff942012-01-14 04:30:29 +00003511 const VarDecl *InitDecl;
3512 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003513
John McCallde0fe072017-08-15 21:42:52 +00003514 Optional<ConstantEmitter> emitter;
3515
Artem Belevich97c01c32016-02-02 22:29:48 +00003516 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3517 // as part of their declaration." Sema has already checked for
3518 // error cases, so we just need to set Init to UndefValue.
Artem Belevich7b056662018-12-13 21:43:04 +00003519 bool IsCUDASharedVar =
3520 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3521 // Shadows of initialized device-side global variables are also left
3522 // undefined.
3523 bool IsCUDAShadowVar =
3524 !getLangOpts().CUDAIsDevice &&
3525 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3526 D->hasAttr<CUDASharedAttr>());
3527 if (getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar))
Jingyue Wu284ebe22015-08-22 05:49:28 +00003528 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00003529 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00003530 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003531 // implicitly initialized with { 0 }.
3532 //
3533 // Note that tentative definitions are only emitted at the end of
3534 // a translation unit, so they should never have incomplete
3535 // type. In addition, EmitTentativeDefinition makes sure that we
3536 // never attempt to emit a tentative definition if a real one
3537 // exists. A use may still exists, however, so we still may need
3538 // to do a RAUW.
3539 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00003540 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003541 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003542 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00003543 emitter.emplace(*this);
3544 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003545
Fariborz Jahanian63628032012-06-26 16:06:38 +00003546 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00003547 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00003548 if (D->getType()->isReferenceType())
3549 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00003550
David Blaikiebbafb8a2012-03-11 07:00:24 +00003551 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003552 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00003553 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003554 } else {
3555 ErrorUnsupported(D, "static initializer");
3556 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3557 }
John McCall70013b62010-07-15 23:40:35 +00003558 } else {
3559 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00003560 // initializer position (just in case this entry was delayed) if we
3561 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003562 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00003563 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00003564 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003565 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003566
Chris Lattner2192fe52011-07-18 04:24:23 +00003567 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003568 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00003569 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00003570
Chris Lattner149927c2009-03-21 09:16:30 +00003571 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003572 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00003573 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00003574 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3575 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00003576 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00003577 Entry = CE->getOperand(0);
3578 }
Mike Stump11289f42009-09-09 15:08:12 +00003579
Chris Lattner149927c2009-03-21 09:16:30 +00003580 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003581 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003582
Chris Lattner149927c2009-03-21 09:16:30 +00003583 // We have a definition after a declaration with the wrong type.
3584 // We must make a new GlobalVariable* and update everything that used OldGV
3585 // (a declaration or tentative definition) with the new GlobalVariable*
3586 // (which will be a definition).
3587 //
3588 // This happens if there is a prototype for a global (e.g.
3589 // "extern int x[];") and then a definition of a different type (e.g.
3590 // "int x[10];"). This also happens when an initializer has a different type
3591 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00003592 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003593 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00003594 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00003595
John McCall7ec50432010-03-19 23:29:14 +00003596 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003597 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00003598
Chris Lattner149927c2009-03-21 09:16:30 +00003599 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003600 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00003601 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00003602
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003603 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00003604 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00003605 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00003606 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003607
3608 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00003609 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00003610 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00003611
Richard Smithdf931ce2013-04-06 05:00:46 +00003612 MaybeHandleStaticInExternC(D, GV);
3613
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003614 if (D->hasAttr<AnnotateAttr>())
3615 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00003616
Artem Belevich42e19492016-03-02 18:28:50 +00003617 // Set the llvm linkage type as appropriate.
3618 llvm::GlobalValue::LinkageTypes Linkage =
3619 getLLVMLinkageVarDefinition(D, GV->isConstant());
3620
Jingyue Wu284ebe22015-08-22 05:49:28 +00003621 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3622 // the device. [...]"
3623 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3624 // __device__, declares a variable that: [...]
3625 // Is accessible from all the threads within the grid and from the host
3626 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3627 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00003628 if (GV && LangOpts.CUDA) {
3629 if (LangOpts.CUDAIsDevice) {
3630 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3631 GV->setExternallyInitialized(true);
3632 } else {
3633 // Host-side shadows of external declarations of device-side
3634 // global variables become internal definitions. These have to
3635 // be internal in order to prevent name conflicts with global
3636 // host variables with the same name in a different TUs.
3637 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3638 Linkage = llvm::GlobalValue::InternalLinkage;
3639
3640 // Shadow variables and their properties must be registered
3641 // with CUDA runtime.
3642 unsigned Flags = 0;
3643 if (!D->hasDefinition())
3644 Flags |= CGCUDARuntime::ExternDeviceVar;
3645 if (D->hasAttr<CUDAConstantAttr>())
3646 Flags |= CGCUDARuntime::ConstantDeviceVar;
Artem Belevich99535772018-12-22 01:11:09 +00003647 // Extern global variables will be registered in the TU where they are
3648 // defined.
3649 if (!D->hasExternalStorage())
Yaxun Liuc18e9ec2019-02-14 02:00:09 +00003650 getCUDARuntime().registerDeviceVar(D, *GV, Flags);
Artem Belevich42e19492016-03-02 18:28:50 +00003651 } else if (D->hasAttr<CUDASharedAttr>())
3652 // __shared__ variables are odd. Shadows do get created, but
3653 // they are not registered with the CUDA runtime, so they
3654 // can't really be used to access their device-side
3655 // counterparts. It's not clear yet whether it's nvcc's bug or
3656 // a feature, but we've got to do the same for compatibility.
3657 Linkage = llvm::GlobalValue::InternalLinkage;
3658 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00003659 }
John McCallde0fe072017-08-15 21:42:52 +00003660
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003661 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00003662 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00003663
3664 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00003665 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3666 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00003667
Hans Wennborg899ded92014-10-16 20:52:46 +00003668 // If it is in a read-only section, mark it 'constant'.
3669 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3670 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3671 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3672 GV->setConstant(true);
3673 }
3674
Ken Dyck160146e2010-01-27 17:10:57 +00003675 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00003676
David Majnemer35ab3282014-06-11 04:08:55 +00003677
Manman Ren68150262015-11-11 22:42:31 +00003678 // On Darwin, if the normal linkage of a C++ thread_local variable is
3679 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3680 // copies within a linkage unit; otherwise, the backing variable has
3681 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00003682 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00003683 // variable. This is to preserve the ability to change the implementation
3684 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00003685 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00003686 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00003687 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3688 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00003689 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00003690
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003691 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00003692 if (D->hasAttr<DLLImportAttr>())
3693 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3694 else if (D->hasAttr<DLLExportAttr>())
3695 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00003696 else
3697 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00003698
Yaxun Liu402804b2016-12-15 08:09:08 +00003699 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00003700 // common vars aren't constant even if declared const.
3701 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00003702 // Tentative definition of global variables may be initialized with
3703 // non-zero null pointers. In this case they should have weak linkage
3704 // since common linkage must have zero initializer and must not have
3705 // explicit section therefore cannot have non-zero initial value.
3706 if (!GV->getInitializer()->isNullValue())
3707 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3708 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00003709
Rafael Espindola502f65a2014-05-05 20:21:03 +00003710 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00003711
David Majnemerbb525f7c2014-10-15 22:38:23 +00003712 if (D->getTLSKind() && !GV->isThreadLocal()) {
3713 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003714 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00003715 setTLSMode(GV, *D);
3716 }
3717
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003718 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003719
John McCallcdf7ef52010-11-06 09:44:32 +00003720 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00003721 if (NeedsGlobalCtor || NeedsGlobalDtor)
3722 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00003723
Alexey Samsonov4b8de112014-08-01 21:35:28 +00003724 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00003725
Sanjiv Gupta158143a2008-06-05 08:59:10 +00003726 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00003727 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003728 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00003729 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003730}
Chris Lattner09153c02007-06-22 18:48:09 +00003731
David Majnemerc017d362014-08-05 00:01:13 +00003732static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00003733 CodeGenModule &CGM, const VarDecl *D,
3734 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00003735 // Don't give variables common linkage if -fno-common was specified unless it
3736 // was overridden by a NoCommon attribute.
3737 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3738 return true;
3739
3740 // C11 6.9.2/2:
3741 // A declaration of an identifier for an object that has file scope without
3742 // an initializer, and without a storage-class specifier or with the
3743 // storage-class specifier static, constitutes a tentative definition.
3744 if (D->getInit() || D->hasExternalStorage())
3745 return true;
3746
3747 // A variable cannot be both common and exist in a section.
3748 if (D->hasAttr<SectionAttr>())
3749 return true;
3750
Javed Absar2a67c9e2017-06-05 10:11:57 +00003751 // A variable cannot be both common and exist in a section.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003752 // We don't try to determine which is the right section in the front-end.
Javed Absar2a67c9e2017-06-05 10:11:57 +00003753 // If no specialized section name is applicable, it will resort to default.
3754 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3755 D->hasAttr<PragmaClangDataSectionAttr>() ||
3756 D->hasAttr<PragmaClangRodataSectionAttr>())
3757 return true;
3758
David Majnemer9832a3d2014-04-10 16:53:16 +00003759 // Thread local vars aren't considered common linkage.
3760 if (D->getTLSKind())
3761 return true;
3762
3763 // Tentative definitions marked with WeakImportAttr are true definitions.
3764 if (D->hasAttr<WeakImportAttr>())
3765 return true;
3766
Nico Weber608e7682015-04-15 23:04:24 +00003767 // A variable cannot be both common and exist in a comdat.
3768 if (shouldBeInCOMDAT(CGM, *D))
3769 return true;
3770
Sanjay Patel2f9303a2016-06-30 21:02:40 +00003771 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00003772 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00003773 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00003774 if (D->hasAttr<AlignedAttr>())
3775 return true;
3776 QualType VarType = D->getType();
3777 if (Context.isAlignmentRequired(VarType))
3778 return true;
3779
3780 if (const auto *RT = VarType->getAs<RecordType>()) {
3781 const RecordDecl *RD = RT->getDecl();
3782 for (const FieldDecl *FD : RD->fields()) {
3783 if (FD->isBitField())
3784 continue;
3785 if (FD->hasAttr<AlignedAttr>())
3786 return true;
3787 if (Context.isAlignmentRequired(FD->getType()))
3788 return true;
3789 }
3790 }
3791 }
Shoaib Meenai39287e72019-01-09 20:05:16 +00003792
Erich Keane892e6332019-02-07 15:14:11 +00003793 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
3794 // common symbols, so symbols with greater alignment requirements cannot be
3795 // common.
Shoaib Meenai39287e72019-01-09 20:05:16 +00003796 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
3797 // alignments for common symbols via the aligncomm directive, so this
3798 // restriction only applies to MSVC environments.
Erich Keane85c62242019-01-08 18:44:22 +00003799 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
Erich Keane892e6332019-02-07 15:14:11 +00003800 Context.getTypeAlignIfKnown(D->getType()) >
3801 Context.toBits(CharUnits::fromQuantity(32)))
Erich Keane85c62242019-01-08 18:44:22 +00003802 return true;
David Majnemerc017d362014-08-05 00:01:13 +00003803
David Majnemer9832a3d2014-04-10 16:53:16 +00003804 return false;
3805}
3806
Hans Wennborg1a3a0742014-05-14 19:54:53 +00003807llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00003808 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003809 if (Linkage == GVA_Internal)
3810 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003811
3812 if (D->hasAttr<WeakAttr>()) {
3813 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003814 return llvm::GlobalVariable::WeakODRLinkage;
3815 else
3816 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003817 }
3818
Erich Keane7ef210d2018-10-22 21:20:45 +00003819 if (const auto *FD = D->getAsFunction())
3820 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
3821 return llvm::GlobalVariable::LinkOnceAnyLinkage;
3822
David Majnemer27d69db2014-04-28 22:17:59 +00003823 // We are guaranteed to have a strong definition somewhere else,
3824 // so we can use available_externally linkage.
3825 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003826 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003827
David Majnemer27d69db2014-04-28 22:17:59 +00003828 // Note that Apple's kernel linker doesn't support symbol
3829 // coalescing, so we need to avoid linkonce and weak linkages there.
3830 // Normally, this means we just map to internal, but for explicit
3831 // instantiations we'll map to external.
3832
3833 // In C++, the compiler has to emit a definition in every translation unit
3834 // that references the function. We should use linkonce_odr because
3835 // a) if all references in this translation unit are optimized away, we
3836 // don't need to codegen it. b) if the function persists, it needs to be
3837 // merged with other definitions. c) C++ has the ODR, so we know the
3838 // definition is dependable.
3839 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00003840 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00003841 : llvm::Function::InternalLinkage;
3842
3843 // An explicit instantiation of a template has weak linkage, since
3844 // explicit instantiations can occur in multiple translation units
3845 // and must all be equivalent. However, we are not allowed to
3846 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00003847 //
3848 // We don't currently support CUDA device code spread out across multiple TUs,
3849 // so say that CUDA templates are either external (for kernels) or internal.
3850 // This lets llvm perform aggressive inter-procedural optimizations.
3851 if (Linkage == GVA_StrongODR) {
3852 if (Context.getLangOpts().AppleKext)
3853 return llvm::Function::ExternalLinkage;
3854 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3855 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3856 : llvm::Function::InternalLinkage;
3857 return llvm::Function::WeakODRLinkage;
3858 }
David Majnemer27d69db2014-04-28 22:17:59 +00003859
David Majnemer27d69db2014-04-28 22:17:59 +00003860 // C++ doesn't have tentative definitions and thus cannot have common
3861 // linkage.
3862 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00003863 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00003864 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00003865 return llvm::GlobalVariable::CommonLinkage;
3866
David Majnemer27d69db2014-04-28 22:17:59 +00003867 // selectany symbols are externally visible, so use weak instead of
3868 // linkonce. MSVC optimizes away references to const selectany globals, so
3869 // all definitions should be the same and ODR linkage should be used.
3870 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3871 if (D->hasAttr<SelectAnyAttr>())
3872 return llvm::GlobalVariable::WeakODRLinkage;
3873
3874 // Otherwise, we have strong external linkage.
3875 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003876 return llvm::GlobalVariable::ExternalLinkage;
3877}
3878
David Majnemer27d69db2014-04-28 22:17:59 +00003879llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3880 const VarDecl *VD, bool IsConstant) {
3881 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00003882 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00003883}
3884
John McCall49954ca2012-12-12 22:21:47 +00003885/// Replace the uses of a function that was declared with a non-proto type.
3886/// We want to silently drop extra arguments from call sites
3887static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3888 llvm::Function *newFn) {
3889 // Fast path.
3890 if (old->use_empty()) return;
3891
3892 llvm::Type *newRetTy = newFn->getReturnType();
3893 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00003894 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00003895
3896 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3897 ui != ue; ) {
3898 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003899 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00003900
3901 // Recognize and replace uses of bitcasts. Most calls to
3902 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003903 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00003904 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3905 replaceUsesOfNonProtoConstant(bitcast, newFn);
3906 continue;
3907 }
3908
3909 // Recognize calls to the function.
James Y Knight3933add2019-01-30 02:54:28 +00003910 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
John McCall49954ca2012-12-12 22:21:47 +00003911 if (!callSite) continue;
James Y Knight3933add2019-01-30 02:54:28 +00003912 if (!callSite->isCallee(&*use))
3913 continue;
John McCall49954ca2012-12-12 22:21:47 +00003914
3915 // If the return types don't match exactly, then we can't
3916 // transform this call unless it's dead.
3917 if (callSite->getType() != newRetTy && !callSite->use_empty())
3918 continue;
3919
3920 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00003921 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
James Y Knight3933add2019-01-30 02:54:28 +00003922 llvm::AttributeList oldAttrs = callSite->getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00003923
John McCall49954ca2012-12-12 22:21:47 +00003924 // If the function was passed too few arguments, don't transform.
3925 unsigned newNumArgs = newFn->arg_size();
James Y Knight3933add2019-01-30 02:54:28 +00003926 if (callSite->arg_size() < newNumArgs)
3927 continue;
John McCall49954ca2012-12-12 22:21:47 +00003928
3929 // If extra arguments were passed, we silently drop them.
3930 // If any of the types mismatch, we don't transform.
3931 unsigned argNo = 0;
3932 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00003933 for (llvm::Argument &A : newFn->args()) {
James Y Knight3933add2019-01-30 02:54:28 +00003934 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00003935 dontTransform = true;
3936 break;
3937 }
3938
3939 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00003940 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00003941 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00003942 }
3943 if (dontTransform)
3944 continue;
3945
John McCall49954ca2012-12-12 22:21:47 +00003946 // Okay, we can transform this. Create the new call instruction and copy
3947 // over the required information.
James Y Knight3933add2019-01-30 02:54:28 +00003948 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
John McCall49954ca2012-12-12 22:21:47 +00003949
David Majnemer0b17d442015-12-15 21:27:59 +00003950 // Copy over any operand bundles.
James Y Knight3933add2019-01-30 02:54:28 +00003951 callSite->getOperandBundlesAsDefs(newBundles);
David Majnemer0b17d442015-12-15 21:27:59 +00003952
James Y Knight3933add2019-01-30 02:54:28 +00003953 llvm::CallBase *newCall;
3954 if (dyn_cast<llvm::CallInst>(callSite)) {
3955 newCall =
3956 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
John McCall49954ca2012-12-12 22:21:47 +00003957 } else {
James Y Knight3933add2019-01-30 02:54:28 +00003958 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
3959 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
3960 oldInvoke->getUnwindDest(), newArgs,
3961 newBundles, "", callSite);
John McCall49954ca2012-12-12 22:21:47 +00003962 }
3963 newArgs.clear(); // for the next iteration
3964
3965 if (!newCall->getType()->isVoidTy())
James Y Knight3933add2019-01-30 02:54:28 +00003966 newCall->takeName(callSite);
3967 newCall->setAttributes(llvm::AttributeList::get(
Reid Kleckner7f720332017-04-13 00:58:09 +00003968 newFn->getContext(), oldAttrs.getFnAttributes(),
3969 oldAttrs.getRetAttributes(), newArgAttrs));
James Y Knight3933add2019-01-30 02:54:28 +00003970 newCall->setCallingConv(callSite->getCallingConv());
John McCall49954ca2012-12-12 22:21:47 +00003971
3972 // Finally, remove the old call, replacing any uses with the new one.
3973 if (!callSite->use_empty())
James Y Knight3933add2019-01-30 02:54:28 +00003974 callSite->replaceAllUsesWith(newCall);
John McCall49954ca2012-12-12 22:21:47 +00003975
3976 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003977 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003978 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003979
John McCall49954ca2012-12-12 22:21:47 +00003980 callSite->eraseFromParent();
3981 }
3982}
3983
Chris Lattner36797ab2009-05-05 06:16:31 +00003984/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3985/// implement a function with no prototype, e.g. "int foo() {}". If there are
3986/// existing call uses of the old function in the module, this adjusts them to
3987/// call the new function directly.
3988///
3989/// This is not just a cleanup: the always_inline pass requires direct calls to
3990/// functions to be able to inline them. If there is a bitcast in the way, it
3991/// won't inline them. Instcombine normally deletes these calls, but it isn't
3992/// run at -O0.
3993static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3994 llvm::Function *NewFn) {
3995 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003996 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003997
John McCall49954ca2012-12-12 22:21:47 +00003998 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003999}
4000
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004001void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00004002 auto DK = VD->isThisDeclarationADefinition();
4003 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4004 return;
4005
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004006 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4007 // If we have a definition, this might be a deferred decl. If the
4008 // instantiation is explicit, make sure we emit it at the end.
4009 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4010 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004011
4012 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00004013}
Daniel Dunbar9c426522008-07-29 23:18:29 +00004014
Rafael Espindolacd7743b2013-12-09 16:01:03 +00004015void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4016 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004017 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00004018
John McCall46288ef2011-03-09 08:12:35 +00004019 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00004020 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4021 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00004022
Chris Lattnereb7466d2009-05-12 20:58:15 +00004023 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00004024 if (!GV || (GV->getType()->getElementType() != Ty))
4025 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4026 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00004027 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00004028
Andrey Bokhankocab58582015-08-31 13:20:44 +00004029 // Already emitted.
4030 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00004031 return;
Mike Stump11289f42009-09-09 15:08:12 +00004032
John McCall8e7cb6d2010-11-02 21:04:24 +00004033 // We need to set linkage and visibility on the function before
4034 // generating code for it because various parts of IR generation
4035 // want to propagate this information down (e.g. to local static
4036 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004037 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00004038 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00004039
Rafael Espindolae033c8c2014-05-08 15:26:12 +00004040 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Rafael Espindolab7350042018-03-01 00:35:47 +00004041 setGVProperties(Fn, GD);
John McCall8e7cb6d2010-11-02 21:04:24 +00004042
Richard Smithdf931ce2013-04-06 05:00:46 +00004043 MaybeHandleStaticInExternC(D, Fn);
4044
Yaxun Liu4306f202018-04-20 17:01:03 +00004045
Rafael Espindoladbee8a72015-01-15 21:36:08 +00004046 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00004047
John McCalla738c252011-03-09 04:27:21 +00004048 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00004049
Rafael Espindolae4e78132018-03-01 00:00:02 +00004050 setNonAliasAttributes(GD, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00004051 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00004052
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004053 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00004054 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004055 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00004056 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00004057 if (D->hasAttr<AnnotateAttr>())
4058 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00004059}
4060
John McCall7ec50432010-03-19 23:29:14 +00004061void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004062 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004063 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00004064 assert(AA && "Not an alias?");
4065
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004066 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00004067
Hal Finkel0e2b9752015-09-04 21:49:21 +00004068 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004069 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00004070 return;
4071 }
4072
John McCall7ec50432010-03-19 23:29:14 +00004073 // If there is a definition in the module, then it wins over the alias.
4074 // This is dubious, but allow it to be safe. Just ignore the alias.
4075 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4076 if (Entry && !Entry->isDeclaration())
4077 return;
4078
Rafael Espindola208b5c02013-10-22 19:26:13 +00004079 Aliases.push_back(GD);
4080
Chris Lattner2192fe52011-07-18 04:24:23 +00004081 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00004082
4083 // Create a reference to the named value. This ensures that it is emitted
4084 // if a deferred decl.
4085 llvm::Constant *Aliasee;
4086 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00004087 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00004088 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00004089 else
John McCall7ec50432010-03-19 23:29:14 +00004090 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00004091 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00004092 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00004093
4094 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00004095 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00004096 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00004097
Chris Lattner54041692009-03-22 21:47:11 +00004098 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00004099 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004100 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00004101 return;
4102 }
4103
John McCall7ec50432010-03-19 23:29:14 +00004104 assert(Entry->isDeclaration());
4105
Chris Lattner54041692009-03-22 21:47:11 +00004106 // If there is a declaration in the module, then we had an extern followed
4107 // by the alias, as in:
4108 // extern int test6();
4109 // ...
4110 // int test6() __attribute__((alias("test7")));
4111 //
4112 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00004113 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00004114
Owen Andersonade90fd2009-07-29 18:54:39 +00004115 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00004116 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00004117 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00004118 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00004119 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00004120 }
Mike Stump11289f42009-09-09 15:08:12 +00004121
Daniel Dunbar38932572009-04-14 08:05:55 +00004122 // Set attributes which are particular to an alias; this is a
4123 // specialization of the attributes which may be set on a global
4124 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00004125 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4126 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00004127 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4128 }
4129
David Majnemerbb525f7c2014-10-15 22:38:23 +00004130 if (const auto *VD = dyn_cast<VarDecl>(D))
4131 if (VD->getTLSKind())
4132 setTLSMode(GA, *VD);
4133
Rafael Espindolab7350042018-03-01 00:35:47 +00004134 SetCommonAttributes(GD, GA);
Chris Lattner54041692009-03-22 21:47:11 +00004135}
4136
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004137void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4138 const auto *D = cast<ValueDecl>(GD.getDecl());
4139 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4140 assert(IFA && "Not an ifunc?");
4141
4142 StringRef MangledName = getMangledName(GD);
4143
4144 if (IFA->getResolver() == MangledName) {
4145 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4146 return;
4147 }
4148
4149 // Report an error if some definition overrides ifunc.
4150 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4151 if (Entry && !Entry->isDeclaration()) {
4152 GlobalDecl OtherGD;
4153 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4154 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00004155 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4156 << MangledName;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004157 Diags.Report(OtherGD.getDecl()->getLocation(),
4158 diag::note_previous_definition);
4159 }
4160 return;
4161 }
4162
4163 Aliases.push_back(GD);
4164
4165 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4166 llvm::Constant *Resolver =
4167 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4168 /*ForVTable=*/false);
4169 llvm::GlobalIFunc *GIF =
4170 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4171 "", Resolver, &getModule());
4172 if (Entry) {
4173 if (GIF->getResolver() == Entry) {
4174 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4175 return;
4176 }
4177 assert(Entry->isDeclaration());
4178
4179 // If there is a declaration in the module, then we had an extern followed
4180 // by the ifunc, as in:
4181 // extern int test();
4182 // ...
4183 // int test() __attribute__((ifunc("resolver")));
4184 //
4185 // Remove it and replace uses of it with the ifunc.
4186 GIF->takeName(Entry);
4187
4188 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4189 Entry->getType()));
4190 Entry->eraseFromParent();
4191 } else
4192 GIF->setName(MangledName);
4193
Rafael Espindola75c649c2018-03-01 00:06:55 +00004194 SetCommonAttributes(GD, GIF);
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004195}
4196
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004197llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00004198 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00004199 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004200 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00004201}
Chris Lattner1eec6602007-08-31 04:31:45 +00004202
David Blaikie2e804282015-04-05 22:47:07 +00004203static llvm::StringMapEntry<llvm::GlobalVariable *> &
4204GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4205 const StringLiteral *Literal, bool TargetIsLSB,
4206 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004207 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004208 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00004209
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004210 // Check for simple case.
4211 if (!Literal->containsNonAsciiOrNull()) {
4212 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00004213 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004214 }
4215
Bill Wendling82b87f12012-03-30 00:26:17 +00004216 // Otherwise, convert the UTF8 literals into a string of shorts.
4217 IsUTF16 = true;
4218
Justin Lebar90910552016-09-30 00:38:45 +00004219 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4220 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4221 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00004222
Justin Lebar90910552016-09-30 00:38:45 +00004223 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4224 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00004225
Daniel Dunbar91ade142009-07-23 23:41:22 +00004226 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00004227 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00004228
Bill Wendling82b87f12012-03-30 00:26:17 +00004229 // Add an explicit null.
4230 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00004231 return *Map.insert(std::make_pair(
4232 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4233 (StringLength + 1) * 2),
4234 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00004235}
4236
John McCall7f416cc2015-09-08 08:05:57 +00004237ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00004238CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4239 unsigned StringLength = 0;
4240 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00004241 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4242 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4243 getDataLayout().isLittleEndian(), isUTF16,
4244 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004245
David Blaikie13156b62014-11-19 03:06:06 +00004246 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00004247 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00004248
Chris Lattnerece04092012-02-07 00:39:47 +00004249 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00004250 llvm::Constant *Zeros[] = { Zero, Zero };
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004251
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004252 const ASTContext &Context = getContext();
4253 const llvm::Triple &Triple = getTriple();
4254
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004255 const auto CFRuntime = getLangOpts().CFRuntime;
4256 const bool IsSwiftABI =
4257 static_cast<unsigned>(CFRuntime) >=
4258 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4259 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4260
Chris Lattneraa64ca22009-07-16 16:48:25 +00004261 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00004262 if (!CFConstantStringClassRef) {
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004263 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00004264 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00004265 Ty = llvm::ArrayType::get(Ty, 0);
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004266
4267 switch (CFRuntime) {
4268 default: break;
4269 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
Saleem Abdulrasool0c16a132018-10-25 17:52:13 +00004270 case LangOptions::CoreFoundationABI::Swift5_0:
4271 CFConstantStringClassName =
Saleem Abdulrasool98ac9982018-10-26 03:16:16 +00004272 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4273 : "$s10Foundation19_NSCFConstantStringCN";
Saleem Abdulrasool0c16a132018-10-25 17:52:13 +00004274 Ty = IntPtrTy;
4275 break;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004276 case LangOptions::CoreFoundationABI::Swift4_2:
4277 CFConstantStringClassName =
Saleem Abdulrasool98ac9982018-10-26 03:16:16 +00004278 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4279 : "$S10Foundation19_NSCFConstantStringCN";
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004280 Ty = IntPtrTy;
4281 break;
4282 case LangOptions::CoreFoundationABI::Swift4_1:
4283 CFConstantStringClassName =
4284 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4285 : "__T010Foundation19_NSCFConstantStringCN";
4286 Ty = IntPtrTy;
4287 break;
4288 }
4289
4290 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004291
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004292 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
Kristina Brooks34e24d52018-09-25 22:27:40 +00004293 llvm::GlobalValue *GV = nullptr;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004294
Kristina Brooks34e24d52018-09-25 22:27:40 +00004295 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004296 IdentifierInfo &II = Context.Idents.get(GV->getName());
4297 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
Kristina Brooks34e24d52018-09-25 22:27:40 +00004298 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004299
Kristina Brooks34e24d52018-09-25 22:27:40 +00004300 const VarDecl *VD = nullptr;
4301 for (const auto &Result : DC->lookup(&II))
4302 if ((VD = dyn_cast<VarDecl>(Result)))
4303 break;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004304
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004305 if (Triple.isOSBinFormatELF()) {
Kristina Brooks34e24d52018-09-25 22:27:40 +00004306 if (!VD)
4307 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004308 } else {
4309 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4310 if (!VD || !VD->hasAttr<DLLExportAttr>())
Kristina Brooks34e24d52018-09-25 22:27:40 +00004311 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004312 else
Kristina Brooks34e24d52018-09-25 22:27:40 +00004313 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Kristina Brooks34e24d52018-09-25 22:27:40 +00004314 }
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004315
Kristina Brooks34e24d52018-09-25 22:27:40 +00004316 setDSOLocal(GV);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004317 }
4318 }
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004319
Daniel Dunbard644ad62008-08-23 18:37:06 +00004320 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00004321 CFConstantStringClassRef =
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004322 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4323 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004324 }
Mike Stump11289f42009-09-09 15:08:12 +00004325
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004326 QualType CFTy = Context.getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00004327
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004328 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00004329
John McCall23c9dc62016-11-28 22:18:27 +00004330 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00004331 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00004332
Anders Carlssonb04ea612007-08-21 00:21:21 +00004333 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004334 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00004335
Anders Carlssonb04ea612007-08-21 00:21:21 +00004336 // Flags.
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004337 if (IsSwiftABI) {
4338 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4339 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4340 } else {
4341 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4342 }
Anders Carlsson157c3212009-08-16 05:55:31 +00004343
Anders Carlssonb04ea612007-08-21 00:21:21 +00004344 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00004345 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00004346 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00004347 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00004348 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4349 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00004350 C = llvm::ConstantDataArray::get(VMContext, Arr);
4351 } else {
David Blaikie13156b62014-11-19 03:06:06 +00004352 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00004353 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00004354
Bill Wendling86131f22012-01-10 08:46:39 +00004355 // Note: -fwritable-strings doesn't make the backing store strings of
4356 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004357 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00004358 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4359 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004360 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00004361 // Don't enforce the target's minimum global alignment, since the only use
4362 // of the string is via this class initializer.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004363 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4364 : Context.getTypeAlignInChars(Context.CharTy);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004365 GV->setAlignment(Align.getQuantity());
4366
4367 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4368 // Without it LLVM can merge the string with a non unnamed_addr one during
4369 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004370 if (Triple.isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004371 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4372 : "__TEXT,__cstring,cstring_literals");
Kristina Brooks34e24d52018-09-25 22:27:40 +00004373 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4374 // the static linker to adjust permissions to read-only later on.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004375 else if (Triple.isOSBinFormatELF())
Kristina Brooks34e24d52018-09-25 22:27:40 +00004376 GV->setSection(".rodata");
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004377
Bill Wendling82b87f12012-03-30 00:26:17 +00004378 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004379 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00004380 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00004381
Bill Wendling82b87f12012-03-30 00:26:17 +00004382 if (isUTF16)
4383 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004384 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4385 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00004386
Anders Carlssonb04ea612007-08-21 00:21:21 +00004387 // String length.
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004388 llvm::IntegerType *LengthTy =
4389 llvm::IntegerType::get(getModule().getContext(),
4390 Context.getTargetInfo().getLongWidth());
4391 if (IsSwiftABI) {
4392 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4393 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4394 LengthTy = Int32Ty;
4395 else
4396 LengthTy = IntPtrTy;
4397 }
4398 Fields.addInt(LengthTy, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004399
John McCall7f416cc2015-09-08 08:05:57 +00004400 CharUnits Alignment = getPointerAlign();
4401
Anders Carlssonb04ea612007-08-21 00:21:21 +00004402 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004403 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4404 /*isConstant=*/false,
4405 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004406 switch (Triple.getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004407 case llvm::Triple::UnknownObjectFormat:
4408 llvm_unreachable("unknown file format");
Jason Liua03ae732019-03-12 22:01:10 +00004409 case llvm::Triple::XCOFF:
4410 llvm_unreachable("XCOFF is not yet implemented");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004411 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004412 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00004413 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00004414 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004415 break;
4416 case llvm::Triple::MachO:
4417 GV->setSection("__DATA,__cfstring");
4418 break;
4419 }
David Blaikie13156b62014-11-19 03:06:06 +00004420 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00004421
John McCall7f416cc2015-09-08 08:05:57 +00004422 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00004423}
Chris Lattnerfb300092007-11-28 05:34:05 +00004424
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00004425bool CodeGenModule::getExpressionLocationsEnabled() const {
4426 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4427}
4428
Douglas Gregor636e2002011-08-09 17:23:49 +00004429QualType CodeGenModule::getObjCFastEnumerationStateType() {
4430 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004431 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00004432 D->startDefinition();
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004433
Douglas Gregor636e2002011-08-09 17:23:49 +00004434 QualType FieldTypes[] = {
4435 Context.UnsignedLongTy,
4436 Context.getPointerType(Context.getObjCIdType()),
4437 Context.getPointerType(Context.UnsignedLongTy),
4438 Context.getConstantArrayType(Context.UnsignedLongTy,
4439 llvm::APInt(32, 5), ArrayType::Normal, 0)
4440 };
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004441
Douglas Gregor636e2002011-08-09 17:23:49 +00004442 for (size_t i = 0; i < 4; ++i) {
4443 FieldDecl *Field = FieldDecl::Create(Context,
4444 D,
4445 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004446 SourceLocation(), nullptr,
4447 FieldTypes[i], /*TInfo=*/nullptr,
4448 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00004449 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004450 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00004451 Field->setAccess(AS_public);
4452 D->addDecl(Field);
4453 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004454
Douglas Gregor636e2002011-08-09 17:23:49 +00004455 D->completeDefinition();
4456 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4457 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004458
Douglas Gregor636e2002011-08-09 17:23:49 +00004459 return ObjCFastEnumerationStateType;
4460}
4461
Eli Friedmanfcec6302011-11-01 02:23:42 +00004462llvm::Constant *
4463CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4464 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004465
Eli Friedmanfcec6302011-11-01 02:23:42 +00004466 // Don't emit it as the address of the string, emit the string data itself
4467 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00004468 if (E->getCharByteWidth() == 1) {
4469 SmallString<64> Str(E->getString());
4470
4471 // Resize the string to the right size, which is indicated by its type.
4472 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4473 Str.resize(CAT->getSize().getZExtValue());
4474 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4475 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004476
4477 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00004478 llvm::Type *ElemTy = AType->getElementType();
4479 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00004480
4481 // Wide strings have either 2-byte or 4-byte elements.
4482 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4483 SmallVector<uint16_t, 32> Elements;
4484 Elements.reserve(NumElements);
4485
4486 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4487 Elements.push_back(E->getCodeUnit(i));
4488 Elements.resize(NumElements);
4489 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00004490 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004491
Chris Lattner02cb1712012-02-06 22:52:04 +00004492 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4493 SmallVector<uint32_t, 32> Elements;
4494 Elements.reserve(NumElements);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004495
Chris Lattner02cb1712012-02-06 22:52:04 +00004496 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4497 Elements.push_back(E->getCodeUnit(i));
4498 Elements.resize(NumElements);
4499 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00004500}
4501
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004502static llvm::GlobalVariable *
4503GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4504 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00004505 CharUnits Alignment) {
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004506 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4507 CGM.getStringLiteralAddressSpace());
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004508
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004509 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004510 // Create a global variable for this string
4511 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004512 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4513 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00004514 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004515 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004516 if (GV->isWeakForLinker()) {
4517 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4518 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4519 }
Rafael Espindola0d40f122018-03-20 20:42:55 +00004520 CGM.setDSOLocal(GV);
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004521
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004522 return GV;
4523}
4524
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004525/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4526/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00004527ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00004528CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4529 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00004530 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00004531
Richard Smith00db2f12014-07-29 21:20:12 +00004532 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4533 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00004534 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004535 Entry = &ConstantStringMap[C];
4536 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004537 if (Alignment.getQuantity() > GV->getAlignment())
4538 GV->setAlignment(Alignment.getQuantity());
Michael Liao0ee7bd42019-02-21 19:40:20 +00004539 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4540 Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00004541 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00004542 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00004543
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004544 SmallString<256> MangledNameBuffer;
4545 StringRef GlobalVariableName;
4546 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00004547
Reid Kleckner7a368962018-09-06 18:25:39 +00004548 // Mangle the string literal if that's how the ABI merges duplicate strings.
4549 // Don't do it if they are writable, since we don't want writes in one TU to
4550 // affect strings in another.
4551 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4552 !LangOpts.WritableStrings) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004553 llvm::raw_svector_ostream Out(MangledNameBuffer);
4554 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004555 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4556 GlobalVariableName = MangledNameBuffer;
4557 } else {
4558 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00004559 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00004560 }
4561
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004562 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4563 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004564 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00004565
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00004566 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4567 QualType());
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004568
4569 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4570 Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004571}
4572
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004573/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4574/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00004575ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004576CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4577 std::string Str;
4578 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00004579
4580 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004581}
4582
Alexey Samsonovadc90372014-06-04 20:25:57 +00004583/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4584/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004585/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00004586ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4587 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00004588 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00004589 CharUnits Alignment =
4590 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004591
Richard Smith00db2f12014-07-29 21:20:12 +00004592 llvm::Constant *C =
4593 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4594
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004595 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00004596 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004597 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004598 Entry = &ConstantStringMap[C];
4599 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004600 if (Alignment.getQuantity() > GV->getAlignment())
4601 GV->setAlignment(Alignment.getQuantity());
Michael Liao0ee7bd42019-02-21 19:40:20 +00004602 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4603 Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004604 }
4605 }
4606
Daniel Dunbar08b216a2009-03-31 23:42:16 +00004607 // Get the default prefix if a name wasn't specified.
4608 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00004609 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00004610 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004611 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4612 GlobalName, Alignment);
4613 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004614 *Entry = GV;
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004615
4616 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4617 Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00004618}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004619
John McCall7f416cc2015-09-08 08:05:57 +00004620ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00004621 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00004622 assert((E->getStorageDuration() == SD_Static ||
4623 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004624 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00004625
4626 // If we're not materializing a subobject of the temporary, keep the
4627 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00004628 QualType MaterializedType = Init->getType();
4629 if (Init == E->GetTemporaryExpr())
4630 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004631
John McCall7f416cc2015-09-08 08:05:57 +00004632 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4633
David Majnemer2dcef9e2015-08-13 23:50:15 +00004634 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00004635 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004636
4637 // FIXME: If an externally-visible declaration extends multiple temporaries,
4638 // we need to give each temporary the same name in every translation unit (and
4639 // we also need to make the temporaries externally-visible).
4640 SmallString<256> Name;
4641 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00004642 getCXXABI().getMangleContext().mangleReferenceTemporary(
4643 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00004644
Craig Topper8a13c412014-05-21 05:09:00 +00004645 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004646 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00004647 // We might have a cached constant initializer for this temporary. Note
4648 // that this might have a different value from the value computed by
4649 // evaluating the initializer if the surrounding constant expression
4650 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00004651 Value = getContext().getMaterializedTemporaryValue(E, false);
4652 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00004653 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004654 }
4655
Richard Smitha509f2f2013-06-14 03:07:01 +00004656 // Try evaluating it now, it might have a constant initializer.
4657 Expr::EvalResult EvalResult;
4658 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4659 !EvalResult.hasSideEffects())
4660 Value = &EvalResult.Val;
4661
Alexander Richardson6d989432017-10-15 18:48:14 +00004662 LangAS AddrSpace =
John McCallde0fe072017-08-15 21:42:52 +00004663 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4664
4665 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00004666 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00004667 bool Constant = false;
4668 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00004669 if (Value) {
4670 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00004671 emitter.emplace(*this);
4672 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4673 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00004674 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4675 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004676 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00004677 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00004678 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00004679 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00004680 }
4681
4682 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00004683 llvm::GlobalValue::LinkageTypes Linkage =
4684 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004685 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4686 const VarDecl *InitVD;
4687 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4688 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4689 // Temporaries defined inside a class get linkonce_odr linkage because the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004690 // class can be defined in multiple translation units.
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004691 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4692 } else {
4693 // There is no need for this temporary to have external linkage if the
4694 // VarDecl has external linkage.
4695 Linkage = llvm::GlobalVariable::InternalLinkage;
4696 }
4697 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00004698 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004699 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00004700 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00004701 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00004702 if (emitter) emitter->finalize(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +00004703 setGVProperties(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00004704 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004705 if (supportsCOMDAT() && GV->isWeakForLinker())
4706 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00004707 if (VD->getTLSKind())
4708 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00004709 llvm::Constant *CV = GV;
4710 if (AddrSpace != LangAS::Default)
4711 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4712 *this, GV, AddrSpace, LangAS::Default,
4713 Type->getPointerTo(
4714 getContext().getTargetAddressSpace(LangAS::Default)));
4715 MaterializedGlobalTemporaryMap[E] = CV;
4716 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004717}
4718
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004719/// EmitObjCPropertyImplementations - Emit information for synthesized
4720/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00004721void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004722 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004723 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004724 // Dynamic is just for type-checking.
4725 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4726 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4727
4728 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00004729 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004730 // we want, that just indicates if the decl came from a
4731 // property. What we want to know is if the method is defined in
4732 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004733 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004734 CodeGenFunction(*this).GenerateObjCGetter(
4735 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004736 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004737 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004738 CodeGenFunction(*this).GenerateObjCSetter(
4739 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004740 }
4741 }
4742}
4743
John McCall6a4fa522011-03-22 07:05:39 +00004744static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004745 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4746 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00004747 ivar; ivar = ivar->getNextIvar())
4748 if (ivar->getType().isDestructedType())
4749 return true;
4750
4751 return false;
4752}
4753
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004754static bool AllTrivialInitializers(CodeGenModule &CGM,
4755 ObjCImplementationDecl *D) {
4756 CodeGenFunction CGF(CGM);
4757 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4758 E = D->init_end(); B != E; ++B) {
4759 CXXCtorInitializer *CtorInitExp = *B;
4760 Expr *Init = CtorInitExp->getInit();
4761 if (!CGF.isTrivialInitializer(Init))
4762 return false;
4763 }
4764 return true;
4765}
4766
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004767/// EmitObjCIvarInitializations - Emit information for ivar initialization
4768/// for an implementation.
4769void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00004770 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4771 if (needsDestructMethod(D)) {
4772 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4773 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4774 ObjCMethodDecl *DTORMethod =
4775 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004776 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004777 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004778 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004779 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00004780 D->addInstanceMethod(DTORMethod);
4781 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00004782 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00004783 }
4784
4785 // If the implementation doesn't have any ivar initializers, we don't need
4786 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004787 if (D->getNumIvarInitializers() == 0 ||
4788 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004789 return;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004790
John McCall6a4fa522011-03-22 07:05:39 +00004791 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4792 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004793 // The constructor returns 'self'.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004794 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004795 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004796 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004797 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00004798 getContext().getObjCIdType(),
4799 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004800 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004801 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004802 /*isImplicitlyDeclared=*/true,
4803 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004804 ObjCMethodDecl::Required);
4805 D->addInstanceMethod(CTORMethod);
4806 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00004807 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004808}
4809
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004810// EmitLinkageSpec - Emit all declarations in a linkage spec.
4811void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00004812 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4813 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004814 ErrorUnsupported(LSD, "linkage spec");
4815 return;
4816 }
4817
Richard Smith8df390f2016-09-08 23:14:54 +00004818 EmitDeclContext(LSD);
4819}
4820
4821void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4822 for (auto *I : DC->decls()) {
4823 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4824 // are themselves considered "top-level", so EmitTopLevelDecl on an
4825 // ObjCImplDecl does not recursively visit them. We need to do that in
4826 // case they're nested inside another construct (LinkageSpecDecl /
4827 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00004828 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004829 for (auto *M : OID->methods())
4830 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004831 }
Richard Smith8df390f2016-09-08 23:14:54 +00004832
Aaron Ballman629afae2014-03-07 19:56:05 +00004833 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004834 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004835}
4836
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004837/// EmitTopLevelDecl - Emit code for a single top level declaration.
4838void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00004839 // Ignore dependent declarations.
Richard Smith32b615c2018-02-01 00:28:36 +00004840 if (D->isTemplated())
Douglas Gregor70d83e22009-06-29 17:30:29 +00004841 return;
Mike Stump11289f42009-09-09 15:08:12 +00004842
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004843 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00004844 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00004845 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004846 case Decl::Function:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004847 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00004848 // Always provide some coverage mapping
4849 // even for the functions that aren't emitted.
4850 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004851 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004852
Richard Smithada08882017-04-19 21:15:45 +00004853 case Decl::CXXDeductionGuide:
4854 // Function-like, but does not result in code emission.
4855 break;
4856
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004857 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00004858 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004859 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004860 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00004861 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4862 for (auto *B : DD->bindings())
4863 if (auto *HD = B->getHoldingVar())
4864 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004865 break;
4866
John McCall32f44bd2011-04-12 01:01:22 +00004867 // Indirect fields from global anonymous structs and unions can be
4868 // ignored; only the actual variable requires IR gen support.
4869 case Decl::IndirectField:
4870 break;
4871
Anders Carlssonf7475242009-04-15 15:55:24 +00004872 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004873 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00004874 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004875 break;
Richard Smithe1246122017-11-03 01:26:01 +00004876 case Decl::ClassTemplateSpecialization: {
4877 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4878 if (DebugInfo &&
4879 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4880 Spec->hasDefinition())
4881 DebugInfo->completeTemplateDefinition(*Spec);
4882 } LLVM_FALLTHROUGH;
Richard Smith62f19e72016-06-25 00:15:56 +00004883 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00004884 if (DebugInfo) {
4885 if (auto *ES = D->getASTContext().getExternalSource())
4886 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4887 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4888 }
Richard Smith62f19e72016-06-25 00:15:56 +00004889 // Emit any static data members, they may be definitions.
4890 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4891 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4892 EmitTopLevelDecl(I);
4893 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00004894 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00004895 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004896 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004897 case Decl::VarTemplate:
4898 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004899 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00004900 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00004901 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00004902 case Decl::Empty:
Richard Smith7c7e5312018-10-26 03:21:20 +00004903 case Decl::Binding:
Douglas Gregorfec52632009-06-20 00:51:54 +00004904 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00004905 case Decl::Using: // using X; [C++]
4906 if (CGDebugInfo *DI = getModuleDebugInfo())
4907 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4908 return;
David Blaikief121b932013-05-20 22:50:41 +00004909 case Decl::NamespaceAlias:
4910 if (CGDebugInfo *DI = getModuleDebugInfo())
4911 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4912 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00004913 case Decl::UsingDirective: // using namespace X; [C++]
4914 if (CGDebugInfo *DI = getModuleDebugInfo())
4915 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4916 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00004917 case Decl::CXXConstructor:
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00004918 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00004919 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004920 case Decl::CXXDestructor:
Reid Klecknere7de47e2013-07-22 13:51:44 +00004921 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004922 break;
Anders Carlsson87835432009-06-11 21:22:55 +00004923
4924 case Decl::StaticAssert:
4925 // Nothing to do.
4926 break;
4927
Anders Carlssonf7475242009-04-15 15:55:24 +00004928 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00004929
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004930 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00004931 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00004932 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00004933 break;
4934
Douglas Gregorf6102672012-01-01 21:23:57 +00004935 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004936 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00004937 if (Proto->isThisDeclarationADefinition())
4938 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004939 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00004940 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004941
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004942 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004943 // Categories have properties but don't support synthesize so we
4944 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00004945 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004946 break;
4947
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004948 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004949 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004950 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004951 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00004952 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00004953 // Emit global variable debug information.
4954 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00004955 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00004956 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4957 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004958 break;
Mike Stump11289f42009-09-09 15:08:12 +00004959 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004960 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004961 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004962 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004963 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004964 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4965 break;
4966 }
Mike Stump11289f42009-09-09 15:08:12 +00004967 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00004968 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004969 break;
4970
Nico Weber66220292016-03-02 17:28:48 +00004971 case Decl::PragmaComment: {
4972 const auto *PCD = cast<PragmaCommentDecl>(D);
4973 switch (PCD->getCommentKind()) {
4974 case PCK_Unknown:
4975 llvm_unreachable("unexpected pragma comment kind");
4976 case PCK_Linker:
4977 AppendLinkerOptions(PCD->getArg());
4978 break;
4979 case PCK_Lib:
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00004980 if (getTarget().getTriple().isOSBinFormatELF() &&
4981 !getTarget().getTriple().isPS4())
4982 AddELFLibDirective(PCD->getArg());
4983 else
4984 AddDependentLib(PCD->getArg());
Nico Weber66220292016-03-02 17:28:48 +00004985 break;
4986 case PCK_Compiler:
4987 case PCK_ExeStr:
4988 case PCK_User:
4989 break; // We ignore all of these.
4990 }
4991 break;
4992 }
4993
Nico Webercbbaeb12016-03-02 19:28:54 +00004994 case Decl::PragmaDetectMismatch: {
4995 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4996 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4997 break;
4998 }
4999
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00005000 case Decl::LinkageSpec:
5001 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005002 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005003
5004 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00005005 // File-scope asm is ignored during device-side CUDA compilation.
5006 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5007 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005008 // File-scope asm is ignored during device-side OpenMP compilation.
5009 if (LangOpts.OpenMPIsDevice)
5010 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005011 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00005012 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005013 break;
5014 }
Mike Stump11289f42009-09-09 15:08:12 +00005015
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005016 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005017 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005018
Richard Smithdc1f0422016-07-20 19:10:16 +00005019 // If we've already imported this module, we're done.
5020 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00005021 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005022
Richard Smithdc1f0422016-07-20 19:10:16 +00005023 // Emit debug information for direct imports.
5024 if (!Import->getImportedOwningModule()) {
5025 if (CGDebugInfo *DI = getModuleDebugInfo())
5026 DI->EmitImportDecl(*Import);
5027 }
5028
Manman Ren3b5dbf22016-10-14 18:55:44 +00005029 // Find all of the submodules and emit the module initializers.
5030 llvm::SmallPtrSet<clang::Module *, 16> Visited;
5031 SmallVector<clang::Module *, 16> Stack;
5032 Visited.insert(Import->getImportedModule());
5033 Stack.push_back(Import->getImportedModule());
5034
5035 while (!Stack.empty()) {
5036 clang::Module *Mod = Stack.pop_back_val();
5037 if (!EmittedModuleInitializers.insert(Mod).second)
5038 continue;
5039
5040 for (auto *D : Context.getModuleInitializers(Mod))
5041 EmitTopLevelDecl(D);
5042
5043 // Visit the submodules of this module.
5044 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5045 SubEnd = Mod->submodule_end();
5046 Sub != SubEnd; ++Sub) {
5047 // Skip explicit children; they need to be explicitly imported to emit
5048 // the initializers.
5049 if ((*Sub)->IsExplicit)
5050 continue;
5051
5052 if (Visited.insert(*Sub).second)
5053 Stack.push_back(*Sub);
5054 }
5055 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005056 break;
David Blaikie0e716b42014-03-03 23:48:23 +00005057 }
5058
Richard Smith8df390f2016-09-08 23:14:54 +00005059 case Decl::Export:
5060 EmitDeclContext(cast<ExportDecl>(D));
5061 break;
5062
Alexey Bataev97720002014-11-11 04:05:39 +00005063 case Decl::OMPThreadPrivate:
5064 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5065 break;
5066
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005067 case Decl::OMPAllocate:
5068 break;
5069
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005070 case Decl::OMPDeclareReduction:
5071 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5072 break;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00005073
Michael Kruse251e1482019-02-01 20:25:04 +00005074 case Decl::OMPDeclareMapper:
5075 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5076 break;
5077
Kelvin Li1408f912018-09-26 04:28:39 +00005078 case Decl::OMPRequires:
5079 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5080 break;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005081
Mike Stump11289f42009-09-09 15:08:12 +00005082 default:
Mike Stump18bb9282009-05-16 07:57:57 +00005083 // Make sure we handled everything we should, every other kind is a
5084 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
5085 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005086 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00005087 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005088 }
5089}
John McCall09ae0322010-07-06 23:57:41 +00005090
Alex Lorenzee024992014-08-04 18:41:51 +00005091void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5092 // Do we need to generate coverage mapping?
5093 if (!CodeGenOpts.CoverageMapping)
5094 return;
5095 switch (D->getKind()) {
5096 case Decl::CXXConversion:
5097 case Decl::CXXMethod:
5098 case Decl::Function:
5099 case Decl::ObjCMethod:
5100 case Decl::CXXConstructor:
5101 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00005102 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00005103 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00005104 SourceManager &SM = getContext().getSourceManager();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005105 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
Vedant Kumar0acf3432017-09-22 18:23:04 +00005106 return;
Alex Lorenzee024992014-08-04 18:41:51 +00005107 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5108 if (I == DeferredEmptyCoverageMappingDecls.end())
5109 DeferredEmptyCoverageMappingDecls[D] = true;
5110 break;
5111 }
5112 default:
5113 break;
5114 };
5115}
5116
5117void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5118 // Do we need to generate coverage mapping?
5119 if (!CodeGenOpts.CoverageMapping)
5120 return;
5121 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5122 if (Fn->isTemplateInstantiation())
5123 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5124 }
5125 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5126 if (I == DeferredEmptyCoverageMappingDecls.end())
5127 DeferredEmptyCoverageMappingDecls[D] = false;
5128 else
5129 I->second = false;
5130}
5131
5132void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Eli Friedman8516b7f2017-12-19 01:54:09 +00005133 // We call takeVector() here to avoid use-after-free.
5134 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5135 // we deserialize function bodies to emit coverage info for them, and that
5136 // deserializes more declarations. How should we handle that case?
5137 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
Eli Friedmandbcfade2017-12-13 00:14:17 +00005138 if (!Entry.second)
Alex Lorenzee024992014-08-04 18:41:51 +00005139 continue;
Eli Friedmandbcfade2017-12-13 00:14:17 +00005140 const Decl *D = Entry.first;
Alex Lorenzee024992014-08-04 18:41:51 +00005141 switch (D->getKind()) {
5142 case Decl::CXXConversion:
5143 case Decl::CXXMethod:
5144 case Decl::Function:
5145 case Decl::ObjCMethod: {
5146 CodeGenPGO PGO(*this);
5147 GlobalDecl GD(cast<FunctionDecl>(D));
5148 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5149 getFunctionLinkage(GD));
5150 break;
5151 }
5152 case Decl::CXXConstructor: {
5153 CodeGenPGO PGO(*this);
5154 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5155 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5156 getFunctionLinkage(GD));
5157 break;
5158 }
5159 case Decl::CXXDestructor: {
5160 CodeGenPGO PGO(*this);
5161 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5162 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5163 getFunctionLinkage(GD));
5164 break;
5165 }
5166 default:
5167 break;
5168 };
5169 }
5170}
5171
John McCall09ae0322010-07-06 23:57:41 +00005172/// Turns the given pointer into a constant.
5173static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5174 const void *Ptr) {
5175 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00005176 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00005177 return llvm::ConstantInt::get(i64, PtrInt);
5178}
5179
5180static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5181 llvm::NamedMDNode *&GlobalMetadata,
5182 GlobalDecl D,
5183 llvm::GlobalValue *Addr) {
5184 if (!GlobalMetadata)
5185 GlobalMetadata =
5186 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5187
5188 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005189 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5190 llvm::ConstantAsMetadata::get(GetPointerConstant(
5191 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00005192 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00005193}
5194
Richard Smithdf931ce2013-04-06 05:00:46 +00005195/// For each function which is declared within an extern "C" region and marked
5196/// as 'used', but has internal linkage, create an alias from the unmangled
5197/// name to the mangled name if possible. People expect to be able to refer
5198/// to such functions with an unmangled name from inline assembly within the
5199/// same translation unit.
5200void CodeGenModule::EmitStaticExternCAliases() {
Yaxun Liub0eee292018-03-29 14:50:00 +00005201 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00005202 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00005203 for (auto &I : StaticExternCValues) {
5204 IdentifierInfo *Name = I.first;
5205 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00005206 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00005207 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00005208 }
Richard Smithdf931ce2013-04-06 05:00:46 +00005209}
5210
Alp Tokerfb8d02b2014-06-05 22:10:59 +00005211bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5212 GlobalDecl &Result) const {
5213 auto Res = Manglings.find(MangledName);
5214 if (Res == Manglings.end())
5215 return false;
5216 Result = Res->getValue();
5217 return true;
5218}
5219
John McCall09ae0322010-07-06 23:57:41 +00005220/// Emits metadata nodes associating all the global values in the
5221/// current module with the Decls they came from. This is useful for
5222/// projects using IR gen as a subroutine.
5223///
5224/// Since there's currently no way to associate an MDNode directly
5225/// with an llvm::GlobalValue, we create a global named metadata
5226/// with the name 'clang.global.decl.ptrs'.
5227void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00005228 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005229
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005230 for (auto &I : MangledDeclNames) {
5231 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00005232 // Some mangled names don't necessarily have an associated GlobalValue
5233 // in this module, e.g. if we mangled it for DebugInfo.
5234 if (Addr)
5235 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00005236 }
5237}
5238
5239/// Emits metadata nodes for all the local variables in the current
5240/// function.
5241void CodeGenFunction::EmitDeclMetadata() {
5242 if (LocalDeclMap.empty()) return;
5243
5244 llvm::LLVMContext &Context = getLLVMContext();
5245
5246 // Find the unique metadata ID for this name.
5247 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5248
Craig Topper8a13c412014-05-21 05:09:00 +00005249 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005250
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005251 for (auto &I : LocalDeclMap) {
5252 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00005253 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005254 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005255 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005256 Alloca->setMetadata(
5257 DeclPtrKind, llvm::MDNode::get(
5258 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005259 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005260 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5261 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5262 }
5263 }
5264}
Daniel Dunbar900546d2010-07-16 00:00:15 +00005265
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005266void CodeGenModule::EmitVersionIdentMetadata() {
5267 llvm::NamedMDNode *IdentMetadata =
5268 TheModule.getOrInsertNamedMetadata("llvm.ident");
5269 std::string Version = getClangFullVersion();
5270 llvm::LLVMContext &Ctx = TheModule.getContext();
5271
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005272 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005273 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5274}
5275
Scott Linderde6beb02018-12-14 15:38:15 +00005276void CodeGenModule::EmitCommandLineMetadata() {
5277 llvm::NamedMDNode *CommandLineMetadata =
5278 TheModule.getOrInsertNamedMetadata("llvm.commandline");
5279 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5280 llvm::LLVMContext &Ctx = TheModule.getContext();
5281
5282 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5283 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5284}
5285
Robert Lytton57765d52014-07-03 09:30:33 +00005286void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00005287 // Warning, new MangledDeclNames may be appended within this loop.
5288 // We rely on MapVector insertions adding new elements to the end
5289 // of the container.
5290 // FIXME: Move this loop into the one target that needs it, and only
5291 // loop over those declarations for which we couldn't emit the target
5292 // metadata when we emitted the declaration.
5293 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00005294 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00005295 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5296 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00005297 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5298 }
5299}
5300
Nick Lewycky85c011d2011-05-05 00:08:20 +00005301void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00005302 if (getCodeGenOpts().CoverageDataFile.empty() &&
5303 getCodeGenOpts().CoverageNotesFile.empty())
5304 return;
5305
5306 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5307 if (!CUNode)
5308 return;
5309
5310 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5311 llvm::LLVMContext &Ctx = TheModule.getContext();
5312 auto *CoverageDataFile =
5313 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5314 auto *CoverageNotesFile =
5315 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5316 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5317 llvm::MDNode *CU = CUNode->getOperand(i);
5318 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5319 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00005320 }
5321}
Nico Webercf4ff5862012-10-11 10:13:44 +00005322
Nico Weber17d3a2c2014-09-08 16:26:36 +00005323llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00005324 // Sema has checked that all uuid strings are of the form
5325 // "12345678-1234-1234-1234-1234567890ab".
5326 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00005327 for (unsigned i = 0; i < 36; ++i) {
5328 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5329 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00005330 }
Nico Webercf4ff5862012-10-11 10:13:44 +00005331
Nico Weberdfa274e2014-09-08 16:11:15 +00005332 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00005333 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00005334
David Majnemerbbecd092013-08-15 19:59:14 +00005335 llvm::Constant *Field3[8];
5336 for (unsigned Idx = 0; Idx < 8; ++Idx)
5337 Field3[Idx] = llvm::ConstantInt::get(
5338 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5339
5340 llvm::Constant *Fields[4] = {
5341 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5342 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5343 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5344 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5345 };
5346
5347 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00005348}
David Majnemere2cb8d12014-07-07 06:20:47 +00005349
5350llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5351 bool ForEH) {
5352 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5353 // FIXME: should we even be calling this method if RTTI is disabled
5354 // and it's not for EH?
Yaxun Liu6328f9a2018-06-05 15:11:02 +00005355 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
David Majnemere2cb8d12014-07-07 06:20:47 +00005356 return llvm::Constant::getNullValue(Int8PtrTy);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00005357
David Majnemere2cb8d12014-07-07 06:20:47 +00005358 if (ForEH && Ty->isObjCObjectPointerType() &&
5359 LangOpts.ObjCRuntime.isGNUFamily())
5360 return ObjCRuntime->GetEHType(Ty);
5361
David Majnemer443250f2015-03-17 20:35:00 +00005362 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00005363}
5364
Alexey Bataev97720002014-11-11 04:05:39 +00005365void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005366 // Do not emit threadprivates in simd-only mode.
5367 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5368 return;
Alexey Bataev97720002014-11-11 04:05:39 +00005369 for (auto RefExpr : D->varlists()) {
5370 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5371 bool PerformInit =
5372 VD->getAnyInitializer() &&
5373 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5374 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00005375
5376 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00005377 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005378 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00005379 CXXGlobalInits.push_back(InitFunction);
5380 }
5381}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005382
Peter Collingbournee44acad2018-06-26 02:15:47 +00005383llvm::Metadata *
5384CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5385 StringRef Suffix) {
5386 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005387 if (InternalId)
5388 return InternalId;
5389
5390 if (isExternallyVisible(T->getLinkage())) {
5391 std::string OutName;
5392 llvm::raw_string_ostream Out(OutName);
5393 getCXXABI().getMangleContext().mangleTypeName(T, Out);
Peter Collingbournee44acad2018-06-26 02:15:47 +00005394 Out << Suffix;
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005395
5396 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5397 } else {
5398 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5399 llvm::ArrayRef<llvm::Metadata *>());
5400 }
5401
5402 return InternalId;
5403}
5404
Peter Collingbournee44acad2018-06-26 02:15:47 +00005405llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5406 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5407}
5408
5409llvm::Metadata *
5410CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5411 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5412}
5413
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005414// Generalize pointer types to a void pointer with the qualifiers of the
5415// originally pointed-to type, e.g. 'const char *' and 'char * const *'
5416// generalize to 'const void *' while 'char *' and 'const char **' generalize to
5417// 'void *'.
5418static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5419 if (!Ty->isPointerType())
5420 return Ty;
5421
5422 return Ctx.getPointerType(
5423 QualType(Ctx.VoidTy).withCVRQualifiers(
5424 Ty->getPointeeType().getCVRQualifiers()));
5425}
5426
5427// Apply type generalization to a FunctionType's return and argument types
5428static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5429 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5430 SmallVector<QualType, 8> GeneralizedParams;
5431 for (auto &Param : FnType->param_types())
5432 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5433
5434 return Ctx.getFunctionType(
5435 GeneralizeType(Ctx, FnType->getReturnType()),
5436 GeneralizedParams, FnType->getExtProtoInfo());
5437 }
5438
5439 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5440 return Ctx.getFunctionNoProtoType(
5441 GeneralizeType(Ctx, FnType->getReturnType()));
5442
5443 llvm_unreachable("Encountered unknown FunctionType");
5444}
5445
5446llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
Peter Collingbournee44acad2018-06-26 02:15:47 +00005447 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5448 GeneralizedMetadataIdMap, ".generalized");
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005449}
5450
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005451/// Returns whether this module needs the "all-vtables" type identifier.
5452bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005453 // Returns true if at least one of vtable-based CFI checkers is enabled and
5454 // is not in the trapping mode.
5455 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5456 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5457 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5458 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5459 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5460 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5461 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5462 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5463}
5464
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005465void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5466 CharUnits Offset,
5467 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005468 llvm::Metadata *MD =
5469 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005470 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005471
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005472 if (CodeGenOpts.SanitizeCfiCrossDso)
5473 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5474 VTable->addTypeMetadata(Offset.getQuantity(),
5475 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005476
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005477 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005478 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005479 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005480 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005481}
Eric Christopher2b90a642015-11-11 23:05:08 +00005482
Gabor Buella1a83d062018-06-07 08:48:36 +00005483TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5484 assert(TD != nullptr);
5485 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5486
5487 ParsedAttr.Features.erase(
5488 llvm::remove_if(ParsedAttr.Features,
5489 [&](const std::string &Feat) {
5490 return !Target.isValidFeatureName(
5491 StringRef{Feat}.substr(1));
5492 }),
5493 ParsedAttr.Features.end());
5494 return ParsedAttr;
5495}
5496
5497
Eric Christopher2b90a642015-11-11 23:05:08 +00005498// Fills in the supplied string map with the set of target features for the
5499// passed in function.
5500void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
Erich Keanede6480a32018-11-13 15:48:08 +00005501 GlobalDecl GD) {
Eric Christopher2b90a642015-11-11 23:05:08 +00005502 StringRef TargetCPU = Target.getTargetOpts().CPU;
Erich Keanede6480a32018-11-13 15:48:08 +00005503 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
Eric Christopher2b90a642015-11-11 23:05:08 +00005504 if (const auto *TD = FD->getAttr<TargetAttr>()) {
Gabor Buella1a83d062018-06-07 08:48:36 +00005505 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
Erich Keanecf8807c2017-10-27 18:32:23 +00005506
Eric Christopher2b90a642015-11-11 23:05:08 +00005507 // Make a copy of the features as passed on the command line into the
5508 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00005509 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00005510 Target.getTargetOpts().FeaturesAsWritten.begin(),
5511 Target.getTargetOpts().FeaturesAsWritten.end());
5512
Erich Keanecf8807c2017-10-27 18:32:23 +00005513 if (ParsedAttr.Architecture != "" &&
5514 Target.isValidCPUName(ParsedAttr.Architecture))
5515 TargetCPU = ParsedAttr.Architecture;
Eric Christopher2b90a642015-11-11 23:05:08 +00005516
5517 // Now populate the feature map, first with the TargetCPU which is either
5518 // the default or a new one from the target attribute string. Then we'll use
5519 // the passed in features (FeaturesAsWritten) along with the new ones from
5520 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00005521 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5522 ParsedAttr.Features);
Erich Keane3efe0022018-07-20 14:13:28 +00005523 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5524 llvm::SmallVector<StringRef, 32> FeaturesTmp;
Erich Keanede6480a32018-11-13 15:48:08 +00005525 Target.getCPUSpecificCPUDispatchFeatures(
5526 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
Erich Keane3efe0022018-07-20 14:13:28 +00005527 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5528 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00005529 } else {
5530 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5531 Target.getTargetOpts().Features);
5532 }
5533}
Peter Collingbournedc134532016-01-16 00:31:22 +00005534
5535llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5536 if (!SanStats)
5537 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5538
5539 return *SanStats;
5540}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005541llvm::Value *
5542CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5543 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00005544 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00005545 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005546 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5547 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5548 "__translate_sampler_initializer"),
5549 {C});
5550}