blob: e79eb71b793235b276ae371c8553f500e7a16884 [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) {
Gheorghe-Teodor Bercea66cdbb472019-05-21 19:42:01 +0000413 if (llvm::Function *OpenMPRequiresDirectiveRegFun =
414 OpenMPRuntime->emitRequiresDirectiveRegFun()) {
415 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
416 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000417 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000418 OpenMPRuntime->emitRegistrationFunction()) {
419 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
420 OpenMPRegistrationFunction : nullptr;
421 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
422 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000423 OpenMPRuntime->clear();
424 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000425 if (PGOReader) {
Rong Xu39f6d7e2019-03-01 17:50:20 +0000426 getModule().setProfileSummary(
427 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
428 llvm::ProfileSummary::PSK_Instr);
Easwaran Raman695890c2015-12-17 19:14:27 +0000429 if (PGOStats.hasDiagnostics())
430 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
431 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000432 EmitCtorList(GlobalCtors, "llvm.global_ctors");
433 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000434 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000435 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000436 EmitDeferredUnusedCoverageMappings();
437 if (CoverageMapping)
438 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000439 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000440 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000441 CodeGenFunction(*this).EmitCfiCheckStub();
442 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000443 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000444 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000445 if (SanStats)
446 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000447
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000448 if (CodeGenOpts.Autolink &&
449 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000450 EmitModuleLinkOptions();
451 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000452
Ben Dunbobbin1d165152019-05-17 03:44:15 +0000453 // On ELF we pass the dependent library specifiers directly to the linker
454 // without manipulating them. This is in contrast to other platforms where
455 // they are mapped to a specific linker option by the compiler. This
456 // difference is a result of the greater variety of ELF linkers and the fact
457 // that ELF linkers tend to handle libraries in a more complicated fashion
458 // than on other platforms. This forces us to defer handling the dependent
459 // libs to the linker.
Yaxun Liu02afe4e2019-05-28 21:18:59 +0000460 //
461 // CUDA/HIP device and host libraries are different. Currently there is no
462 // way to differentiate dependent libraries for host or device. Existing
463 // usage of #pragma comment(lib, *) is intended for host libraries on
464 // Windows. Therefore emit llvm.dependent-libraries only for host.
465 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
Ben Dunbobbin1d165152019-05-17 03:44:15 +0000466 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
467 for (auto *MD : ELFDependentLibraries)
468 NMD->addOperand(MD);
469 }
470
Nirav Dave741dea02017-03-30 13:41:44 +0000471 // Record mregparm value now so it is visible through rest of codegen.
472 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
473 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
474 CodeGenOpts.NumRegisterParameters);
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000475
Reid Kleckner124955a2015-08-05 18:51:13 +0000476 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000477 // We actually want the latest version when there are conflicts.
478 // We can change from Warning to Latest if such mode is supported.
479 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
480 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000481 }
482 if (CodeGenOpts.EmitCodeView) {
483 // Indicate that we want CodeView in the metadata.
484 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
485 }
Reid Kleckner75557712018-11-16 18:47:41 +0000486 if (CodeGenOpts.CodeViewGHash) {
487 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
488 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000489 if (CodeGenOpts.ControlFlowGuard) {
490 // We want function ID tables for Control Flow Guard.
Hans Wennborga912e3e2018-08-10 09:49:21 +0000491 getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000492 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000493 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
494 // We don't support LTO with 2 with different StrictVTablePointers
495 // FIXME: we could support it by stripping all the information introduced
496 // by StrictVTablePointers.
497
498 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
499
500 llvm::Metadata *Ops[2] = {
501 llvm::MDString::get(VMContext, "StrictVTablePointers"),
502 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
503 llvm::Type::getInt32Ty(VMContext), 1))};
504
505 getModule().addModuleFlag(llvm::Module::Require,
506 "StrictVTablePointersRequirement",
507 llvm::MDNode::get(VMContext, Ops));
508 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000509 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000510 // We support a single version in the linked module. The LLVM
511 // parser will drop debug info with a different version number
512 // (and warn about it, too).
513 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000514 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000515
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000516 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000517 // the correct build attributes in the ARM backend. wchar_size is also used by
518 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000519 uint64_t WCharWidth =
520 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000521 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
522
Justin Bogner9bb7f152014-06-23 20:03:28 +0000523 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000524 if ( Arch == llvm::Triple::arm
525 || Arch == llvm::Triple::armeb
526 || Arch == llvm::Triple::thumb
527 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000528 // The minimum width of an enum in bytes
529 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
530 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
531 }
532
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000533 if (CodeGenOpts.SanitizeCfiCrossDso) {
534 // Indicate that we want cross-DSO control flow integrity checks.
535 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
536 }
537
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000538 if (CodeGenOpts.CFProtectionReturn &&
539 Target.checkCFProtectionReturnSupported(getDiags())) {
540 // Indicate that we want to instrument return control flow protection.
541 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
542 1);
543 }
544
545 if (CodeGenOpts.CFProtectionBranch &&
546 Target.checkCFProtectionBranchSupported(getDiags())) {
547 // Indicate that we want to instrument branch control flow protection.
548 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
549 1);
550 }
551
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000552 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000553 // Indicate whether __nvvm_reflect should be configured to flush denormal
554 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
555 // property.)
556 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
Yaxun Liue1bfbc52018-07-21 02:02:22 +0000557 CodeGenOpts.FlushDenorm ? 1 : 0);
Justin Lebard3a44f62016-04-05 18:26:20 +0000558 }
559
Alexey Bader364a1162017-06-20 14:30:18 +0000560 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
561 if (LangOpts.OpenCL) {
562 EmitOpenCLMetadata();
563 // Emit SPIR version.
Anastasia Stulovaeba9a6e2019-05-09 10:25:45 +0000564 if (getTriple().isSPIR()) {
Alexey Bader364a1162017-06-20 14:30:18 +0000565 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
566 // opencl.spir.version named metadata.
Anastasia Stulovaf61b5482019-05-30 15:18:07 +0000567 // C++ is backwards compatible with OpenCL v2.0.
568 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
Alexey Bader364a1162017-06-20 14:30:18 +0000569 llvm::Metadata *SPIRVerElts[] = {
570 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Anastasia Stulovaf61b5482019-05-30 15:18:07 +0000571 Int32Ty, Version / 100)),
Alexey Bader364a1162017-06-20 14:30:18 +0000572 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Anastasia Stulovaf61b5482019-05-30 15:18:07 +0000573 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
Alexey Bader364a1162017-06-20 14:30:18 +0000574 llvm::NamedMDNode *SPIRVerMD =
575 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
576 llvm::LLVMContext &Ctx = TheModule.getContext();
577 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
578 }
579 }
580
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000581 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000582 assert(PLevel < 3 && "Invalid PIC Level");
583 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000584 if (Context.getLangOpts().PIE)
585 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000586 }
587
Caroline Tice62279732018-09-21 18:34:59 +0000588 if (getCodeGenOpts().CodeModel.size() > 0) {
589 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
590 .Case("tiny", llvm::CodeModel::Tiny)
591 .Case("small", llvm::CodeModel::Small)
592 .Case("kernel", llvm::CodeModel::Kernel)
593 .Case("medium", llvm::CodeModel::Medium)
594 .Case("large", llvm::CodeModel::Large)
595 .Default(~0u);
596 if (CM != ~0u) {
597 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
598 getModule().setCodeModel(codeModel);
599 }
600 }
601
Sriraman Tallam80af0052018-02-23 21:27:33 +0000602 if (CodeGenOpts.NoPLT)
603 getModule().setRtLibUseGOT();
604
John McCall0bdb1fd2010-09-16 06:16:50 +0000605 SimplifyPersonality();
606
John McCall09ae0322010-07-06 23:57:41 +0000607 if (getCodeGenOpts().EmitDeclMetadata)
608 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000609
610 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000611 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000612
613 if (DebugInfo)
614 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000615
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +0000616 if (getCodeGenOpts().EmitVersionIdentMetadata)
617 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000618
Scott Linderde6beb02018-12-14 15:38:15 +0000619 if (!getCodeGenOpts().RecordCommandLine.empty())
620 EmitCommandLineMetadata();
621
Robert Lytton57765d52014-07-03 09:30:33 +0000622 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000623}
624
Alexey Bader364a1162017-06-20 14:30:18 +0000625void CodeGenModule::EmitOpenCLMetadata() {
626 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
627 // opencl.ocl.version named metadata node.
Anastasia Stulovaf61b5482019-05-30 15:18:07 +0000628 // C++ is backwards compatible with OpenCL v2.0.
629 // FIXME: We might need to add CXX version at some point too?
630 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
Alexey Bader364a1162017-06-20 14:30:18 +0000631 llvm::Metadata *OCLVerElts[] = {
632 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Anastasia Stulovaf61b5482019-05-30 15:18:07 +0000633 Int32Ty, Version / 100)),
Alexey Bader364a1162017-06-20 14:30:18 +0000634 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
Anastasia Stulovaf61b5482019-05-30 15:18:07 +0000635 Int32Ty, (Version % 100) / 10))};
Alexey Bader364a1162017-06-20 14:30:18 +0000636 llvm::NamedMDNode *OCLVerMD =
637 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
638 llvm::LLVMContext &Ctx = TheModule.getContext();
639 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
640}
641
Devang Patel945b8ae2011-03-23 16:29:39 +0000642void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
643 // Make sure that this type is translated.
644 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000645}
646
David Majnemer929025d2016-01-26 19:30:26 +0000647void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
648 // Make sure that this type is translated.
649 Types.RefreshTypeCacheForClass(RD);
650}
651
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000652llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
Dan Gohman947c9af2010-10-14 23:06:10 +0000653 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000654 return nullptr;
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000655 return TBAA->getTypeInfo(QTy);
Dan Gohman947c9af2010-10-14 23:06:10 +0000656}
657
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000658TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
Ivan A. Kosarev124a2182018-02-20 12:33:04 +0000659 if (!TBAA)
660 return TBAAAccessInfo();
661 return TBAA->getAccessInfo(AccessType);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000662}
663
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000664TBAAAccessInfo
665CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000666 if (!TBAA)
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000667 return TBAAAccessInfo();
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000668 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000669}
670
Dan Gohman22695fc2012-09-28 21:58:29 +0000671llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
672 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000673 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000674 return TBAA->getTBAAStructInfo(QTy);
675}
676
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000677llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
678 if (!TBAA)
679 return nullptr;
680 return TBAA->getBaseTypeInfo(QTy);
681}
682
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000683llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
Manman Renc451e572013-04-04 21:53:22 +0000684 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000685 return nullptr;
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000686 return TBAA->getAccessTagInfo(Info);
Manman Renc451e572013-04-04 21:53:22 +0000687}
688
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000689TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
690 TBAAAccessInfo TargetInfo) {
691 if (!TBAA)
692 return TBAAAccessInfo();
693 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
694}
695
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000696TBAAAccessInfo
697CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
698 TBAAAccessInfo InfoB) {
699 if (!TBAA)
700 return TBAAAccessInfo();
701 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
702}
703
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000704TBAAAccessInfo
705CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
706 TBAAAccessInfo SrcInfo) {
707 if (!TBAA)
708 return TBAAAccessInfo();
709 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
710}
711
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000712void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000713 TBAAAccessInfo TBAAInfo) {
714 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
715 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
Dan Gohman947c9af2010-10-14 23:06:10 +0000716}
717
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000718void CodeGenModule::DecorateInstructionWithInvariantGroup(
719 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000720 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
721 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000722}
723
Alp Toker29cb66b2014-01-26 06:17:37 +0000724void CodeGenModule::Error(SourceLocation loc, StringRef message) {
725 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
726 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000727}
728
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000729/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000730/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000731void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000732 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000733 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000734 std::string Msg = Type;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000735 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
736 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000737}
Chris Lattner41af8182007-12-02 06:27:33 +0000738
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000739/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000740/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000741void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000742 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000743 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000744 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000745 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000746}
747
John McCall23c29fe2011-06-24 21:55:10 +0000748llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
749 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
750}
751
Mike Stump11289f42009-09-09 15:08:12 +0000752void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000753 const NamedDecl *D) const {
Rafael Espindola123ce972018-01-24 18:58:32 +0000754 if (GV->hasDLLImportStorageClass())
755 return;
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000756 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000757 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000758 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000759 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000760 }
Rafael Espindola3f727a82018-03-14 18:14:46 +0000761 if (!D)
762 return;
Scott Linderbef26632019-01-28 17:12:19 +0000763 // Set visibility for definitions, and for declarations if requested globally
764 // or set explicitly.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000765 LinkageInfo LV = D->getLinkageAndVisibility();
Scott Linderbef26632019-01-28 17:12:19 +0000766 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
767 !GV->isDeclarationForLinker())
Rafael Espindola4a5da442013-02-27 02:56:45 +0000768 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000769}
770
Rafael Espindola699f5d62018-02-07 22:15:33 +0000771static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
Rafael Espindola3dd49812018-02-23 00:22:15 +0000772 llvm::GlobalValue *GV) {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000773 if (GV->hasLocalLinkage())
774 return true;
775
776 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
777 return true;
778
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000779 // DLLImport explicitly marks the GV as external.
780 if (GV->hasDLLImportStorageClass())
781 return false;
782
Rafael Espindola699f5d62018-02-07 22:15:33 +0000783 const llvm::Triple &TT = CGM.getTriple();
Martin Storsjo5ff7a8e2018-08-29 17:26:58 +0000784 if (TT.isWindowsGNUEnvironment()) {
785 // In MinGW, variables without DLLImport can still be automatically
786 // imported from a DLL by the linker; don't mark variables that
787 // potentially could come from another DLL as DSO local.
788 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
789 !GV->isThreadLocal())
790 return false;
791 }
Reid Kleckner6bf108d2019-05-07 23:06:21 +0000792
793 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
794 // remain unresolved in the link, they can be resolved to zero, which is
795 // outside the current DSO.
796 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
797 return false;
798
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000799 // Every other GV is local on COFF.
800 // Make an exception for windows OS in the triple: Some firmware builds use
801 // *-win32-macho triples. This (accidentally?) produced windows relocations
802 // without GOT tables in older clang versions; Keep this behaviour.
803 // FIXME: even thread local variables?
804 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
805 return true;
806
807 // Only handle COFF and ELF for now.
Rafael Espindola699f5d62018-02-07 22:15:33 +0000808 if (!TT.isOSBinFormatELF())
809 return false;
810
811 // If this is not an executable, don't assume anything is local.
812 const auto &CGOpts = CGM.getCodeGenOpts();
813 llvm::Reloc::Model RM = CGOpts.RelocationModel;
814 const auto &LOpts = CGM.getLangOpts();
Alexey Bataev6b21c4a2019-05-21 18:20:08 +0000815 if (RM != llvm::Reloc::Static && !LOpts.PIE && !LOpts.OpenMPIsDevice)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000816 return false;
817
818 // A definition cannot be preempted from an executable.
819 if (!GV->isDeclarationForLinker())
820 return true;
821
822 // Most PIC code sequences that assume that a symbol is local cannot produce a
823 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
824 // depended, it seems worth it to handle it here.
825 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
826 return false;
827
828 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
829 llvm::Triple::ArchType Arch = TT.getArch();
830 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
831 Arch == llvm::Triple::ppc64le)
832 return false;
833
834 // If we can use copy relocations we can assume it is local.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000835 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
836 if (!Var->isThreadLocal() &&
Rafael Espindola75e57362018-02-07 23:04:06 +0000837 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
838 return true;
Rafael Espindola699f5d62018-02-07 22:15:33 +0000839
840 // If we can use a plt entry as the symbol address we can assume it
841 // is local.
842 // FIXME: This should work for PIE, but the gold linker doesn't support it.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000843 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000844 return true;
845
846 // Otherwise don't assue it is local.
847 return false;
848}
849
Rafael Espindola3dd49812018-02-23 00:22:15 +0000850void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000851 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
Rafael Espindola699f5d62018-02-07 22:15:33 +0000852}
853
Rafael Espindolab7350042018-03-01 00:35:47 +0000854void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
855 GlobalDecl GD) const {
856 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
Reid Klecknerae9b0702018-03-16 19:40:50 +0000857 // C++ destructors have a few C++ ABI specific special cases.
Rafael Espindolab7350042018-03-01 00:35:47 +0000858 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
Reid Klecknerae9b0702018-03-16 19:40:50 +0000859 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
860 return;
Rafael Espindolab7350042018-03-01 00:35:47 +0000861 }
862 setDLLImportDLLExport(GV, D);
863}
864
865void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
866 const NamedDecl *D) const {
Rafael Espindola3f727a82018-03-14 18:14:46 +0000867 if (D && D->isExternallyVisible()) {
Rafael Espindolab7350042018-03-01 00:35:47 +0000868 if (D->hasAttr<DLLImportAttr>())
869 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
870 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
871 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
872 }
873}
874
875void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
876 GlobalDecl GD) const {
877 setDLLImportDLLExport(GV, GD);
878 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
879}
880
Rafael Espindola699f5d62018-02-07 22:15:33 +0000881void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
882 const NamedDecl *D) const {
Rafael Espindolab7350042018-03-01 00:35:47 +0000883 setDLLImportDLLExport(GV, D);
884 setGlobalVisibilityAndLocal(GV, D);
885}
886
887void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
888 const NamedDecl *D) const {
Rafael Espindola699f5d62018-02-07 22:15:33 +0000889 setGlobalVisibility(GV, D);
Rafael Espindola3dd49812018-02-23 00:22:15 +0000890 setDSOLocal(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000891}
892
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000893static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
894 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
895 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
896 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
897 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
898 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
899}
900
901static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
902 CodeGenOptions::TLSModel M) {
903 switch (M) {
904 case CodeGenOptions::GeneralDynamicTLSModel:
905 return llvm::GlobalVariable::GeneralDynamicTLSModel;
906 case CodeGenOptions::LocalDynamicTLSModel:
907 return llvm::GlobalVariable::LocalDynamicTLSModel;
908 case CodeGenOptions::InitialExecTLSModel:
909 return llvm::GlobalVariable::InitialExecTLSModel;
910 case CodeGenOptions::LocalExecTLSModel:
911 return llvm::GlobalVariable::LocalExecTLSModel;
912 }
913 llvm_unreachable("Invalid TLS model!");
914}
915
David Majnemerbb525f7c2014-10-15 22:38:23 +0000916void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000917 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000918
David Majnemerbb525f7c2014-10-15 22:38:23 +0000919 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000920 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000921
922 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000923 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000924 TLM = GetLLVMTLSModel(Attr->getModel());
925 }
926
927 GV->setThreadLocalMode(TLM);
928}
929
Erich Keane3efe0022018-07-20 14:13:28 +0000930static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
931 StringRef Name) {
932 const TargetInfo &Target = CGM.getTarget();
933 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
934}
935
936static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
937 const CPUSpecificAttr *Attr,
Erich Keanede6480a32018-11-13 15:48:08 +0000938 unsigned CPUIndex,
Erich Keane3efe0022018-07-20 14:13:28 +0000939 raw_ostream &Out) {
Erich Keane19a8adc2018-10-25 18:57:19 +0000940 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
941 // supported.
Erich Keane3efe0022018-07-20 14:13:28 +0000942 if (Attr)
Erich Keanede6480a32018-11-13 15:48:08 +0000943 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
Erich Keane19a8adc2018-10-25 18:57:19 +0000944 else if (CGM.getTarget().supportsIFunc())
Erich Keane3efe0022018-07-20 14:13:28 +0000945 Out << ".resolver";
946}
947
Erich Keane281d20b2018-01-08 21:34:17 +0000948static void AppendTargetMangling(const CodeGenModule &CGM,
949 const TargetAttr *Attr, raw_ostream &Out) {
950 if (Attr->isDefaultVersion())
951 return;
952
953 Out << '.';
Erich Keane3efe0022018-07-20 14:13:28 +0000954 const TargetInfo &Target = CGM.getTarget();
Erich Keane281d20b2018-01-08 21:34:17 +0000955 TargetAttr::ParsedTargetAttr Info =
956 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
Erich Keane3efe0022018-07-20 14:13:28 +0000957 // Multiversioning doesn't allow "no-${feature}", so we can
958 // only have "+" prefixes here.
959 assert(LHS.startswith("+") && RHS.startswith("+") &&
960 "Features should always have a prefix.");
961 return Target.multiVersionSortPriority(LHS.substr(1)) >
962 Target.multiVersionSortPriority(RHS.substr(1));
963 });
Erich Keane281d20b2018-01-08 21:34:17 +0000964
965 bool IsFirst = true;
966
967 if (!Info.Architecture.empty()) {
968 IsFirst = false;
969 Out << "arch_" << Info.Architecture;
970 }
971
972 for (StringRef Feat : Info.Features) {
973 if (!IsFirst)
974 Out << '_';
975 IsFirst = false;
976 Out << Feat.substr(1);
977 }
978}
979
980static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
981 const NamedDecl *ND,
Erich Keane3efe0022018-07-20 14:13:28 +0000982 bool OmitMultiVersionMangling = false) {
Erich Keane281d20b2018-01-08 21:34:17 +0000983 SmallString<256> Buffer;
984 llvm::raw_svector_ostream Out(Buffer);
985 MangleContext &MC = CGM.getCXXABI().getMangleContext();
986 if (MC.shouldMangleDeclName(ND)) {
987 llvm::raw_svector_ostream Out(Buffer);
988 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
989 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
990 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
991 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
992 else
993 MC.mangleName(ND, Out);
994 } else {
995 IdentifierInfo *II = ND->getIdentifier();
996 assert(II && "Attempt to mangle unnamed decl.");
997 const auto *FD = dyn_cast<FunctionDecl>(ND);
998
999 if (FD &&
1000 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1001 llvm::raw_svector_ostream Out(Buffer);
1002 Out << "__regcall3__" << II->getName();
1003 } else {
1004 Out << II->getName();
1005 }
1006 }
1007
1008 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Erich Keane3efe0022018-07-20 14:13:28 +00001009 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
Erich Keane5c0d1922018-11-28 18:34:14 +00001010 switch (FD->getMultiVersionKind()) {
1011 case MultiVersionKind::CPUDispatch:
1012 case MultiVersionKind::CPUSpecific:
Erich Keanede6480a32018-11-13 15:48:08 +00001013 AppendCPUSpecificCPUDispatchMangling(CGM,
1014 FD->getAttr<CPUSpecificAttr>(),
1015 GD.getMultiVersionIndex(), Out);
Erich Keane5c0d1922018-11-28 18:34:14 +00001016 break;
1017 case MultiVersionKind::Target:
Erich Keane3efe0022018-07-20 14:13:28 +00001018 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
Erich Keane5c0d1922018-11-28 18:34:14 +00001019 break;
1020 case MultiVersionKind::None:
1021 llvm_unreachable("None multiversion type isn't valid here");
1022 }
Erich Keane3efe0022018-07-20 14:13:28 +00001023 }
1024
Erich Keane281d20b2018-01-08 21:34:17 +00001025 return Out.str();
1026}
1027
1028void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1029 const FunctionDecl *FD) {
1030 if (!FD->isMultiVersion())
1031 return;
1032
1033 // Get the name of what this would be without the 'target' attribute. This
1034 // allows us to lookup the version that was emitted when this wasn't a
1035 // multiversion function.
1036 std::string NonTargetName =
Erich Keane3efe0022018-07-20 14:13:28 +00001037 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane281d20b2018-01-08 21:34:17 +00001038 GlobalDecl OtherGD;
1039 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1040 assert(OtherGD.getCanonicalDecl()
1041 .getDecl()
1042 ->getAsFunction()
1043 ->isMultiVersion() &&
1044 "Other GD should now be a multiversioned function");
1045 // OtherFD is the version of this function that was mangled BEFORE
1046 // becoming a MultiVersion function. It potentially needs to be updated.
Erich Keane7304f0a2018-11-28 20:58:43 +00001047 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1048 .getDecl()
1049 ->getAsFunction()
1050 ->getMostRecentDecl();
Erich Keane281d20b2018-01-08 21:34:17 +00001051 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1052 // This is so that if the initial version was already the 'default'
1053 // version, we don't try to update it.
1054 if (OtherName != NonTargetName) {
Erich Keanebc40c5c2018-01-09 01:09:12 +00001055 // Remove instead of erase, since others may have stored the StringRef
1056 // to this.
1057 const auto ExistingRecord = Manglings.find(NonTargetName);
1058 if (ExistingRecord != std::end(Manglings))
1059 Manglings.remove(&(*ExistingRecord));
Erich Keane281d20b2018-01-08 21:34:17 +00001060 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1061 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1062 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1063 Entry->setName(OtherName);
1064 }
1065 }
1066}
1067
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001068StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +00001069 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1070
1071 // Some ABIs don't have constructor variants. Make sure that base and
1072 // complete constructors get mangled the same.
1073 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1074 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1075 CXXCtorType OrigCtorType = GD.getCtorType();
1076 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1077 if (OrigCtorType == Ctor_Base)
1078 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1079 }
1080 }
1081
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001082 auto FoundName = MangledDeclNames.find(CanonicalGD);
1083 if (FoundName != MangledDeclNames.end())
1084 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001085
Richard Smith6d0e97a2014-08-02 00:50:16 +00001086 // Keep the first result in the case of a mangling collision.
Erich Keane281d20b2018-01-08 21:34:17 +00001087 const auto *ND = cast<NamedDecl>(GD.getDecl());
Yaxun Liue739ac02019-02-27 02:02:52 +00001088 std::string MangledName = getMangledNameImpl(*this, GD, ND);
1089
1090 // Postfix kernel stub names with .stub to differentiate them from kernel
1091 // names in device binaries. This is to facilitate the debugger to find
1092 // the correct symbols for kernels in the device binary.
1093 if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
1094 if (getLangOpts().HIP && !getLangOpts().CUDAIsDevice &&
1095 FD->hasAttr<CUDAGlobalAttr>())
1096 MangledName = MangledName + ".stub";
1097
1098 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001099 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +00001100}
1101
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001102StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1103 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001104 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1105 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +00001106
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001107 SmallString<256> Buffer;
1108 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +00001109 if (!D)
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001110 MangleCtx.mangleGlobalBlock(BD,
Fariborz Jahanian63628032012-06-26 16:06:38 +00001111 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001112 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001113 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001114 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001115 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001116 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001117 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001118
Richard Smith6d0e97a2014-08-02 00:50:16 +00001119 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1120 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +00001121}
1122
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001123llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +00001124 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +00001125}
1126
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001127/// AddGlobalCtor - Add a function to the list that will be called before
1128/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001129void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1130 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001131 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001132 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001133}
1134
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001135/// AddGlobalDtor - Add a function to the list that will be called
1136/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001137void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Akira Hatanaka617e2612018-04-17 18:41:52 +00001138 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1139 DtorsUsingAtExit[Priority].push_back(Dtor);
1140 return;
1141 }
1142
Daniel Dunbardec798b2009-01-13 02:25:00 +00001143 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +00001144 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001145}
1146
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001147void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001148 if (Fns.empty()) return;
1149
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001150 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +00001151 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Dylan McKay21e7f5e2018-11-09 17:15:06 +00001152 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1153 TheModule.getDataLayout().getProgramAddressSpace());
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001154
Reid Kleckner563f0e82014-05-23 21:13:45 +00001155 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1156 llvm::StructType *CtorStructTy = llvm::StructType::get(
Dylan McKay21e7f5e2018-11-09 17:15:06 +00001157 Int32Ty, CtorPFTy, VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001158
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001159 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +00001160 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001161 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +00001162 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001163 auto ctor = ctors.beginStruct(CtorStructTy);
1164 ctor.addInt(Int32Ty, I.Priority);
1165 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1166 if (I.AssociatedData)
1167 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1168 else
1169 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +00001170 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001171 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001172
John McCall18081af2016-11-19 20:12:25 +00001173 auto list =
1174 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1175 /*constant*/ false,
1176 llvm::GlobalValue::AppendingLinkage);
1177
1178 // The LTO linker doesn't seem to like it when we set an alignment
1179 // on appending variables. Take it off as a workaround.
1180 list->setAlignment(0);
1181
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001182 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001183}
1184
John McCalld4324142010-02-19 01:32:20 +00001185llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001186CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001187 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +00001188
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001189 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +00001190
Reid Klecknerae9b0702018-03-16 19:40:50 +00001191 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1192 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
Reid Klecknera283e482017-12-21 19:44:23 +00001193
Richard Smith5179eb72016-06-28 19:03:57 +00001194 if (isa<CXXConstructorDecl>(D) &&
1195 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1196 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1197 // Our approach to inheriting constructors is fundamentally different from
1198 // that used by the MS ABI, so keep our inheriting constructor thunks
1199 // internal rather than trying to pick an unambiguous mangling for them.
1200 return llvm::GlobalValue::InternalLinkage;
1201 }
1202
Hans Wennborg275efb92014-05-28 01:52:23 +00001203 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +00001204}
Nuno Lopesb6f79532008-06-08 15:45:52 +00001205
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001206llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001207 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1208 if (!MDS) return nullptr;
1209
Benjamin Kramer630cf8c2016-11-23 11:20:27 +00001210 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001211}
1212
Erich Keanede6480a32018-11-13 15:48:08 +00001213void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
Mike Stump11289f42009-09-09 15:08:12 +00001214 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001215 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001216 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00001217 llvm::AttributeList PAL;
Erich Keanede6480a32018-11-13 15:48:08 +00001218 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
Reid Klecknercdd26792017-04-18 23:50:03 +00001219 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001220 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +00001221}
1222
Anastasia Stulovae6cf6c72019-05-09 13:55:44 +00001223static void removeImageAccessQualifier(std::string& TyName) {
1224 std::string ReadOnlyQual("__read_only");
1225 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1226 if (ReadOnlyPos != std::string::npos)
1227 // "+ 1" for the space after access qualifier.
1228 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1229 else {
1230 std::string WriteOnlyQual("__write_only");
1231 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1232 if (WriteOnlyPos != std::string::npos)
1233 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1234 else {
1235 std::string ReadWriteQual("__read_write");
1236 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1237 if (ReadWritePos != std::string::npos)
1238 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1239 }
1240 }
1241}
1242
1243// Returns the address space id that should be produced to the
1244// kernel_arg_addr_space metadata. This is always fixed to the ids
1245// as specified in the SPIR 2.0 specification in order to differentiate
1246// for example in clGetKernelArgInfo() implementation between the address
1247// spaces with targets without unique mapping to the OpenCL address spaces
1248// (basically all single AS CPUs).
1249static unsigned ArgInfoAddressSpace(LangAS AS) {
1250 switch (AS) {
1251 case LangAS::opencl_global: return 1;
1252 case LangAS::opencl_constant: return 2;
1253 case LangAS::opencl_local: return 3;
1254 case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
1255 default:
1256 return 0; // Assume private.
1257 }
1258}
1259
1260void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
1261 const FunctionDecl *FD,
1262 CodeGenFunction *CGF) {
1263 assert(((FD && CGF) || (!FD && !CGF)) &&
1264 "Incorrect use - FD and CGF should either be both null or not!");
1265 // Create MDNodes that represent the kernel arg metadata.
1266 // Each MDNode is a list in the form of "key", N number of values which is
1267 // the same number of values as their are kernel arguments.
1268
1269 const PrintingPolicy &Policy = Context.getPrintingPolicy();
1270
1271 // MDNode for the kernel argument address space qualifiers.
1272 SmallVector<llvm::Metadata *, 8> addressQuals;
1273
1274 // MDNode for the kernel argument access qualifiers (images only).
1275 SmallVector<llvm::Metadata *, 8> accessQuals;
1276
1277 // MDNode for the kernel argument type names.
1278 SmallVector<llvm::Metadata *, 8> argTypeNames;
1279
1280 // MDNode for the kernel argument base type names.
1281 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1282
1283 // MDNode for the kernel argument type qualifiers.
1284 SmallVector<llvm::Metadata *, 8> argTypeQuals;
1285
1286 // MDNode for the kernel argument names.
1287 SmallVector<llvm::Metadata *, 8> argNames;
1288
1289 if (FD && CGF)
1290 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1291 const ParmVarDecl *parm = FD->getParamDecl(i);
1292 QualType ty = parm->getType();
1293 std::string typeQuals;
1294
1295 if (ty->isPointerType()) {
1296 QualType pointeeTy = ty->getPointeeType();
1297
1298 // Get address qualifier.
1299 addressQuals.push_back(
1300 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1301 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1302
1303 // Get argument type name.
1304 std::string typeName =
1305 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
1306
1307 // Turn "unsigned type" to "utype"
1308 std::string::size_type pos = typeName.find("unsigned");
1309 if (pointeeTy.isCanonical() && pos != std::string::npos)
1310 typeName.erase(pos + 1, 8);
1311
1312 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1313
1314 std::string baseTypeName =
1315 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
1316 Policy) +
1317 "*";
1318
1319 // Turn "unsigned type" to "utype"
1320 pos = baseTypeName.find("unsigned");
1321 if (pos != std::string::npos)
1322 baseTypeName.erase(pos + 1, 8);
1323
1324 argBaseTypeNames.push_back(
1325 llvm::MDString::get(VMContext, baseTypeName));
1326
1327 // Get argument type qualifiers:
1328 if (ty.isRestrictQualified())
1329 typeQuals = "restrict";
1330 if (pointeeTy.isConstQualified() ||
1331 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1332 typeQuals += typeQuals.empty() ? "const" : " const";
1333 if (pointeeTy.isVolatileQualified())
1334 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1335 } else {
1336 uint32_t AddrSpc = 0;
1337 bool isPipe = ty->isPipeType();
1338 if (ty->isImageType() || isPipe)
1339 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1340
1341 addressQuals.push_back(
1342 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1343
1344 // Get argument type name.
1345 std::string typeName;
1346 if (isPipe)
1347 typeName = ty.getCanonicalType()
1348 ->getAs<PipeType>()
1349 ->getElementType()
1350 .getAsString(Policy);
1351 else
1352 typeName = ty.getUnqualifiedType().getAsString(Policy);
1353
1354 // Turn "unsigned type" to "utype"
1355 std::string::size_type pos = typeName.find("unsigned");
1356 if (ty.isCanonical() && pos != std::string::npos)
1357 typeName.erase(pos + 1, 8);
1358
1359 std::string baseTypeName;
1360 if (isPipe)
1361 baseTypeName = ty.getCanonicalType()
1362 ->getAs<PipeType>()
1363 ->getElementType()
1364 .getCanonicalType()
1365 .getAsString(Policy);
1366 else
1367 baseTypeName =
1368 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
1369
1370 // Remove access qualifiers on images
1371 // (as they are inseparable from type in clang implementation,
1372 // but OpenCL spec provides a special query to get access qualifier
1373 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1374 if (ty->isImageType()) {
1375 removeImageAccessQualifier(typeName);
1376 removeImageAccessQualifier(baseTypeName);
1377 }
1378
1379 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1380
1381 // Turn "unsigned type" to "utype"
1382 pos = baseTypeName.find("unsigned");
1383 if (pos != std::string::npos)
1384 baseTypeName.erase(pos + 1, 8);
1385
1386 argBaseTypeNames.push_back(
1387 llvm::MDString::get(VMContext, baseTypeName));
1388
1389 if (isPipe)
1390 typeQuals = "pipe";
1391 }
1392
1393 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1394
1395 // Get image and pipe access qualifier:
1396 if (ty->isImageType() || ty->isPipeType()) {
1397 const Decl *PDecl = parm;
1398 if (auto *TD = dyn_cast<TypedefType>(ty))
1399 PDecl = TD->getDecl();
1400 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1401 if (A && A->isWriteOnly())
1402 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1403 else if (A && A->isReadWrite())
1404 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1405 else
1406 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1407 } else
1408 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1409
1410 // Get argument name.
1411 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1412 }
1413
1414 Fn->setMetadata("kernel_arg_addr_space",
1415 llvm::MDNode::get(VMContext, addressQuals));
1416 Fn->setMetadata("kernel_arg_access_qual",
1417 llvm::MDNode::get(VMContext, accessQuals));
1418 Fn->setMetadata("kernel_arg_type",
1419 llvm::MDNode::get(VMContext, argTypeNames));
1420 Fn->setMetadata("kernel_arg_base_type",
1421 llvm::MDNode::get(VMContext, argBaseTypeNames));
1422 Fn->setMetadata("kernel_arg_type_qual",
1423 llvm::MDNode::get(VMContext, argTypeQuals));
1424 if (getCodeGenOpts().EmitOpenCLArgMetadata)
1425 Fn->setMetadata("kernel_arg_name",
1426 llvm::MDNode::get(VMContext, argNames));
1427}
1428
John McCall9b0a7ce2011-10-02 01:16:38 +00001429/// Determines whether the language options require us to model
1430/// unwind exceptions. We treat -fexceptions as mandating this
1431/// except under the fragile ObjC ABI with only ObjC exceptions
1432/// enabled. This means, for example, that C with -fexceptions
1433/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001434static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +00001435 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001436 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +00001437
1438 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001439 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +00001440
1441 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001442 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +00001443 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +00001444 }
1445
1446 return true;
1447}
1448
Peter Collingbournee44acad2018-06-26 02:15:47 +00001449static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1450 const CXXMethodDecl *MD) {
1451 // Check that the type metadata can ever actually be used by a call.
1452 if (!CGM.getCodeGenOpts().LTOUnit ||
1453 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1454 return false;
1455
1456 // Only functions whose address can be taken with a member function pointer
1457 // need this sort of type metadata.
1458 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1459 !isa<CXXDestructorDecl>(MD);
1460}
1461
1462std::vector<const CXXRecordDecl *>
1463CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1464 llvm::SetVector<const CXXRecordDecl *> MostBases;
1465
1466 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1467 CollectMostBases = [&](const CXXRecordDecl *RD) {
1468 if (RD->getNumBases() == 0)
1469 MostBases.insert(RD);
1470 for (const CXXBaseSpecifier &B : RD->bases())
1471 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1472 };
1473 CollectMostBases(RD);
1474 return MostBases.takeVector();
1475}
1476
Daniel Dunbar38932572009-04-14 08:05:55 +00001477void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1478 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001479 llvm::AttrBuilder B;
1480
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001481 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001482 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001483
David Blaikiebbafb8a2012-03-11 07:00:24 +00001484 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001485 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +00001486
Manoj Gupta4fbf84c2018-05-09 21:41:18 +00001487 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1488 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1489 B.addAttribute(llvm::Attribute::StackProtect);
1490 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1491 B.addAttribute(llvm::Attribute::StackProtectStrong);
1492 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1493 B.addAttribute(llvm::Attribute::StackProtectReq);
1494 }
Akira Hatanaka200500d2015-10-08 19:30:57 +00001495
1496 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001497 // If we don't have a declaration to control inlining, the function isn't
1498 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1499 // disabled, mark the function as noinline.
1500 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1501 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1502 B.addAttribute(llvm::Attribute::NoInline);
1503
Reid Kleckneree4930b2017-05-02 22:07:37 +00001504 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +00001505 return;
1506 }
1507
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001508 // Track whether we need to add the optnone LLVM attribute,
1509 // starting with the default for this optimization level.
1510 bool ShouldAddOptNone =
1511 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1512 // We can't add optnone in the following cases, it won't pass the verifier.
1513 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1514 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1515 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1516
1517 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001518 B.addAttribute(llvm::Attribute::OptimizeNone);
1519
1520 // OptimizeNone implies noinline; we should not be inlining such functions.
1521 B.addAttribute(llvm::Attribute::NoInline);
1522 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1523 "OptimizeNone and AlwaysInline on same function!");
1524
1525 // We still need to handle naked functions even though optnone subsumes
1526 // much of their semantics.
1527 if (D->hasAttr<NakedAttr>())
1528 B.addAttribute(llvm::Attribute::Naked);
1529
1530 // OptimizeNone wins over OptimizeForSize and MinSize.
1531 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1532 F->removeFnAttr(llvm::Attribute::MinSize);
1533 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +00001534 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001535 B.addAttribute(llvm::Attribute::Naked);
1536 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001537 } else if (D->hasAttr<NoDuplicateAttr>()) {
1538 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001539 } else if (D->hasAttr<NoInlineAttr>()) {
1540 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +00001541 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +00001542 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001543 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001544 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001545 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1546 // If we're not inlining, then force everything that isn't always_inline to
1547 // carry an explicit noinline attribute.
1548 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1549 B.addAttribute(llvm::Attribute::NoInline);
1550 } else {
1551 // Otherwise, propagate the inline hint attribute and potentially use its
1552 // absence to mark things as noinline.
1553 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Richard Trieu9b36a9c2018-10-23 01:26:28 +00001554 // Search function and template pattern redeclarations for inline.
1555 auto CheckForInline = [](const FunctionDecl *FD) {
1556 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1557 return Redecl->isInlineSpecified();
1558 };
1559 if (any_of(FD->redecls(), CheckRedeclForInline))
1560 return true;
1561 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1562 if (!Pattern)
1563 return false;
1564 return any_of(Pattern->redecls(), CheckRedeclForInline);
1565 };
1566 if (CheckForInline(FD)) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001567 B.addAttribute(llvm::Attribute::InlineHint);
1568 } else if (CodeGenOpts.getInlining() ==
1569 CodeGenOptions::OnlyHintInlining &&
1570 !FD->isInlined() &&
1571 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1572 B.addAttribute(llvm::Attribute::NoInline);
1573 }
1574 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001575 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001576
Chandler Carruthfcd33142016-12-23 01:24:49 +00001577 // Add other optimization related attributes if we are optimizing this
1578 // function.
1579 if (!D->hasAttr<OptimizeNoneAttr>()) {
1580 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001581 if (!ShouldAddOptNone)
1582 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001583 B.addAttribute(llvm::Attribute::Cold);
1584 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001585
Chandler Carruthfcd33142016-12-23 01:24:49 +00001586 if (D->hasAttr<MinSizeAttr>())
1587 B.addAttribute(llvm::Attribute::MinSize);
1588 }
Richard Smithb555a762012-09-28 22:46:07 +00001589
Reid Kleckneree4930b2017-05-02 22:07:37 +00001590 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001591
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001592 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1593 if (alignment)
1594 F->setAlignment(alignment);
1595
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001596 if (!D->hasAttr<AlignedAttr>())
1597 if (LangOpts.FunctionAlignment)
1598 F->setAlignment(1 << LangOpts.FunctionAlignment);
1599
Dan Gohmanc2853072015-09-03 22:51:53 +00001600 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1601 // reserve a bit for differentiating between virtual and non-virtual member
1602 // functions. If the current target's C++ ABI requires this and this is a
1603 // member function, set its alignment accordingly.
1604 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1605 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1606 F->setAlignment(2);
1607 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001608
1609 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1610 if (CodeGenOpts.SanitizeCfiCrossDso)
1611 if (auto *FD = dyn_cast<FunctionDecl>(D))
Peter Collingbournee44acad2018-06-26 02:15:47 +00001612 CreateFunctionTypeMetadataForIcall(FD, F);
1613
1614 // Emit type metadata on member functions for member function pointer checks.
1615 // These are only ever necessary on definitions; we're guaranteed that the
1616 // definition will be present in the LTO unit as a result of LTO visibility.
1617 auto *MD = dyn_cast<CXXMethodDecl>(D);
1618 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1619 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1620 llvm::Metadata *Id =
1621 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1622 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1623 F->addTypeMetadata(0, Id);
1624 }
1625 }
Daniel Dunbar449a3392008-09-04 23:41:35 +00001626}
1627
Rafael Espindola75c649c2018-03-01 00:06:55 +00001628void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1629 const Decl *D = GD.getDecl();
Rafael Espindolab7350042018-03-01 00:35:47 +00001630 if (dyn_cast_or_null<NamedDecl>(D))
1631 setGVProperties(GV, GD);
John McCall457a04e2010-10-22 21:05:15 +00001632 else
1633 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001634
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001635 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001636 addUsedGlobal(GV);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001637
1638 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1639 const auto *VD = cast<VarDecl>(D);
Erich Keane85822b32018-10-25 19:13:46 +00001640 if (VD->getType().isConstQualified() &&
1641 VD->getStorageDuration() == SD_Static)
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001642 addUsedGlobal(GV);
1643 }
Rafael Espindola502f65a2014-05-05 20:21:03 +00001644}
1645
Erich Keanede6480a32018-11-13 15:48:08 +00001646bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
Erich Keane93e58662018-02-12 17:01:41 +00001647 llvm::AttrBuilder &Attrs) {
1648 // Add target-cpu and target-features attributes to functions. If
1649 // we have a decl for the function and it has a target attribute then
1650 // parse that and add it to the feature set.
1651 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1652 std::vector<std::string> Features;
Erich Keanede6480a32018-11-13 15:48:08 +00001653 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
Erich Keane93e58662018-02-12 17:01:41 +00001654 FD = FD ? FD->getMostRecentDecl() : FD;
1655 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
Erich Keane3efe0022018-07-20 14:13:28 +00001656 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
Erich Keane93e58662018-02-12 17:01:41 +00001657 bool AddedAttr = false;
Erich Keane3efe0022018-07-20 14:13:28 +00001658 if (TD || SD) {
Erich Keane93e58662018-02-12 17:01:41 +00001659 llvm::StringMap<bool> FeatureMap;
Erich Keanede6480a32018-11-13 15:48:08 +00001660 getFunctionFeatureMap(FeatureMap, GD);
Erich Keane93e58662018-02-12 17:01:41 +00001661
1662 // Produce the canonical string for this set of features.
1663 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1664 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1665
1666 // Now add the target-cpu and target-features to the function.
1667 // While we populated the feature map above, we still need to
1668 // get and parse the target attribute so we can get the cpu for
1669 // the function.
Erich Keane3efe0022018-07-20 14:13:28 +00001670 if (TD) {
1671 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1672 if (ParsedAttr.Architecture != "" &&
1673 getTarget().isValidCPUName(ParsedAttr.Architecture))
1674 TargetCPU = ParsedAttr.Architecture;
1675 }
Erich Keane93e58662018-02-12 17:01:41 +00001676 } else {
1677 // Otherwise just add the existing target cpu and target features to the
1678 // function.
1679 Features = getTarget().getTargetOpts().Features;
1680 }
1681
1682 if (TargetCPU != "") {
1683 Attrs.addAttribute("target-cpu", TargetCPU);
1684 AddedAttr = true;
1685 }
1686 if (!Features.empty()) {
Fangrui Song55fab262018-09-26 22:16:28 +00001687 llvm::sort(Features);
Erich Keane93e58662018-02-12 17:01:41 +00001688 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1689 AddedAttr = true;
1690 }
1691
1692 return AddedAttr;
1693}
1694
Rafael Espindola285271c2018-02-28 23:54:23 +00001695void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001696 llvm::GlobalObject *GO) {
Rafael Espindola285271c2018-02-28 23:54:23 +00001697 const Decl *D = GD.getDecl();
Rafael Espindola75c649c2018-03-01 00:06:55 +00001698 SetCommonAttributes(GD, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001699
Javed Absar2a67c9e2017-06-05 10:11:57 +00001700 if (D) {
1701 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1702 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1703 GV->addAttribute("bss-section", SA->getName());
1704 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1705 GV->addAttribute("data-section", SA->getName());
1706 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1707 GV->addAttribute("rodata-section", SA->getName());
1708 }
1709
1710 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1711 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
Erich Keane30994d22018-02-08 20:04:22 +00001712 if (!D->getAttr<SectionAttr>())
1713 F->addFnAttr("implicit-section-name", SA->getName());
Erich Keane93e58662018-02-12 17:01:41 +00001714
1715 llvm::AttrBuilder Attrs;
Erich Keanede6480a32018-11-13 15:48:08 +00001716 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
Erich Keane93e58662018-02-12 17:01:41 +00001717 // We know that GetCPUAndFeaturesAttributes will always have the
1718 // newest set, since it has the newest possible FunctionDecl, so the
1719 // new ones should replace the old.
1720 F->removeFnAttr("target-cpu");
1721 F->removeFnAttr("target-features");
1722 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1723 }
Javed Absar2a67c9e2017-06-05 10:11:57 +00001724 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001725
Erich Keane7963e8b2018-07-18 20:04:48 +00001726 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1727 GO->setSection(CSA->getName());
1728 else if (const auto *SA = D->getAttr<SectionAttr>())
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001729 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001730 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001731
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001732 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001733}
1734
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001735void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001736 llvm::Function *F,
1737 const CGFunctionInfo &FI) {
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001738 const Decl *D = GD.getDecl();
Erich Keanede6480a32018-11-13 15:48:08 +00001739 SetLLVMFunctionAttributes(GD, FI, F);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001740 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001741
1742 F->setLinkage(llvm::Function::InternalLinkage);
1743
Rafael Espindola285271c2018-02-28 23:54:23 +00001744 setNonAliasAttributes(GD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001745}
1746
Rafael Espindolab7350042018-03-01 00:35:47 +00001747static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
David Majnemerf6acb762014-04-25 17:07:16 +00001748 // Set linkage and visibility in case we never see a definition.
1749 LinkageInfo LV = ND->getLinkageAndVisibility();
Rafael Espindolab7350042018-03-01 00:35:47 +00001750 // Don't set internal linkage on declarations.
1751 // "extern_weak" is overloaded in LLVM; we probably should have
1752 // separate linkage types for this.
1753 if (isExternallyVisible(LV.getLinkage()) &&
1754 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1755 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001756}
1757
Peter Collingbournee44acad2018-06-26 02:15:47 +00001758void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1759 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001760 // Only if we are checking indirect calls.
1761 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1762 return;
1763
Peter Collingbournee44acad2018-06-26 02:15:47 +00001764 // Non-static class methods are handled via vtable or member function pointer
1765 // checks elsewhere.
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001766 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1767 return;
1768
1769 // Additionally, if building with cross-DSO support...
1770 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001771 // Skip available_externally functions. They won't be codegen'ed in the
1772 // current module anyway.
1773 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1774 return;
1775 }
1776
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001777 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001778 F->addTypeMetadata(0, MD);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001779 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001780
1781 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001782 if (CodeGenOpts.SanitizeCfiCrossDso)
1783 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1784 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001785}
1786
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001787void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1788 bool IsIncompleteFunction,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001789 bool IsThunk) {
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001790
Pete Cooper2f1637a2015-05-20 17:17:45 +00001791 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001792 // If this is an intrinsic function, set the function's attributes
1793 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001794 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001795 return;
1796 }
1797
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001798 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001799
Scott Linderfb59fef2019-04-23 21:50:11 +00001800 if (!IsIncompleteFunction)
Erich Keanede6480a32018-11-13 15:48:08 +00001801 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +00001802
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001803 // Add the Returned attribute for "this", except for iOS 5 and earlier
1804 // where substantial code, including the libstdc++ dylib, was compiled with
1805 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001806 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001807 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001808 assert(!F->arg_empty() &&
1809 F->arg_begin()->getType()
1810 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1811 "unexpected this return");
1812 F->addAttribute(1, llvm::Attribute::Returned);
1813 }
1814
Daniel Dunbar38932572009-04-14 08:05:55 +00001815 // Only a few attributes are set on declarations; these may later be
1816 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001817
Jake Ehrlichba874ad2017-11-29 00:54:20 +00001818 setLinkageForGV(F, FD);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001819 setGVProperties(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001820
Scott Linderfb59fef2019-04-23 21:50:11 +00001821 // Setup target-specific attributes.
1822 if (!IsIncompleteFunction && F->isDeclaration())
1823 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1824
Erich Keane7963e8b2018-07-18 20:04:48 +00001825 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1826 F->setSection(CSA->getName());
1827 else if (const auto *SA = FD->getAttr<SectionAttr>())
1828 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001829
Richard Smith351241c2016-04-07 21:46:12 +00001830 if (FD->isReplaceableGlobalAllocationFunction()) {
1831 // A replaceable global allocation function does not act like a builtin by
1832 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001833 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001834 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001835
Richard Smith351241c2016-04-07 21:46:12 +00001836 // A sane operator new returns a non-aliasing pointer.
1837 // FIXME: Also add NonNull attribute to the return value
1838 // for the non-nothrow forms?
1839 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1840 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1841 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001842 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001843 llvm::Attribute::NoAlias);
1844 }
1845
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001846 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001847 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001848 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1849 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001850 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001851
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001852 // Don't emit entries for function declarations in the cross-DSO mode. This
1853 // is handled with better precision by the receiving DSO.
1854 if (!CodeGenOpts.SanitizeCfiCrossDso)
Peter Collingbournee44acad2018-06-26 02:15:47 +00001855 CreateFunctionTypeMetadataForIcall(FD, F);
Alexey Bataevb952e632017-12-15 16:28:31 +00001856
1857 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1858 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001859
1860 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
1861 // Annotate the callback behavior as metadata:
1862 // - The callback callee (as argument number).
1863 // - The callback payloads (as argument numbers).
1864 llvm::LLVMContext &Ctx = F->getContext();
1865 llvm::MDBuilder MDB(Ctx);
1866
1867 // The payload indices are all but the first one in the encoding. The first
1868 // identifies the callback callee.
1869 int CalleeIdx = *CB->encoding_begin();
1870 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
1871 F->addMetadata(llvm::LLVMContext::MD_callback,
1872 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1873 CalleeIdx, PayloadIndices,
1874 /* VarArgsArePassed */ false)}));
1875 }
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001876}
1877
Rafael Espindola060062a2014-03-06 22:15:10 +00001878void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001879 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001880 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001881 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001882}
1883
Rafael Espindola060062a2014-03-06 22:15:10 +00001884void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1885 assert(!GV->isDeclaration() &&
1886 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001887 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001888}
1889
1890static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001891 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001892 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001893 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001894 return;
1895
Rafael Espindola060062a2014-03-06 22:15:10 +00001896 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001897 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001898 UsedArray.resize(List.size());
1899 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001900 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001901 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1902 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001903 }
Mike Stump11289f42009-09-09 15:08:12 +00001904
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001905 if (UsedArray.empty())
1906 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001907 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001908
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001909 auto *GV = new llvm::GlobalVariable(
1910 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1911 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001912
1913 GV->setSection("llvm.metadata");
1914}
1915
Rafael Espindola060062a2014-03-06 22:15:10 +00001916void CodeGenModule::emitLLVMUsed() {
1917 emitUsed(*this, "llvm.used", LLVMUsed);
1918 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1919}
1920
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001921void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001922 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001923 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1924}
1925
Aaron Ballman5d041be2013-06-04 02:07:14 +00001926void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1927 llvm::SmallString<32> Opt;
1928 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001929 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001930 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1931}
1932
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001933void CodeGenModule::AddDependentLib(StringRef Lib) {
Ben Dunbobbin1d165152019-05-17 03:44:15 +00001934 auto &C = getLLVMContext();
1935 if (getTarget().getTriple().isOSBinFormatELF()) {
1936 ELFDependentLibraries.push_back(
1937 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
1938 return;
1939 }
1940
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001941 llvm::SmallString<24> Opt;
1942 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001943 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Ben Dunbobbin1d165152019-05-17 03:44:15 +00001944 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001945}
1946
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001947/// Add link options implied by the given module, including modules
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001948/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001949static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001950 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001951 llvm::SmallPtrSet<Module *, 16> &Visited) {
1952 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001953 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001954 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001955 }
1956
1957 // Import this module's dependencies.
1958 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001959 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001960 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001961 }
1962
1963 // Add linker options to link against the libraries/frameworks
1964 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001965 llvm::LLVMContext &Context = CGM.getLLVMContext();
Saleem Abdulrasool175890e2019-01-05 19:27:12 +00001966 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00001967
1968 // For modules that use export_as for linking, use that module
1969 // name instead.
1970 if (Mod->UseExportAsModuleLinkName)
1971 return;
1972
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001973 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001974 // Link against a framework. Frameworks are currently Darwin only, so we
1975 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001976 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001977 llvm::Metadata *Args[2] = {
1978 llvm::MDString::get(Context, "-framework"),
1979 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001980
1981 Metadata.push_back(llvm::MDNode::get(Context, Args));
1982 continue;
1983 }
1984
1985 // Link against a library.
Ben Dunbobbin1d165152019-05-17 03:44:15 +00001986 if (IsELF) {
Saleem Abdulrasool175890e2019-01-05 19:27:12 +00001987 llvm::Metadata *Args[2] = {
1988 llvm::MDString::get(Context, "lib"),
1989 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
1990 };
1991 Metadata.push_back(llvm::MDNode::get(Context, Args));
1992 } else {
1993 llvm::SmallString<24> Opt;
1994 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1995 Mod->LinkLibraries[I - 1].Library, Opt);
1996 auto *OptString = llvm::MDString::get(Context, Opt);
1997 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1998 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001999 }
2000}
2001
2002void CodeGenModule::EmitModuleLinkOptions() {
2003 // Collect the set of all of the modules we want to visit to emit link
2004 // options, which is essentially the imported modules and all of their
2005 // non-explicit child modules.
2006 llvm::SetVector<clang::Module *> LinkModules;
2007 llvm::SmallPtrSet<clang::Module *, 16> Visited;
2008 SmallVector<clang::Module *, 16> Stack;
2009
2010 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00002011 for (Module *M : ImportedModules) {
2012 // Do not add any link flags when an implementation TU of a module imports
2013 // a header of that same module.
2014 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2015 !getLangOpts().isCompilingModule())
2016 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00002017 if (Visited.insert(M).second)
2018 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00002019 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002020
2021 // Find all of the modules to import, making a little effort to prune
2022 // non-leaf modules.
2023 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00002024 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002025
2026 bool AnyChildren = false;
2027
2028 // Visit the submodules of this module.
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00002029 for (const auto &SM : Mod->submodules()) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002030 // Skip explicit children; they need to be explicitly imported to be
2031 // linked against.
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00002032 if (SM->IsExplicit)
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002033 continue;
2034
Saleem Abdulrasoolda32d7f2019-01-05 18:39:32 +00002035 if (Visited.insert(SM).second) {
2036 Stack.push_back(SM);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002037 AnyChildren = true;
2038 }
2039 }
2040
2041 // We didn't find any children, so add this module to the list of
2042 // modules to link against.
2043 if (!AnyChildren) {
2044 LinkModules.insert(Mod);
2045 }
2046 }
2047
2048 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002049 // order. We don't do anything to try to order import link flags with respect
2050 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00002051 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002052 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00002053 for (Module *M : LinkModules)
2054 if (Visited.insert(M).second)
2055 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00002056 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002057 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002058
Daniel Dunbar69e47462013-01-17 01:35:06 +00002059 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00002060 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2061 for (auto *MD : LinkerOptionsMetadata)
2062 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00002063}
2064
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002065void CodeGenModule::EmitDeferred() {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002066 // Emit deferred declare target declarations.
2067 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2068 getOpenMPRuntime().emitDeferredTargetDecls();
2069
Chris Lattner45470942009-03-21 09:44:56 +00002070 // Emit code for any potentially referenced deferred decls. Since a
2071 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002072 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00002073
Rafael Espindolae5df59f2015-01-22 00:24:57 +00002074 if (!DeferredVTables.empty()) {
2075 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00002076
Eric Christopherd160c502016-01-29 01:35:53 +00002077 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00002078 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00002079 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00002080 assert(DeferredVTables.empty());
2081 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00002082
Eric Christopherd160c502016-01-29 01:35:53 +00002083 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00002084 if (DeferredDeclsToEmit.empty())
2085 return;
John McCall6bd2a892013-01-25 22:31:03 +00002086
Rafael Espindolae5df59f2015-01-22 00:24:57 +00002087 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2088 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00002089 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00002090 CurDeclsToEmit.swap(DeferredDeclsToEmit);
2091
Sanjoy Das70a60512017-05-01 06:12:13 +00002092 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002093 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2094 // to get GlobalValue with exactly the type we need, not something that
2095 // might had been created for another decl with the same mangled name but
2096 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002097 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00002098 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002099
2100 // In case of different address spaces, we may still get a cast, even with
2101 // IsForDefinition equal to true. Query mangled names table to get
2102 // GlobalValue.
2103 if (!GV)
2104 GV = GetGlobalValue(getMangledName(D));
2105
2106 // Make sure GetGlobalValue returned non-null.
2107 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002108
John McCallc2af9392010-05-27 01:45:30 +00002109 // Check to see if we've already emitted this. This is necessary
2110 // for a couple of reasons: first, decls can end up in the
2111 // deferred-decls queue multiple times, and second, decls can end
2112 // up with definitions in unusual ways (e.g. by an extern inline
2113 // function acquiring a strong function redefinition). Just
2114 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002115 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00002116 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002117
Chris Lattner45470942009-03-21 09:44:56 +00002118 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002119 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00002120
2121 // If we found out that we need to emit more decls, do that recursively.
2122 // This has the advantage that the decls are emitted in a DFS and related
2123 // ones are close together, which is convenient for testing.
2124 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2125 EmitDeferred();
2126 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2127 }
Chris Lattner45470942009-03-21 09:44:56 +00002128 }
Chris Lattnerbed31442007-05-28 01:07:47 +00002129}
Chris Lattner09153c02007-06-22 18:48:09 +00002130
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002131void CodeGenModule::EmitVTablesOpportunistically() {
2132 // Try to emit external vtables as available_externally if they have emitted
2133 // all inlined virtual functions. It runs after EmitDeferred() and therefore
2134 // is not allowed to create new references to things that need to be emitted
2135 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2136
Piotr Padlewski05547742017-06-01 09:24:36 +00002137 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2138 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002139
2140 for (const CXXRecordDecl *RD : OpportunisticVTables) {
2141 assert(getVTables().isVTableExternal(RD) &&
2142 "This queue should only contain external vtables");
2143 if (getCXXABI().canSpeculativelyEmitVTable(RD))
2144 VTables.GenerateClassData(RD);
2145 }
2146 OpportunisticVTables.clear();
2147}
2148
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002149void CodeGenModule::EmitGlobalAnnotations() {
2150 if (Annotations.empty())
2151 return;
2152
2153 // Create a new global variable for the ConstantStruct in the Module.
2154 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2155 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002156 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2157 llvm::GlobalValue::AppendingLinkage,
2158 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002159 gv->setSection(AnnotationSection);
2160}
2161
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002162llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00002163 llvm::Constant *&AStr = AnnotationStrings[Str];
2164 if (AStr)
2165 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002166
2167 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00002168 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002169 auto *gv =
2170 new llvm::GlobalVariable(getModule(), s->getType(), true,
2171 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002172 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002173 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00002174 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002175 return gv;
2176}
2177
2178llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2179 SourceManager &SM = getContext().getSourceManager();
2180 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2181 if (PLoc.isValid())
2182 return EmitAnnotationString(PLoc.getFilename());
2183 return EmitAnnotationString(SM.getBufferName(Loc));
2184}
2185
2186llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2187 SourceManager &SM = getContext().getSourceManager();
2188 PresumedLoc PLoc = SM.getPresumedLoc(L);
2189 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2190 SM.getExpansionLineNumber(L);
2191 return llvm::ConstantInt::get(Int32Ty, LineNo);
2192}
2193
Mike Stump11289f42009-09-09 15:08:12 +00002194llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00002195 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002196 SourceLocation L) {
2197 // Get the globals for file name, annotation, and the line number.
2198 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2199 *UnitGV = EmitAnnotationUnit(L),
2200 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00002201
Daniel Dunbar346892a2009-04-14 22:41:13 +00002202 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00002203 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002204 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
2205 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2206 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2207 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00002208 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00002209 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00002210}
2211
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002212void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2213 llvm::GlobalValue *GV) {
2214 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2215 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002216 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2217 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002218}
2219
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002220bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
2221 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002222 SourceLocation Loc) const {
2223 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2224 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002225 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002226 return true;
2227 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00002228 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002229 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002230 // If location is unknown, this may be a compiler-generated function. Assume
2231 // it's located in the main file.
2232 auto &SM = Context.getSourceManager();
2233 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002234 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00002235 }
2236 return false;
2237}
2238
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002239bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
2240 SourceLocation Loc, QualType Ty,
2241 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002242 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002243 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +00002244 (SanitizerKind::Address | SanitizerKind::KernelAddress |
2245 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002246 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002247 return false;
2248 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002249 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002250 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002251 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002252 return true;
2253 // Check global type.
2254 if (!Ty.isNull()) {
2255 // Drill down the array types: if global variable of a fixed type is
2256 // blacklisted, we also don't instrument arrays of them.
2257 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2258 Ty = AT->getElementType();
2259 Ty = Ty.getCanonicalType().getUnqualifiedType();
2260 // We allow to blacklist only record types (classes, structs etc.)
2261 if (Ty->isRecordType()) {
2262 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00002263 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00002264 return true;
2265 }
2266 }
2267 return false;
2268}
2269
Dean Michael Berris835832d2017-03-30 00:29:36 +00002270bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2271 StringRef Category) const {
Dean Michael Berris835832d2017-03-30 00:29:36 +00002272 const auto &XRayFilter = getContext().getXRayFilter();
2273 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00002274 auto Attr = ImbueAttr::NONE;
Dean Michael Berris835832d2017-03-30 00:29:36 +00002275 if (Loc.isValid())
2276 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2277 if (Attr == ImbueAttr::NONE)
2278 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2279 switch (Attr) {
2280 case ImbueAttr::NONE:
2281 return false;
2282 case ImbueAttr::ALWAYS:
2283 Fn->addFnAttr("function-instrument", "xray-always");
2284 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00002285 case ImbueAttr::ALWAYS_ARG1:
2286 Fn->addFnAttr("function-instrument", "xray-always");
2287 Fn->addFnAttr("xray-log-args", "1");
2288 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00002289 case ImbueAttr::NEVER:
2290 Fn->addFnAttr("function-instrument", "xray-never");
2291 break;
2292 }
2293 return true;
2294}
2295
Hans Wennborg43a0f992015-01-10 01:19:48 +00002296bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00002297 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002298 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00002299 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002300
Elizabeth Andrews6593df22018-08-22 19:05:19 +00002301 if (CodeGenOpts.KeepStaticConsts) {
2302 const auto *VD = dyn_cast<VarDecl>(Global);
2303 if (VD && VD->getType().isConstQualified() &&
Erich Keane85822b32018-10-25 19:13:46 +00002304 VD->getStorageDuration() == SD_Static)
Elizabeth Andrews6593df22018-08-22 19:05:19 +00002305 return true;
2306 }
2307
Hans Wennborg43a0f992015-01-10 01:19:48 +00002308 return getContext().DeclMustBeEmitted(Global);
2309}
2310
2311bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2312 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
2313 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2314 // Implicit template instantiations may change linkage if they are later
2315 // explicitly instantiated, so they should not be emitted eagerly.
2316 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00002317 if (const auto *VD = dyn_cast<VarDecl>(Global))
2318 if (Context.getInlineVariableDefinitionKind(VD) ==
2319 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2320 // A definition of an inline constexpr static data member may change
2321 // linkage later if it's redeclared outside the class.
2322 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00002323 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2324 // codegen for global variables, because they may be marked as threadprivate.
2325 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
Alexey Bataev96edb2e2018-06-25 15:32:05 +00002326 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
Alexey Bataevd01b7492018-08-15 19:45:12 +00002327 !isTypeConstant(Global->getType(), false) &&
2328 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
Samuel Antaof8b50122015-07-13 22:54:53 +00002329 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00002330
2331 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002332}
2333
John McCall7f416cc2015-09-08 08:05:57 +00002334ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00002335 const CXXUuidofExpr* E) {
2336 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2337 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00002338 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00002339 std::string Name = "_GUID_" + Uuid.lower();
2340 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00002341
David Majnemer65687602016-03-27 04:46:14 +00002342 // The UUID descriptor should be pointer aligned.
2343 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00002344
Nico Webercf4ff5862012-10-11 10:13:44 +00002345 // Look for an existing global.
2346 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00002347 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002348
Nico Weber17d3a2c2014-09-08 16:26:36 +00002349 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00002350 assert(Init && "failed to initialize as constant");
2351
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002352 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00002353 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00002354 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002355 if (supportsCOMDAT())
2356 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolaca08d242018-03-20 15:42:58 +00002357 setDSOLocal(GV);
John McCall7f416cc2015-09-08 08:05:57 +00002358 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002359}
2360
John McCall7f416cc2015-09-08 08:05:57 +00002361ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002362 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2363 assert(AA && "No alias?");
2364
John McCall7f416cc2015-09-08 08:05:57 +00002365 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002366 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002367
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002368 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00002369 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002370 if (Entry) {
2371 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00002372 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2373 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002374 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002375
2376 llvm::Constant *Aliasee;
2377 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002378 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2379 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00002380 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002381 else
John McCall7ec50432010-03-19 23:29:14 +00002382 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00002383 llvm::PointerType::getUnqual(DeclTy),
2384 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002385
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002386 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002387 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2388 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002389
John McCall7f416cc2015-09-08 08:05:57 +00002390 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002391}
2392
Chris Lattnere0be0df2009-05-12 21:21:08 +00002393void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002394 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002395
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002396 // Weak references don't produce any output by themselves.
2397 if (Global->hasAttr<WeakRefAttr>())
2398 return;
2399
Chris Lattner54041692009-03-22 21:47:11 +00002400 // If this is an alias definition (which otherwise looks like a declaration)
2401 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002402 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00002403 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002404
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002405 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2406 if (Global->hasAttr<IFuncAttr>())
2407 return emitIFuncDefinition(GD);
2408
Erich Keane3efe0022018-07-20 14:13:28 +00002409 // If this is a cpu_dispatch multiversion function, emit the resolver.
2410 if (Global->hasAttr<CPUDispatchAttr>())
2411 return emitCPUDispatchDefinition(GD);
2412
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002413 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002414 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00002415 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002416 if (!Global->hasAttr<CUDADeviceAttr>() &&
2417 !Global->hasAttr<CUDAGlobalAttr>() &&
2418 !Global->hasAttr<CUDAConstantAttr>() &&
2419 !Global->hasAttr<CUDASharedAttr>())
2420 return;
2421 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00002422 // We need to emit host-side 'shadows' for all global
2423 // device-side variables because the CUDA runtime needs their
2424 // size and host-side address in order to provide access to
2425 // their device-side incarnations.
2426
2427 // So device-only functions are the only things we skip.
2428 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2429 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002430 return;
Artem Belevich42e19492016-03-02 18:28:50 +00002431
2432 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2433 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002434 }
2435 }
2436
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002437 if (LangOpts.OpenMP) {
2438 // If this is OpenMP device, check if it is legal to emit this global
2439 // normally.
2440 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2441 return;
2442 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2443 if (MustBeEmitted(Global))
2444 EmitOMPDeclareReduction(DRD);
2445 return;
Michael Kruse251e1482019-02-01 20:25:04 +00002446 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2447 if (MustBeEmitted(Global))
2448 EmitOMPDeclareMapper(DMD);
2449 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002450 }
2451 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002452
Chris Lattner45470942009-03-21 09:44:56 +00002453 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002454 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002455 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002456 if (!FD->doesThisDeclarationHaveABody()) {
2457 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2458 return;
2459
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002460 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00002461
2462 // Compute the function info and LLVM type.
2463 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2464 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2465
2466 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2467 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002468 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002469 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002470 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002471 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002472 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich99535772018-12-22 01:11:09 +00002473 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00002474 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00002475 if (LangOpts.OpenMP) {
2476 // Emit declaration of the must-be-emitted declare target variable.
2477 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2478 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2479 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
2480 (void)GetAddrOfGlobalVar(VD);
2481 } else {
2482 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
2483 "link claue expected.");
2484 (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
2485 }
2486 return;
2487 }
2488 }
Richard Smithd9b90092016-07-02 01:32:16 +00002489 // If this declaration may have caused an inline variable definition to
2490 // change linkage, make sure that it's emitted.
2491 if (Context.getInlineVariableDefinitionKind(VD) ==
2492 ASTContext::InlineVariableDefinitionKind::Strong)
2493 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00002494 return;
Richard Smithd9b90092016-07-02 01:32:16 +00002495 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002496 }
2497
Hans Wennborg43a0f992015-01-10 01:19:48 +00002498 // Defer code generation to first use when possible, e.g. if this is an inline
2499 // function. If the global must always be emitted, do it eagerly if possible
2500 // to benefit from cache locality.
2501 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002502 // Emit the definition if it can't be deferred.
2503 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002504 return;
2505 }
John McCall70013b62010-07-15 23:40:35 +00002506
2507 // If we're deferring emission of a C++ variable with an
2508 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002509 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00002510 cast<VarDecl>(Global)->hasInit()) {
2511 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00002512 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00002513 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00002514
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002515 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00002516 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00002517 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00002518 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002519 } else if (MustBeEmitted(Global)) {
2520 // The value must be emitted, but cannot be emitted eagerly.
2521 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00002522 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002523 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002524 // Otherwise, remember that we saw a deferred decl with this name. The
2525 // first use of the mangled name will cause it to move into
2526 // DeferredDeclsToEmit.
2527 DeferredDecls[MangledName] = GD;
2528 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002529}
2530
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002531// Check if T is a class type with a destructor that's not dllimport.
2532static bool HasNonDllImportDtor(QualType T) {
2533 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2534 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2535 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2536 return true;
2537
2538 return false;
2539}
2540
Rafael Espindolac5941352011-10-26 20:41:06 +00002541namespace {
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002542 struct FunctionIsDirectlyRecursive
2543 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
Rafael Espindolac5941352011-10-26 20:41:06 +00002544 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002545 const Builtin::Context &BI;
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002546 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
2547 : Name(N), BI(C) {}
Rafael Espindolac5941352011-10-26 20:41:06 +00002548
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002549 bool VisitCallExpr(const CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002550 const FunctionDecl *FD = E->getDirectCallee();
2551 if (!FD)
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002552 return false;
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002553 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2554 if (Attr && Name == Attr->getLabel())
2555 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002556 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00002557 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002558 return false;
Eric Christopher02d5d862015-08-06 01:01:12 +00002559 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00002560 if (BuiltinName.startswith("__builtin_") &&
2561 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002562 return true;
Rafael Espindolac5941352011-10-26 20:41:06 +00002563 }
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002564 return false;
2565 }
2566
2567 bool VisitStmt(const Stmt *S) {
2568 for (const Stmt *Child : S->children())
2569 if (Child && this->Visit(Child))
2570 return true;
2571 return false;
Rafael Espindolac5941352011-10-26 20:41:06 +00002572 }
2573 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002574
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002575 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002576 struct DLLImportFunctionVisitor
2577 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2578 bool SafeToInline = true;
2579
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002580 bool shouldVisitImplicitCode() const { return true; }
2581
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002582 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002583 if (VD->getTLSKind()) {
2584 // A thread-local variable cannot be imported.
2585 SafeToInline = false;
2586 return SafeToInline;
2587 }
2588
2589 // A variable definition might imply a destructor call.
2590 if (VD->isThisDeclarationADefinition())
2591 SafeToInline = !HasNonDllImportDtor(VD->getType());
2592
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002593 return SafeToInline;
2594 }
2595
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002596 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2597 if (const auto *D = E->getTemporary()->getDestructor())
2598 SafeToInline = D->hasAttr<DLLImportAttr>();
2599 return SafeToInline;
2600 }
2601
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002602 bool VisitDeclRefExpr(DeclRefExpr *E) {
2603 ValueDecl *VD = E->getDecl();
2604 if (isa<FunctionDecl>(VD))
2605 SafeToInline = VD->hasAttr<DLLImportAttr>();
2606 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2607 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2608 return SafeToInline;
2609 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002610
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002611 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2612 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2613 return SafeToInline;
2614 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002615
Hans Wennborg251c2042017-01-23 23:57:50 +00002616 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2617 CXXMethodDecl *M = E->getMethodDecl();
2618 if (!M) {
2619 // Call through a pointer to member function. This is safe to inline.
2620 SafeToInline = true;
2621 } else {
2622 SafeToInline = M->hasAttr<DLLImportAttr>();
2623 }
2624 return SafeToInline;
2625 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002626
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002627 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2628 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2629 return SafeToInline;
2630 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002631
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002632 bool VisitCXXNewExpr(CXXNewExpr *E) {
2633 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2634 return SafeToInline;
2635 }
2636 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002637}
Rafael Espindolac5941352011-10-26 20:41:06 +00002638
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002639// isTriviallyRecursive - Check if this function calls another
2640// decl that, because of the asm attribute or the other decl being a builtin,
2641// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00002642bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002643CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2644 StringRef Name;
2645 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00002646 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002647 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2648 if (!Attr)
2649 return false;
2650 Name = Attr->getLabel();
2651 } else {
2652 Name = FD->getName();
2653 }
Rafael Espindolac5941352011-10-26 20:41:06 +00002654
David Majnemer64b0bdf2015-06-30 04:41:18 +00002655 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Reid Klecknerf09c19c2019-01-25 19:18:40 +00002656 const Stmt *Body = FD->getBody();
2657 return Body ? Walker.Visit(Body) : false;
Rafael Espindolac5941352011-10-26 20:41:06 +00002658}
2659
Hans Wennborg93f75472016-09-13 21:08:20 +00002660bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002661 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00002662 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002663 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00002664 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00002665 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002666
2667 if (F->hasAttr<DLLImportAttr>()) {
2668 // Check whether it would be safe to inline this dllimport function.
2669 DLLImportFunctionVisitor Visitor;
2670 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2671 if (!Visitor.SafeToInline)
2672 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00002673
2674 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2675 // Implicit destructor invocations aren't captured in the AST, so the
2676 // check above can't see them. Check for them manually here.
2677 for (const Decl *Member : Dtor->getParent()->decls())
2678 if (isa<FieldDecl>(Member))
2679 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2680 return false;
2681 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2682 if (HasNonDllImportDtor(B.getType()))
2683 return false;
2684 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002685 }
2686
Rafael Espindolac5941352011-10-26 20:41:06 +00002687 // PR9614. Avoid cases where the source code is lying to us. An available
2688 // externally function should have an equivalent function somewhere else,
2689 // but a function that calls itself is clearly not equivalent to the real
2690 // implementation.
2691 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002692 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00002693}
2694
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002695bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2696 return CodeGenOpts.OptimizationLevel > 0;
2697}
2698
Erich Keanede6480a32018-11-13 15:48:08 +00002699void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2700 llvm::GlobalValue *GV) {
2701 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2702
2703 if (FD->isCPUSpecificMultiVersion()) {
2704 auto *Spec = FD->getAttr<CPUSpecificAttr>();
2705 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2706 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2707 // Requires multiple emits.
2708 } else
2709 EmitGlobalFunctionDefinition(GD, GV);
2710}
2711
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002712void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002713 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002714
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002715 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00002716 Context.getSourceManager(),
2717 "Generating code for declaration");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002718
Erich Keanede6480a32018-11-13 15:48:08 +00002719 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002720 // At -O0, don't generate IR for functions with available_externally
Douglas Gregora700f682010-07-13 06:02:28 +00002721 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002722 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002723 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002724
Lubos Lunakab8cde42019-05-12 10:39:21 +00002725 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
2726 std::string Name;
2727 llvm::raw_string_ostream OS(Name);
2728 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
2729 /*Qualified=*/true);
2730 return Name;
2731 });
Anton Afanasyevd880de22019-03-30 08:42:48 +00002732
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002733 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002734 // Make sure to emit the definition(s) before we emit the thunks.
2735 // This is necessary for the generation of certain thunks.
Peter Collingbourned1c5b282019-03-22 23:05:10 +00002736 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2737 ABI->emitCXXStructor(GD);
Erich Keanede6480a32018-11-13 15:48:08 +00002738 else if (FD->isMultiVersion())
2739 EmitMultiVersionFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002740 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002741 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002742
Douglas Gregora700f682010-07-13 06:02:28 +00002743 if (Method->isVirtual())
2744 getVTables().EmitThunks(GD);
2745
Eli Friedman49a94b12011-05-06 17:27:27 +00002746 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002747 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002748
Erich Keanede6480a32018-11-13 15:48:08 +00002749 if (FD->isMultiVersion())
2750 return EmitMultiVersionFunctionDefinition(GD, GV);
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002751 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002752 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002753
2754 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002755 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002756
David Blaikie83d382b2011-09-23 05:06:16 +00002757 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002758}
2759
Andrey Bokhankocab58582015-08-31 13:20:44 +00002760static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2761 llvm::Function *NewFn);
2762
Erich Keanef353ae12018-09-13 16:58:24 +00002763static unsigned
2764TargetMVPriority(const TargetInfo &TI,
2765 const CodeGenFunction::MultiVersionResolverOption &RO) {
2766 unsigned Priority = 0;
2767 for (StringRef Feat : RO.Conditions.Features)
2768 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2769
2770 if (!RO.Conditions.Architecture.empty())
2771 Priority = std::max(
2772 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2773 return Priority;
2774}
2775
Erich Keane281d20b2018-01-08 21:34:17 +00002776void CodeGenModule::emitMultiVersionFunctions() {
2777 for (GlobalDecl GD : MultiVersionFuncs) {
Erich Keanef353ae12018-09-13 16:58:24 +00002778 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane281d20b2018-01-08 21:34:17 +00002779 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2780 getContext().forEachMultiversionedFunctionVersion(
2781 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2782 GlobalDecl CurGD{
2783 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2784 StringRef MangledName = getMangledName(CurGD);
2785 llvm::Constant *Func = GetGlobalValue(MangledName);
2786 if (!Func) {
2787 if (CurFD->isDefined()) {
2788 EmitGlobalFunctionDefinition(CurGD, nullptr);
2789 Func = GetGlobalValue(MangledName);
2790 } else {
2791 const CGFunctionInfo &FI =
2792 getTypes().arrangeGlobalDeclaration(GD);
2793 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2794 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2795 /*DontDefer=*/false, ForDefinition);
2796 }
2797 assert(Func && "This should have just been created");
2798 }
Erich Keanef353ae12018-09-13 16:58:24 +00002799
2800 const auto *TA = CurFD->getAttr<TargetAttr>();
2801 llvm::SmallVector<StringRef, 8> Feats;
2802 TA->getAddedFeatures(Feats);
2803
2804 Options.emplace_back(cast<llvm::Function>(Func),
2805 TA->getArchitecture(), Feats);
Erich Keane281d20b2018-01-08 21:34:17 +00002806 });
2807
Erich Keane19a8adc2018-10-25 18:57:19 +00002808 llvm::Function *ResolverFunc;
2809 const TargetInfo &TI = getTarget();
2810
2811 if (TI.supportsIFunc() || FD->isTargetMultiVersion())
2812 ResolverFunc = cast<llvm::Function>(
2813 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2814 else
2815 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2816
Erich Keane0a6fde42018-01-16 19:49:52 +00002817 if (supportsCOMDAT())
2818 ResolverFunc->setComdat(
2819 getModule().getOrInsertComdat(ResolverFunc->getName()));
Erich Keanef353ae12018-09-13 16:58:24 +00002820
Fangrui Song899d1392019-04-24 14:43:05 +00002821 llvm::stable_sort(
2822 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2823 const CodeGenFunction::MultiVersionResolverOption &RHS) {
Erich Keanef353ae12018-09-13 16:58:24 +00002824 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2825 });
Erich Keane281d20b2018-01-08 21:34:17 +00002826 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002827 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane281d20b2018-01-08 21:34:17 +00002828 }
2829}
2830
Erich Keane3efe0022018-07-20 14:13:28 +00002831void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2832 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2833 assert(FD && "Not a FunctionDecl?");
2834 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2835 assert(DD && "Not a cpu_dispatch Function?");
James Y Knight916db652019-02-02 01:48:23 +00002836 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
Erich Keane9e94c182018-11-01 15:11:41 +00002837
2838 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2839 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
2840 DeclTy = getTypes().GetFunctionType(FInfo);
2841 }
Erich Keane3efe0022018-07-20 14:13:28 +00002842
2843 StringRef ResolverName = getMangledName(GD);
Erich Keane19a8adc2018-10-25 18:57:19 +00002844
2845 llvm::Type *ResolverType;
2846 GlobalDecl ResolverGD;
2847 if (getTarget().supportsIFunc())
2848 ResolverType = llvm::FunctionType::get(
2849 llvm::PointerType::get(DeclTy,
2850 Context.getTargetAddressSpace(FD->getType())),
2851 false);
2852 else {
2853 ResolverType = DeclTy;
2854 ResolverGD = GD;
2855 }
2856
2857 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2858 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
Erich Keane3efe0022018-07-20 14:13:28 +00002859
Erich Keanef353ae12018-09-13 16:58:24 +00002860 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane3efe0022018-07-20 14:13:28 +00002861 const TargetInfo &Target = getTarget();
Erich Keanede6480a32018-11-13 15:48:08 +00002862 unsigned Index = 0;
Erich Keane3efe0022018-07-20 14:13:28 +00002863 for (const IdentifierInfo *II : DD->cpus()) {
2864 // Get the name of the target function so we can look it up/create it.
2865 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2866 getCPUSpecificMangling(*this, II->getName());
Erich Keanede6480a32018-11-13 15:48:08 +00002867
2868 llvm::Constant *Func = GetGlobalValue(MangledName);
2869
Erich Keane248ed072018-12-07 15:31:23 +00002870 if (!Func) {
2871 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
2872 if (ExistingDecl.getDecl() &&
2873 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
2874 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
2875 Func = GetGlobalValue(MangledName);
2876 } else {
2877 if (!ExistingDecl.getDecl())
2878 ExistingDecl = GD.getWithMultiVersionIndex(Index);
2879
Erich Keanede6480a32018-11-13 15:48:08 +00002880 Func = GetOrCreateLLVMFunction(
Erich Keane248ed072018-12-07 15:31:23 +00002881 MangledName, DeclTy, ExistingDecl,
Erich Keanede6480a32018-11-13 15:48:08 +00002882 /*ForVTable=*/false, /*DontDefer=*/true,
2883 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
Erich Keane248ed072018-12-07 15:31:23 +00002884 }
2885 }
Erich Keanede6480a32018-11-13 15:48:08 +00002886
Erich Keane3efe0022018-07-20 14:13:28 +00002887 llvm::SmallVector<StringRef, 32> Features;
2888 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2889 llvm::transform(Features, Features.begin(),
2890 [](StringRef Str) { return Str.substr(1); });
2891 Features.erase(std::remove_if(
2892 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2893 return !Target.validateCpuSupports(Feat);
2894 }), Features.end());
Erich Keanef353ae12018-09-13 16:58:24 +00002895 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
Erich Keanede6480a32018-11-13 15:48:08 +00002896 ++Index;
Erich Keane3efe0022018-07-20 14:13:28 +00002897 }
2898
2899 llvm::sort(
Fangrui Song1d38c132018-09-30 21:41:11 +00002900 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
2901 const CodeGenFunction::MultiVersionResolverOption &RHS) {
Erich Keanef353ae12018-09-13 16:58:24 +00002902 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
2903 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
2904 });
Erich Keane44731c52018-11-01 12:50:37 +00002905
2906 // If the list contains multiple 'default' versions, such as when it contains
2907 // 'pentium' and 'generic', don't emit the call to the generic one (since we
2908 // always run on at least a 'pentium'). We do this by deleting the 'least
2909 // advanced' (read, lowest mangling letter).
2910 while (Options.size() > 1 &&
2911 CodeGenFunction::GetX86CpuSupportsMask(
2912 (Options.end() - 2)->Conditions.Features) == 0) {
2913 StringRef LHSName = (Options.end() - 2)->Function->getName();
2914 StringRef RHSName = (Options.end() - 1)->Function->getName();
2915 if (LHSName.compare(RHSName) < 0)
2916 Options.erase(Options.end() - 2);
2917 else
2918 Options.erase(Options.end() - 1);
2919 }
2920
Erich Keane3efe0022018-07-20 14:13:28 +00002921 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002922 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane3efe0022018-07-20 14:13:28 +00002923}
2924
Erich Keane19a8adc2018-10-25 18:57:19 +00002925/// If a dispatcher for the specified mangled name is not in the module, create
2926/// and return an llvm Function with the specified type.
2927llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
2928 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
Erich Keane3efe0022018-07-20 14:13:28 +00002929 std::string MangledName =
2930 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane19a8adc2018-10-25 18:57:19 +00002931
2932 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
2933 // a separate resolver).
2934 std::string ResolverName = MangledName;
2935 if (getTarget().supportsIFunc())
2936 ResolverName += ".ifunc";
2937 else if (FD->isTargetMultiVersion())
2938 ResolverName += ".resolver";
2939
2940 // If this already exists, just return that one.
2941 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
2942 return ResolverGV;
Erich Keane281d20b2018-01-08 21:34:17 +00002943
2944 // Since this is the first time we've created this IFunc, make sure
2945 // that we put this multiversioned function into the list to be
Erich Keane3efe0022018-07-20 14:13:28 +00002946 // replaced later if necessary (target multiversioning only).
2947 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2948 MultiVersionFuncs.push_back(GD);
Erich Keane281d20b2018-01-08 21:34:17 +00002949
Erich Keane19a8adc2018-10-25 18:57:19 +00002950 if (getTarget().supportsIFunc()) {
2951 llvm::Type *ResolverType = llvm::FunctionType::get(
2952 llvm::PointerType::get(
2953 DeclTy, getContext().getTargetAddressSpace(FD->getType())),
2954 false);
2955 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2956 MangledName + ".resolver", ResolverType, GlobalDecl{},
2957 /*ForVTable=*/false);
2958 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2959 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2960 GIF->setName(ResolverName);
2961 SetCommonAttributes(FD, GIF);
Erich Keane281d20b2018-01-08 21:34:17 +00002962
Erich Keane19a8adc2018-10-25 18:57:19 +00002963 return GIF;
2964 }
2965
2966 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
2967 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
2968 assert(isa<llvm::GlobalValue>(Resolver) &&
2969 "Resolver should be created for the first time");
2970 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
2971 return Resolver;
Erich Keane281d20b2018-01-08 21:34:17 +00002972}
2973
Chris Lattnerd4808922009-03-22 21:03:39 +00002974/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2975/// module, create and return an llvm Function with the specified type. If there
2976/// is something in the module with the specified name, return it potentially
2977/// bitcasted to the right type.
2978///
2979/// If D is non-null, it specifies a decl that correspond to this. This is used
2980/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002981llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2982 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2983 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2984 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002985 const Decl *D = GD.getDecl();
2986
Erich Keane281d20b2018-01-08 21:34:17 +00002987 // Any attempts to use a MultiVersion function should result in retrieving
2988 // the iFunc instead. Name Mangling will handle the rest of the changes.
2989 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002990 // For the device mark the function as one that should be emitted.
2991 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
Alexey Bataev6d944102018-05-02 15:45:28 +00002992 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002993 !DontDefer && !IsForDefinition) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002994 if (const FunctionDecl *FDDef = FD->getDefinition()) {
2995 GlobalDecl GDDef;
2996 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2997 GDDef = GlobalDecl(CD, GD.getCtorType());
2998 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2999 GDDef = GlobalDecl(DD, GD.getDtorType());
3000 else
3001 GDDef = GlobalDecl(FDDef);
3002 EmitGlobal(GDDef);
3003 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00003004 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003005
Erich Keane3efe0022018-07-20 14:13:28 +00003006 if (FD->isMultiVersion()) {
3007 const auto *TA = FD->getAttr<TargetAttr>();
3008 if (TA && TA->isDefaultVersion())
3009 UpdateMultiVersionNames(GD, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00003010 if (!IsForDefinition)
Erich Keane19a8adc2018-10-25 18:57:19 +00003011 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00003012 }
3013 }
3014
Chris Lattnera85d68e2009-03-21 09:25:43 +00003015 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00003016 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00003017 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00003018 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00003019 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00003020 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00003021 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00003022 }
3023
Hans Wennborg0a20f542014-08-29 00:16:06 +00003024 // Handle dropped DLL attributes.
Rafael Espindolac9643d82018-03-29 16:45:18 +00003025 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Hans Wennborg0a20f542014-08-29 00:16:06 +00003026 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
Rafael Espindolac9643d82018-03-29 16:45:18 +00003027 setDSOLocal(Entry);
3028 }
Hans Wennborg0a20f542014-08-29 00:16:06 +00003029
Andrey Bokhankocab58582015-08-31 13:20:44 +00003030 // If there are two attempts to define the same mangled name, issue an
3031 // error.
3032 if (IsForDefinition && !Entry->isDeclaration()) {
3033 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003034 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3035 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003036 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3037 (GD.getCanonicalDecl().getDecl() !=
3038 OtherGD.getCanonicalDecl().getDecl()) &&
3039 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00003040 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3041 << MangledName;
Andrey Bokhankocab58582015-08-31 13:20:44 +00003042 getDiags().Report(OtherGD.getDecl()->getLocation(),
3043 diag::note_previous_definition);
3044 }
3045 }
3046
3047 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3048 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00003049 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00003050 }
Mike Stump11289f42009-09-09 15:08:12 +00003051
Chris Lattnera85d68e2009-03-21 09:25:43 +00003052 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003053 // (If function is requested for a definition, we always need to create a new
3054 // function, not just return a bitcast.)
3055 if (!IsForDefinition)
3056 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00003057 }
Mike Stump11289f42009-09-09 15:08:12 +00003058
Eli Friedmancc522d92009-11-09 05:07:37 +00003059 // This function doesn't have a complete type (for example, the return
3060 // type is an incomplete struct). Use a fake type instead, and make
3061 // sure not to try to set attributes.
3062 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00003063
Chris Lattner2192fe52011-07-18 04:24:23 +00003064 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00003065 if (isa<llvm::FunctionType>(Ty)) {
3066 FTy = cast<llvm::FunctionType>(Ty);
3067 } else {
John McCall9dc0db22011-05-15 01:53:33 +00003068 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00003069 IsIncompleteFunction = true;
3070 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00003071
3072 llvm::Function *F =
3073 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3074 Entry ? StringRef() : MangledName, &getModule());
3075
3076 // If we already created a function with the same mangled name (but different
3077 // type) before, take its name and add it to the list of functions to be
3078 // replaced with F at the end of CodeGen.
3079 //
3080 // This happens if there is a prototype for a function (e.g. "int f()") and
3081 // then a definition of a different type (e.g. "int f(int x)").
3082 if (Entry) {
3083 F->takeName(Entry);
3084
3085 // This might be an implementation of a function without a prototype, in
3086 // which case, try to do special replacement of calls which match the new
3087 // prototype. The really key thing here is that we also potentially drop
3088 // arguments from the call site so as to make a direct call, which makes the
3089 // inliner happier and suppresses a number of optimizer warnings (!) about
3090 // dropping arguments.
3091 if (!Entry->use_empty()) {
3092 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3093 Entry->removeDeadConstantUsers();
3094 }
3095
3096 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3097 F, Entry->getType()->getElementType()->getPointerTo());
3098 addGlobalValReplacement(Entry, BC);
3099 }
3100
John McCall7ec50432010-03-19 23:29:14 +00003101 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00003102 if (D)
Rafael Espindoladeb10be2018-02-07 19:04:41 +00003103 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00003104 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3105 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00003106 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00003107 }
Eli Friedmancc522d92009-11-09 05:07:37 +00003108
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003109 if (!DontDefer) {
3110 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3111 // each other bottoming out with the base dtor. Therefore we emit non-base
3112 // dtors on usage, even if there is no dtor definition in the TU.
3113 if (D && isa<CXXDestructorDecl>(D) &&
3114 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3115 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00003116 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00003117
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003118 // This is the first use or definition of a mangled name. If there is a
3119 // deferred decl with this name, remember that we need to emit it at the end
3120 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00003121 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003122 if (DDI != DeferredDecls.end()) {
3123 // Move the potentially referenced deferred decl to the
3124 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3125 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00003126 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003127 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003128
3129 // Otherwise, there are cases we have to worry about where we're
3130 // using a declaration for which we must emit a definition but where
3131 // we might not find a top-level definition:
3132 // - member functions defined inline in their classes
3133 // - friend functions defined inline in some class
3134 // - special member functions with implicit definitions
3135 // If we ever change our AST traversal to walk into class methods,
3136 // this will be unnecessary.
3137 //
3138 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00003139 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003140 } else if (getLangOpts().CPlusPlus && D) {
3141 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00003142 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3143 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003144 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00003145 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00003146 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003147 break;
3148 }
John McCall357d0f32010-12-15 04:00:32 +00003149 }
Richard Smith46bb5812014-08-01 01:56:39 +00003150 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003151 }
Chris Lattner45470942009-03-21 09:44:56 +00003152 }
Mike Stump11289f42009-09-09 15:08:12 +00003153
John McCalld06fb862010-04-28 00:00:30 +00003154 // Make sure the result is of the requested type.
3155 if (!IsIncompleteFunction) {
3156 assert(F->getType()->getElementType() == Ty);
3157 return F;
3158 }
3159
Chris Lattnera5f58b02011-07-09 17:41:47 +00003160 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00003161 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00003162}
3163
Chris Lattnerd4808922009-03-22 21:03:39 +00003164/// GetAddrOfFunction - Return the address of the given function. If Ty is
3165/// non-null, then this function will use the specified type if it has to
3166/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00003167llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00003168 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003169 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00003170 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00003171 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00003172 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003173 if (!Ty) {
3174 const auto *FD = cast<FunctionDecl>(GD.getDecl());
James Y Knight916db652019-02-02 01:48:23 +00003175 Ty = getTypes().ConvertType(FD->getType());
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00003176 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00003177
Reid Kleckner28103252018-03-16 22:20:57 +00003178 // Devirtualized destructor calls may come through here instead of via
3179 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3180 // of the complete destructor when necessary.
3181 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3182 if (getTarget().getCXXABI().isMicrosoft() &&
3183 GD.getDtorType() == Dtor_Complete &&
3184 DD->getParent()->getNumVBases() == 0)
3185 GD = GlobalDecl(DD, Dtor_Base);
3186 }
3187
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003188 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003189 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00003190 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00003191 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00003192}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003193
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003194static const FunctionDecl *
3195GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3196 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3197 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3198
3199 IdentifierInfo &CII = C.Idents.get(Name);
3200 for (const auto &Result : DC->lookup(&CII))
3201 if (const auto FD = dyn_cast<FunctionDecl>(Result))
3202 return FD;
3203
3204 if (!C.getLangOpts().CPlusPlus)
3205 return nullptr;
3206
3207 // Demangle the premangled name from getTerminateFn()
3208 IdentifierInfo &CXXII =
Reid Klecknerfb931542018-03-16 20:36:49 +00003209 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003210 ? C.Idents.get("terminate")
3211 : C.Idents.get(Name);
3212
3213 for (const auto &N : {"__cxxabiv1", "std"}) {
3214 IdentifierInfo &NS = C.Idents.get(N);
3215 for (const auto &Result : DC->lookup(&NS)) {
3216 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3217 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
3218 for (const auto &Result : LSD->lookup(&NS))
3219 if ((ND = dyn_cast<NamespaceDecl>(Result)))
3220 break;
3221
3222 if (ND)
3223 for (const auto &Result : ND->lookup(&CXXII))
3224 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3225 return FD;
3226 }
3227 }
3228
3229 return nullptr;
3230}
3231
Chris Lattnerd4808922009-03-22 21:03:39 +00003232/// CreateRuntimeFunction - Create a new runtime function with the specified
3233/// type and name.
James Y Knight9871db02019-02-05 16:42:33 +00003234llvm::FunctionCallee
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003235CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00003236 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003237 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00003238 llvm::Constant *C =
3239 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003240 /*DontDefer=*/false, /*IsThunk=*/false,
3241 ExtraAttrs);
3242
3243 if (auto *F = dyn_cast<llvm::Function>(C)) {
3244 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00003245 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003246
Reid Kleckner1808c022019-04-29 23:05:47 +00003247 // In Windows Itanium environments, try to mark runtime functions
3248 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3249 // will link their standard library statically or dynamically. Marking
3250 // functions imported when they are not imported can cause linker errors
3251 // and warnings.
3252 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3253 !getCodeGenOpts().LTOVisibilityPublicStd) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003254 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3255 if (!FD || FD->hasAttr<DLLImportAttr>()) {
3256 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3257 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3258 }
3259 }
Rafael Espindola3c9be622018-03-20 20:27:30 +00003260 setDSOLocal(F);
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00003261 }
3262 }
3263
James Y Knight9871db02019-02-05 16:42:33 +00003264 return {FTy, C};
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00003265}
3266
Richard Smithe070fd22012-02-17 06:48:11 +00003267/// isTypeConstant - Determine whether an object of this type can be emitted
3268/// as a constant.
3269///
3270/// If ExcludeCtor is true, the duration when the object's constructor runs
3271/// will not be considered. The caller will need to verify that the object is
3272/// not written to during its construction.
3273bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3274 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00003275 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00003276
David Blaikiebbafb8a2012-03-11 07:00:24 +00003277 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00003278 if (const CXXRecordDecl *Record
3279 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3280 return ExcludeCtor && !Record->hasMutableFields() &&
3281 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00003282 }
Richard Smithe070fd22012-02-17 06:48:11 +00003283
Eli Friedmanb095e152009-12-11 21:23:03 +00003284 return true;
3285}
3286
Chris Lattnerd4808922009-03-22 21:03:39 +00003287/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3288/// create and return an llvm GlobalVariable with the specified type. If there
3289/// is something in the module with the specified name, return it potentially
3290/// bitcasted to the right type.
3291///
3292/// If D is non-null, it specifies a decl that correspond to this. This is used
3293/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003294///
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003295/// If IsForDefinition is true, it is guaranteed that an actual global with
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003296/// type Ty will be returned, not conversion of a variable with the same
3297/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00003298llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003299CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00003300 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003301 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00003302 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00003303 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00003304 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00003305 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00003306 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00003307 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00003308 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00003309 }
3310
Hans Wennborg0a20f542014-08-29 00:16:06 +00003311 // Handle dropped DLL attributes.
3312 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3313 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3314
Alexey Bataev03f270c2018-03-30 18:31:07 +00003315 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3316 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3317
Chris Lattnerd4808922009-03-22 21:03:39 +00003318 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00003319 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00003320
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003321 // If there are two attempts to define the same mangled name, issue an
3322 // error.
3323 if (IsForDefinition && !Entry->isDeclaration()) {
3324 GlobalDecl OtherGD;
3325 const VarDecl *OtherD;
3326
3327 // Check that D is not yet in DiagnosedConflictingDefinitions is required
3328 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00003329 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003330 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3331 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3332 OtherD->hasInit() &&
3333 DiagnosedConflictingDefinitions.insert(D).second) {
Richard Smithb5345102018-05-30 01:52:16 +00003334 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3335 << MangledName;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003336 getDiags().Report(OtherGD.getDecl()->getLocation(),
3337 diag::note_previous_definition);
3338 }
3339 }
3340
Chris Lattner3bfce182009-03-21 08:03:33 +00003341 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00003342 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3343 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3344
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003345 // (If global is requested for a definition, we always need to create a new
3346 // global, not just return a bitcast.)
3347 if (!IsForDefinition)
3348 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00003349 }
Mike Stump11289f42009-09-09 15:08:12 +00003350
Yaxun Liucbf647c2017-07-08 13:24:52 +00003351 auto AddrSpace = GetGlobalVarAddressSpace(D);
3352 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3353
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003354 auto *GV = new llvm::GlobalVariable(
3355 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00003356 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00003357 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00003358
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003359 // If we already created a global with the same mangled name (but different
3360 // type) before, take its name and remove it from its parent.
3361 if (Entry) {
3362 GV->takeName(Entry);
3363
3364 if (!Entry->use_empty()) {
3365 llvm::Constant *NewPtrForOldDecl =
3366 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3367 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3368 }
3369
3370 Entry->eraseFromParent();
3371 }
3372
Chris Lattner45470942009-03-21 09:44:56 +00003373 // This is the first use or definition of a mangled name. If there is a
3374 // deferred decl with this name, remember that we need to emit it at the end
3375 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00003376 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00003377 if (DDI != DeferredDecls.end()) {
3378 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3379 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00003380 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00003381 DeferredDecls.erase(DDI);
3382 }
Mike Stump11289f42009-09-09 15:08:12 +00003383
Chris Lattner3bfce182009-03-21 08:03:33 +00003384 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00003385 if (D) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003386 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3387 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3388
Mike Stump18bb9282009-05-16 07:57:57 +00003389 // FIXME: This code is overly simple and should be merged with other global
3390 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00003391 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00003392
Ulrich Weigand46084382015-04-21 17:27:59 +00003393 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3394
Jake Ehrlichba874ad2017-11-29 00:54:20 +00003395 setLinkageForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00003396
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003397 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00003398 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003399 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00003400 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003401 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00003402
Rafael Espindola3dd49812018-02-23 00:22:15 +00003403 setGVProperties(GV, D);
3404
Hans Wennborgfeedf852013-11-21 00:15:56 +00003405 // If required by the ABI, treat declarations of static data members with
3406 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003407 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00003408 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003409 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00003410
Erich Keane99fdfb62017-09-26 23:42:34 +00003411 // Emit section information for extern variables.
3412 if (D->hasExternalStorage()) {
3413 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3414 GV->setSection(SA->getName());
3415 }
3416
Robert Lyttonf80d6882014-05-02 09:33:30 +00003417 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003418 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00003419 D->getLanguageLinkage() == CLanguageLinkage &&
3420 D->getType().isConstant(Context) &&
3421 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3422 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003423
3424 // Check if we a have a const declaration with an initializer, we may be
3425 // able to emit it as available_externally to expose it's value to the
3426 // optimizer.
3427 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3428 D->getType().isConstQualified() && !GV->hasInitializer() &&
3429 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3430 const auto *Record =
3431 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3432 bool HasMutableFields = Record && Record->hasMutableFields();
3433 if (!HasMutableFields) {
3434 const VarDecl *InitDecl;
3435 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3436 if (InitExpr) {
3437 ConstantEmitter emitter(*this);
3438 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3439 if (Init) {
3440 auto *InitType = Init->getType();
3441 if (GV->getType()->getElementType() != InitType) {
3442 // The type of the initializer does not match the definition.
3443 // This happens when an initializer has a different type from
3444 // the type of the global (because of padding at the end of a
3445 // structure for instance).
3446 GV->setName(StringRef());
3447 // Make a new global with the correct type, this is now guaranteed
3448 // to work.
3449 auto *NewGV = cast<llvm::GlobalVariable>(
3450 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3451
3452 // Erase the old global, since it is no longer used.
George Burgess IV00f70bd2018-03-01 05:43:23 +00003453 GV->eraseFromParent();
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003454 GV = NewGV;
3455 } else {
3456 GV->setInitializer(Init);
3457 GV->setConstant(true);
3458 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3459 }
3460 emitter.finalize(GV);
3461 }
3462 }
3463 }
3464 }
Chris Lattnerd4808922009-03-22 21:03:39 +00003465 }
Mike Stump11289f42009-09-09 15:08:12 +00003466
Alexander Richardson6d989432017-10-15 18:48:14 +00003467 LangAS ExpectedAS =
Yaxun Liucbf647c2017-07-08 13:24:52 +00003468 D ? D->getType().getAddressSpace()
Alexander Richardson6d989432017-10-15 18:48:14 +00003469 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00003470 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3471 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00003472 if (AddrSpace != ExpectedAS)
3473 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3474 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00003475
Scott Linder80a1ee42019-02-12 18:30:38 +00003476 if (GV->isDeclaration())
3477 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3478
Matt Arsenault00e65b22013-11-15 02:19:52 +00003479 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00003480}
3481
Andrey Bokhankocab58582015-08-31 13:20:44 +00003482llvm::Constant *
3483CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00003484 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003485 const Decl *D = GD.getDecl();
Peter Collingbourned1c5b282019-03-22 23:05:10 +00003486 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3487 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
Andrey Bokhankocab58582015-08-31 13:20:44 +00003488 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003489 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003490 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003491 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00003492 auto Ty = getTypes().GetFunctionType(*FInfo);
3493 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3494 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003495 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003496 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3497 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3498 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3499 IsForDefinition);
3500 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003501 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003502 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003503}
Chris Lattnerd4808922009-03-22 21:03:39 +00003504
David Greenbe0c5b62018-09-12 14:09:06 +00003505llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3506 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3507 unsigned Alignment) {
Anders Carlssonda80af32011-01-29 18:20:20 +00003508 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00003509 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00003510
Anders Carlssonda80af32011-01-29 18:20:20 +00003511 if (GV) {
3512 // Check if the variable has the right type.
3513 if (GV->getType()->getElementType() == Ty)
3514 return GV;
3515
3516 // Because C++ name mangling, the only way we can end up with an already
3517 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00003518 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00003519 OldGV = GV;
3520 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003521
Anders Carlssonda80af32011-01-29 18:20:20 +00003522 // Create a new variable.
3523 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00003524 Linkage, nullptr, Name);
3525
Anders Carlssonda80af32011-01-29 18:20:20 +00003526 if (OldGV) {
3527 // Replace occurrences of the old variable if needed.
3528 GV->takeName(OldGV);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003529
Anders Carlssonda80af32011-01-29 18:20:20 +00003530 if (!OldGV->use_empty()) {
3531 llvm::Constant *NewPtrForOldDecl =
3532 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3533 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3534 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003535
Anders Carlssonda80af32011-01-29 18:20:20 +00003536 OldGV->eraseFromParent();
3537 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00003538
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003539 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3540 !GV->hasAvailableExternallyLinkage())
3541 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00003542
David Greenbe0c5b62018-09-12 14:09:06 +00003543 GV->setAlignment(Alignment);
3544
Anders Carlssonda80af32011-01-29 18:20:20 +00003545 return GV;
3546}
3547
Chris Lattnerd4808922009-03-22 21:03:39 +00003548/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3549/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00003550/// then it will be created with the specified type instead of whatever the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003551/// normal requested type would be. If IsForDefinition is true, it is guaranteed
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003552/// that an actual global with type Ty will be returned, not conversion of a
3553/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00003554llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003555 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00003556 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00003557 assert(D->hasGlobalStorage() && "Not a global variable");
3558 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00003559 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00003560 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00003561
Chris Lattner2192fe52011-07-18 04:24:23 +00003562 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003563 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00003564
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003565 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003566 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00003567}
3568
3569/// CreateRuntimeVariable - Create a new runtime global variable with the
3570/// specified type and name.
3571llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00003572CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003573 StringRef Name) {
Rafael Espindola6ab4ae42018-03-21 01:30:16 +00003574 auto *Ret =
3575 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3576 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3577 return Ret;
Chris Lattnerd4808922009-03-22 21:03:39 +00003578}
3579
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003580void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3581 assert(!D->getInit() && "Cannot emit definite definitions here!");
3582
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003583 StringRef MangledName = getMangledName(D);
3584 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3585
3586 // We already have a definition, not declaration, with the same mangled name.
3587 // Emitting of declaration is not required (and actually overwrites emitted
3588 // definition).
3589 if (GV && !GV->isDeclaration())
3590 return;
3591
3592 // If we have not seen a reference to this variable yet, place it into the
3593 // deferred declarations table to be emitted if needed later.
3594 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003595 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003596 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00003597 }
3598
3599 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00003600 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003601}
3602
Chris Lattner2192fe52011-07-18 04:24:23 +00003603CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00003604 return Context.toCharUnitsFromBits(
3605 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00003606}
3607
Alexander Richardson6d989432017-10-15 18:48:14 +00003608LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3609 LangAS AddrSpace = LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003610 if (LangOpts.OpenCL) {
Alexander Richardson6d989432017-10-15 18:48:14 +00003611 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003612 assert(AddrSpace == LangAS::opencl_global ||
3613 AddrSpace == LangAS::opencl_constant ||
3614 AddrSpace == LangAS::opencl_local ||
3615 AddrSpace >= LangAS::FirstTargetAddressSpace);
3616 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003617 }
3618
Yaxun Liucbf647c2017-07-08 13:24:52 +00003619 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3620 if (D && D->hasAttr<CUDAConstantAttr>())
3621 return LangAS::cuda_constant;
3622 else if (D && D->hasAttr<CUDASharedAttr>())
3623 return LangAS::cuda_shared;
Yaxun Liua4005e12018-07-28 03:05:25 +00003624 else if (D && D->hasAttr<CUDADeviceAttr>())
3625 return LangAS::cuda_device;
3626 else if (D && D->getType().isConstQualified())
3627 return LangAS::cuda_constant;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003628 else
3629 return LangAS::cuda_device;
3630 }
3631
Alexey Bataevc5687252019-03-21 19:35:27 +00003632 if (LangOpts.OpenMP) {
3633 LangAS AS;
3634 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3635 return AS;
3636 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00003637 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003638}
3639
Yaxun Liudaceb1e2018-05-14 19:20:12 +00003640LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3641 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3642 if (LangOpts.OpenCL)
3643 return LangAS::opencl_constant;
3644 if (auto AS = getTarget().getConstantAddressSpace())
3645 return AS.getValue();
3646 return LangAS::Default;
3647}
3648
3649// In address space agnostic languages, string literals are in default address
3650// space in AST. However, certain targets (e.g. amdgcn) request them to be
3651// emitted in constant address space in LLVM IR. To be consistent with other
3652// parts of AST, string literal global variables in constant address space
3653// need to be casted to default address space before being put into address
3654// map and referenced by other part of CodeGen.
3655// In OpenCL, string literals are in constant address space in AST, therefore
3656// they should not be casted to default address space.
3657static llvm::Constant *
3658castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3659 llvm::GlobalVariable *GV) {
3660 llvm::Constant *Cast = GV;
3661 if (!CGM.getLangOpts().OpenCL) {
3662 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3663 if (AS != LangAS::Default)
3664 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3665 CGM, GV, AS.getValue(), LangAS::Default,
3666 GV->getValueType()->getPointerTo(
3667 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3668 }
3669 }
3670 return Cast;
3671}
3672
Richard Smithdf931ce2013-04-06 05:00:46 +00003673template<typename SomeDecl>
3674void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3675 llvm::GlobalValue *GV) {
3676 if (!getLangOpts().CPlusPlus)
3677 return;
3678
3679 // Must have 'used' attribute, or else inline assembly can't rely on
3680 // the name existing.
3681 if (!D->template hasAttr<UsedAttr>())
3682 return;
3683
3684 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00003685 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00003686 return;
3687
3688 // Must be in an extern "C" context. Entities declared directly within
3689 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003690 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00003691 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00003692 return;
3693
3694 // OK, this is an internal linkage entity inside an extern "C" linkage
3695 // specification. Make a note of that so we can give it the "expected"
3696 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00003697 std::pair<StaticExternCMap::iterator, bool> R =
3698 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00003699
3700 // If we have multiple internal linkage entities with the same name
3701 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00003702 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00003703 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00003704}
3705
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003706static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3707 if (!CGM.supportsCOMDAT())
3708 return false;
3709
3710 if (D.hasAttr<SelectAnyAttr>())
3711 return true;
3712
3713 GVALinkage Linkage;
3714 if (auto *VD = dyn_cast<VarDecl>(&D))
3715 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3716 else
3717 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3718
3719 switch (Linkage) {
3720 case GVA_Internal:
3721 case GVA_AvailableExternally:
3722 case GVA_StrongExternal:
3723 return false;
3724 case GVA_DiscardableODR:
3725 case GVA_StrongODR:
3726 return true;
3727 }
3728 llvm_unreachable("No such linkage");
3729}
3730
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003731void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3732 llvm::GlobalObject &GO) {
3733 if (!shouldBeInCOMDAT(*this, D))
3734 return;
3735 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3736}
3737
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003738/// Pass IsTentative as true if you want to create a tentative definition.
3739void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3740 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003741 // OpenCL global variables of sampler type are translated to function calls,
3742 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003743 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003744 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3745 return;
3746
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003747 // If this is OpenMP device, check if it is legal to emit this global
3748 // normally.
3749 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3750 OpenMPRuntime->emitTargetGlobalVariable(D))
3751 return;
3752
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003753 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00003754 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3755 bool NeedsGlobalCtor = false;
3756 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00003757
Richard Smithdafff942012-01-14 04:30:29 +00003758 const VarDecl *InitDecl;
3759 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003760
John McCallde0fe072017-08-15 21:42:52 +00003761 Optional<ConstantEmitter> emitter;
3762
Artem Belevich97c01c32016-02-02 22:29:48 +00003763 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3764 // as part of their declaration." Sema has already checked for
3765 // error cases, so we just need to set Init to UndefValue.
Artem Belevich7b056662018-12-13 21:43:04 +00003766 bool IsCUDASharedVar =
3767 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3768 // Shadows of initialized device-side global variables are also left
3769 // undefined.
3770 bool IsCUDAShadowVar =
3771 !getLangOpts().CUDAIsDevice &&
3772 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3773 D->hasAttr<CUDASharedAttr>());
3774 if (getLangOpts().CUDA && (IsCUDASharedVar || IsCUDAShadowVar))
Jingyue Wu284ebe22015-08-22 05:49:28 +00003775 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00003776 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00003777 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003778 // implicitly initialized with { 0 }.
3779 //
3780 // Note that tentative definitions are only emitted at the end of
3781 // a translation unit, so they should never have incomplete
3782 // type. In addition, EmitTentativeDefinition makes sure that we
3783 // never attempt to emit a tentative definition if a real one
3784 // exists. A use may still exists, however, so we still may need
3785 // to do a RAUW.
3786 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00003787 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003788 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003789 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00003790 emitter.emplace(*this);
3791 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003792
Fariborz Jahanian63628032012-06-26 16:06:38 +00003793 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00003794 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00003795 if (D->getType()->isReferenceType())
3796 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00003797
David Blaikiebbafb8a2012-03-11 07:00:24 +00003798 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003799 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00003800 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003801 } else {
3802 ErrorUnsupported(D, "static initializer");
3803 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3804 }
John McCall70013b62010-07-15 23:40:35 +00003805 } else {
3806 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00003807 // initializer position (just in case this entry was delayed) if we
3808 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003809 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00003810 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00003811 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003812 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003813
Chris Lattner2192fe52011-07-18 04:24:23 +00003814 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003815 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00003816 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00003817
Chris Lattner149927c2009-03-21 09:16:30 +00003818 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003819 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00003820 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00003821 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3822 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00003823 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00003824 Entry = CE->getOperand(0);
3825 }
Mike Stump11289f42009-09-09 15:08:12 +00003826
Chris Lattner149927c2009-03-21 09:16:30 +00003827 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003828 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003829
Chris Lattner149927c2009-03-21 09:16:30 +00003830 // We have a definition after a declaration with the wrong type.
3831 // We must make a new GlobalVariable* and update everything that used OldGV
3832 // (a declaration or tentative definition) with the new GlobalVariable*
3833 // (which will be a definition).
3834 //
3835 // This happens if there is a prototype for a global (e.g.
3836 // "extern int x[];") and then a definition of a different type (e.g.
3837 // "int x[10];"). This also happens when an initializer has a different type
3838 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00003839 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003840 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00003841 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00003842
John McCall7ec50432010-03-19 23:29:14 +00003843 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003844 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00003845
Chris Lattner149927c2009-03-21 09:16:30 +00003846 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003847 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00003848 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00003849
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003850 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00003851 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00003852 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00003853 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003854
3855 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00003856 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00003857 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00003858
Richard Smithdf931ce2013-04-06 05:00:46 +00003859 MaybeHandleStaticInExternC(D, GV);
3860
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003861 if (D->hasAttr<AnnotateAttr>())
3862 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00003863
Artem Belevich42e19492016-03-02 18:28:50 +00003864 // Set the llvm linkage type as appropriate.
3865 llvm::GlobalValue::LinkageTypes Linkage =
3866 getLLVMLinkageVarDefinition(D, GV->isConstant());
3867
Jingyue Wu284ebe22015-08-22 05:49:28 +00003868 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3869 // the device. [...]"
3870 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3871 // __device__, declares a variable that: [...]
3872 // Is accessible from all the threads within the grid and from the host
3873 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3874 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00003875 if (GV && LangOpts.CUDA) {
3876 if (LangOpts.CUDAIsDevice) {
Michael Liao4b7a7132019-05-29 17:23:27 +00003877 if (Linkage != llvm::GlobalValue::InternalLinkage &&
3878 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
Artem Belevich42e19492016-03-02 18:28:50 +00003879 GV->setExternallyInitialized(true);
3880 } else {
3881 // Host-side shadows of external declarations of device-side
3882 // global variables become internal definitions. These have to
3883 // be internal in order to prevent name conflicts with global
3884 // host variables with the same name in a different TUs.
3885 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3886 Linkage = llvm::GlobalValue::InternalLinkage;
3887
3888 // Shadow variables and their properties must be registered
3889 // with CUDA runtime.
3890 unsigned Flags = 0;
3891 if (!D->hasDefinition())
3892 Flags |= CGCUDARuntime::ExternDeviceVar;
3893 if (D->hasAttr<CUDAConstantAttr>())
3894 Flags |= CGCUDARuntime::ConstantDeviceVar;
Artem Belevich99535772018-12-22 01:11:09 +00003895 // Extern global variables will be registered in the TU where they are
3896 // defined.
3897 if (!D->hasExternalStorage())
Yaxun Liuc18e9ec2019-02-14 02:00:09 +00003898 getCUDARuntime().registerDeviceVar(D, *GV, Flags);
Artem Belevich42e19492016-03-02 18:28:50 +00003899 } else if (D->hasAttr<CUDASharedAttr>())
3900 // __shared__ variables are odd. Shadows do get created, but
3901 // they are not registered with the CUDA runtime, so they
3902 // can't really be used to access their device-side
3903 // counterparts. It's not clear yet whether it's nvcc's bug or
3904 // a feature, but we've got to do the same for compatibility.
3905 Linkage = llvm::GlobalValue::InternalLinkage;
3906 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00003907 }
John McCallde0fe072017-08-15 21:42:52 +00003908
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003909 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00003910 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00003911
3912 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00003913 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3914 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00003915
Hans Wennborg899ded92014-10-16 20:52:46 +00003916 // If it is in a read-only section, mark it 'constant'.
3917 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3918 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3919 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3920 GV->setConstant(true);
3921 }
3922
Ken Dyck160146e2010-01-27 17:10:57 +00003923 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00003924
David Majnemer35ab3282014-06-11 04:08:55 +00003925
Manman Ren68150262015-11-11 22:42:31 +00003926 // On Darwin, if the normal linkage of a C++ thread_local variable is
3927 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3928 // copies within a linkage unit; otherwise, the backing variable has
3929 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00003930 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00003931 // variable. This is to preserve the ability to change the implementation
3932 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00003933 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00003934 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00003935 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3936 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00003937 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00003938
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003939 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00003940 if (D->hasAttr<DLLImportAttr>())
3941 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3942 else if (D->hasAttr<DLLExportAttr>())
3943 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00003944 else
3945 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00003946
Yaxun Liu402804b2016-12-15 08:09:08 +00003947 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00003948 // common vars aren't constant even if declared const.
3949 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00003950 // Tentative definition of global variables may be initialized with
3951 // non-zero null pointers. In this case they should have weak linkage
3952 // since common linkage must have zero initializer and must not have
3953 // explicit section therefore cannot have non-zero initial value.
3954 if (!GV->getInitializer()->isNullValue())
3955 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3956 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00003957
Rafael Espindola502f65a2014-05-05 20:21:03 +00003958 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00003959
David Majnemerbb525f7c2014-10-15 22:38:23 +00003960 if (D->getTLSKind() && !GV->isThreadLocal()) {
3961 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003962 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00003963 setTLSMode(GV, *D);
3964 }
3965
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003966 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003967
John McCallcdf7ef52010-11-06 09:44:32 +00003968 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00003969 if (NeedsGlobalCtor || NeedsGlobalDtor)
3970 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00003971
Alexey Samsonov4b8de112014-08-01 21:35:28 +00003972 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00003973
Sanjiv Gupta158143a2008-06-05 08:59:10 +00003974 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00003975 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003976 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00003977 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003978}
Chris Lattner09153c02007-06-22 18:48:09 +00003979
David Majnemerc017d362014-08-05 00:01:13 +00003980static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00003981 CodeGenModule &CGM, const VarDecl *D,
3982 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00003983 // Don't give variables common linkage if -fno-common was specified unless it
3984 // was overridden by a NoCommon attribute.
3985 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3986 return true;
3987
3988 // C11 6.9.2/2:
3989 // A declaration of an identifier for an object that has file scope without
3990 // an initializer, and without a storage-class specifier or with the
3991 // storage-class specifier static, constitutes a tentative definition.
3992 if (D->getInit() || D->hasExternalStorage())
3993 return true;
3994
3995 // A variable cannot be both common and exist in a section.
3996 if (D->hasAttr<SectionAttr>())
3997 return true;
3998
Javed Absar2a67c9e2017-06-05 10:11:57 +00003999 // A variable cannot be both common and exist in a section.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004000 // We don't try to determine which is the right section in the front-end.
Javed Absar2a67c9e2017-06-05 10:11:57 +00004001 // If no specialized section name is applicable, it will resort to default.
4002 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4003 D->hasAttr<PragmaClangDataSectionAttr>() ||
4004 D->hasAttr<PragmaClangRodataSectionAttr>())
4005 return true;
4006
David Majnemer9832a3d2014-04-10 16:53:16 +00004007 // Thread local vars aren't considered common linkage.
4008 if (D->getTLSKind())
4009 return true;
4010
4011 // Tentative definitions marked with WeakImportAttr are true definitions.
4012 if (D->hasAttr<WeakImportAttr>())
4013 return true;
4014
Nico Weber608e7682015-04-15 23:04:24 +00004015 // A variable cannot be both common and exist in a comdat.
4016 if (shouldBeInCOMDAT(CGM, *D))
4017 return true;
4018
Sanjay Patel2f9303a2016-06-30 21:02:40 +00004019 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00004020 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00004021 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00004022 if (D->hasAttr<AlignedAttr>())
4023 return true;
4024 QualType VarType = D->getType();
4025 if (Context.isAlignmentRequired(VarType))
4026 return true;
4027
4028 if (const auto *RT = VarType->getAs<RecordType>()) {
4029 const RecordDecl *RD = RT->getDecl();
4030 for (const FieldDecl *FD : RD->fields()) {
4031 if (FD->isBitField())
4032 continue;
4033 if (FD->hasAttr<AlignedAttr>())
4034 return true;
4035 if (Context.isAlignmentRequired(FD->getType()))
4036 return true;
4037 }
4038 }
4039 }
Shoaib Meenai39287e72019-01-09 20:05:16 +00004040
Erich Keane892e6332019-02-07 15:14:11 +00004041 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4042 // common symbols, so symbols with greater alignment requirements cannot be
4043 // common.
Shoaib Meenai39287e72019-01-09 20:05:16 +00004044 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4045 // alignments for common symbols via the aligncomm directive, so this
4046 // restriction only applies to MSVC environments.
Erich Keane85c62242019-01-08 18:44:22 +00004047 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
Erich Keane892e6332019-02-07 15:14:11 +00004048 Context.getTypeAlignIfKnown(D->getType()) >
4049 Context.toBits(CharUnits::fromQuantity(32)))
Erich Keane85c62242019-01-08 18:44:22 +00004050 return true;
David Majnemerc017d362014-08-05 00:01:13 +00004051
David Majnemer9832a3d2014-04-10 16:53:16 +00004052 return false;
4053}
4054
Hans Wennborg1a3a0742014-05-14 19:54:53 +00004055llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00004056 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00004057 if (Linkage == GVA_Internal)
4058 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00004059
4060 if (D->hasAttr<WeakAttr>()) {
4061 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00004062 return llvm::GlobalVariable::WeakODRLinkage;
4063 else
4064 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00004065 }
4066
Erich Keane7ef210d2018-10-22 21:20:45 +00004067 if (const auto *FD = D->getAsFunction())
4068 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4069 return llvm::GlobalVariable::LinkOnceAnyLinkage;
4070
David Majnemer27d69db2014-04-28 22:17:59 +00004071 // We are guaranteed to have a strong definition somewhere else,
4072 // so we can use available_externally linkage.
4073 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00004074 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00004075
David Majnemer27d69db2014-04-28 22:17:59 +00004076 // Note that Apple's kernel linker doesn't support symbol
4077 // coalescing, so we need to avoid linkonce and weak linkages there.
4078 // Normally, this means we just map to internal, but for explicit
4079 // instantiations we'll map to external.
4080
4081 // In C++, the compiler has to emit a definition in every translation unit
4082 // that references the function. We should use linkonce_odr because
4083 // a) if all references in this translation unit are optimized away, we
4084 // don't need to codegen it. b) if the function persists, it needs to be
4085 // merged with other definitions. c) C++ has the ODR, so we know the
4086 // definition is dependable.
4087 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00004088 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00004089 : llvm::Function::InternalLinkage;
4090
4091 // An explicit instantiation of a template has weak linkage, since
4092 // explicit instantiations can occur in multiple translation units
4093 // and must all be equivalent. However, we are not allowed to
4094 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00004095 //
4096 // We don't currently support CUDA device code spread out across multiple TUs,
4097 // so say that CUDA templates are either external (for kernels) or internal.
4098 // This lets llvm perform aggressive inter-procedural optimizations.
4099 if (Linkage == GVA_StrongODR) {
4100 if (Context.getLangOpts().AppleKext)
4101 return llvm::Function::ExternalLinkage;
4102 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
4103 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4104 : llvm::Function::InternalLinkage;
4105 return llvm::Function::WeakODRLinkage;
4106 }
David Majnemer27d69db2014-04-28 22:17:59 +00004107
David Majnemer27d69db2014-04-28 22:17:59 +00004108 // C++ doesn't have tentative definitions and thus cannot have common
4109 // linkage.
4110 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00004111 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00004112 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00004113 return llvm::GlobalVariable::CommonLinkage;
4114
David Majnemer27d69db2014-04-28 22:17:59 +00004115 // selectany symbols are externally visible, so use weak instead of
4116 // linkonce. MSVC optimizes away references to const selectany globals, so
4117 // all definitions should be the same and ODR linkage should be used.
4118 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4119 if (D->hasAttr<SelectAnyAttr>())
4120 return llvm::GlobalVariable::WeakODRLinkage;
4121
4122 // Otherwise, we have strong external linkage.
4123 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00004124 return llvm::GlobalVariable::ExternalLinkage;
4125}
4126
David Majnemer27d69db2014-04-28 22:17:59 +00004127llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4128 const VarDecl *VD, bool IsConstant) {
4129 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00004130 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00004131}
4132
John McCall49954ca2012-12-12 22:21:47 +00004133/// Replace the uses of a function that was declared with a non-proto type.
4134/// We want to silently drop extra arguments from call sites
4135static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4136 llvm::Function *newFn) {
4137 // Fast path.
4138 if (old->use_empty()) return;
4139
4140 llvm::Type *newRetTy = newFn->getReturnType();
4141 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00004142 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00004143
4144 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4145 ui != ue; ) {
4146 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00004147 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00004148
4149 // Recognize and replace uses of bitcasts. Most calls to
4150 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004151 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00004152 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4153 replaceUsesOfNonProtoConstant(bitcast, newFn);
4154 continue;
4155 }
4156
4157 // Recognize calls to the function.
James Y Knight3933add2019-01-30 02:54:28 +00004158 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
John McCall49954ca2012-12-12 22:21:47 +00004159 if (!callSite) continue;
James Y Knight3933add2019-01-30 02:54:28 +00004160 if (!callSite->isCallee(&*use))
4161 continue;
John McCall49954ca2012-12-12 22:21:47 +00004162
4163 // If the return types don't match exactly, then we can't
4164 // transform this call unless it's dead.
4165 if (callSite->getType() != newRetTy && !callSite->use_empty())
4166 continue;
4167
4168 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00004169 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
James Y Knight3933add2019-01-30 02:54:28 +00004170 llvm::AttributeList oldAttrs = callSite->getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00004171
John McCall49954ca2012-12-12 22:21:47 +00004172 // If the function was passed too few arguments, don't transform.
4173 unsigned newNumArgs = newFn->arg_size();
James Y Knight3933add2019-01-30 02:54:28 +00004174 if (callSite->arg_size() < newNumArgs)
4175 continue;
John McCall49954ca2012-12-12 22:21:47 +00004176
4177 // If extra arguments were passed, we silently drop them.
4178 // If any of the types mismatch, we don't transform.
4179 unsigned argNo = 0;
4180 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00004181 for (llvm::Argument &A : newFn->args()) {
James Y Knight3933add2019-01-30 02:54:28 +00004182 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00004183 dontTransform = true;
4184 break;
4185 }
4186
4187 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004188 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00004189 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00004190 }
4191 if (dontTransform)
4192 continue;
4193
John McCall49954ca2012-12-12 22:21:47 +00004194 // Okay, we can transform this. Create the new call instruction and copy
4195 // over the required information.
James Y Knight3933add2019-01-30 02:54:28 +00004196 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
John McCall49954ca2012-12-12 22:21:47 +00004197
David Majnemer0b17d442015-12-15 21:27:59 +00004198 // Copy over any operand bundles.
James Y Knight3933add2019-01-30 02:54:28 +00004199 callSite->getOperandBundlesAsDefs(newBundles);
David Majnemer0b17d442015-12-15 21:27:59 +00004200
James Y Knight3933add2019-01-30 02:54:28 +00004201 llvm::CallBase *newCall;
4202 if (dyn_cast<llvm::CallInst>(callSite)) {
4203 newCall =
4204 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
John McCall49954ca2012-12-12 22:21:47 +00004205 } else {
James Y Knight3933add2019-01-30 02:54:28 +00004206 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4207 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4208 oldInvoke->getUnwindDest(), newArgs,
4209 newBundles, "", callSite);
John McCall49954ca2012-12-12 22:21:47 +00004210 }
4211 newArgs.clear(); // for the next iteration
4212
4213 if (!newCall->getType()->isVoidTy())
James Y Knight3933add2019-01-30 02:54:28 +00004214 newCall->takeName(callSite);
4215 newCall->setAttributes(llvm::AttributeList::get(
Reid Kleckner7f720332017-04-13 00:58:09 +00004216 newFn->getContext(), oldAttrs.getFnAttributes(),
4217 oldAttrs.getRetAttributes(), newArgAttrs));
James Y Knight3933add2019-01-30 02:54:28 +00004218 newCall->setCallingConv(callSite->getCallingConv());
John McCall49954ca2012-12-12 22:21:47 +00004219
4220 // Finally, remove the old call, replacing any uses with the new one.
4221 if (!callSite->use_empty())
James Y Knight3933add2019-01-30 02:54:28 +00004222 callSite->replaceAllUsesWith(newCall);
John McCall49954ca2012-12-12 22:21:47 +00004223
4224 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00004225 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00004226 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00004227
John McCall49954ca2012-12-12 22:21:47 +00004228 callSite->eraseFromParent();
4229 }
4230}
4231
Chris Lattner36797ab2009-05-05 06:16:31 +00004232/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4233/// implement a function with no prototype, e.g. "int foo() {}". If there are
4234/// existing call uses of the old function in the module, this adjusts them to
4235/// call the new function directly.
4236///
4237/// This is not just a cleanup: the always_inline pass requires direct calls to
4238/// functions to be able to inline them. If there is a bitcast in the way, it
4239/// won't inline them. Instcombine normally deletes these calls, but it isn't
4240/// run at -O0.
4241static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4242 llvm::Function *NewFn) {
4243 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00004244 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00004245
John McCall49954ca2012-12-12 22:21:47 +00004246 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00004247}
4248
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004249void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00004250 auto DK = VD->isThisDeclarationADefinition();
4251 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4252 return;
4253
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00004254 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4255 // If we have a definition, this might be a deferred decl. If the
4256 // instantiation is explicit, make sure we emit it at the end.
4257 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4258 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00004259
4260 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00004261}
Daniel Dunbar9c426522008-07-29 23:18:29 +00004262
Rafael Espindolacd7743b2013-12-09 16:01:03 +00004263void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4264 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004265 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00004266
John McCall46288ef2011-03-09 08:12:35 +00004267 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00004268 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4269 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00004270
Chris Lattnereb7466d2009-05-12 20:58:15 +00004271 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00004272 if (!GV || (GV->getType()->getElementType() != Ty))
4273 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4274 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00004275 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00004276
Andrey Bokhankocab58582015-08-31 13:20:44 +00004277 // Already emitted.
4278 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00004279 return;
Mike Stump11289f42009-09-09 15:08:12 +00004280
John McCall8e7cb6d2010-11-02 21:04:24 +00004281 // We need to set linkage and visibility on the function before
4282 // generating code for it because various parts of IR generation
4283 // want to propagate this information down (e.g. to local static
4284 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004285 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00004286 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00004287
Rafael Espindolae033c8c2014-05-08 15:26:12 +00004288 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Rafael Espindolab7350042018-03-01 00:35:47 +00004289 setGVProperties(Fn, GD);
John McCall8e7cb6d2010-11-02 21:04:24 +00004290
Richard Smithdf931ce2013-04-06 05:00:46 +00004291 MaybeHandleStaticInExternC(D, Fn);
4292
Yaxun Liu4306f202018-04-20 17:01:03 +00004293
Rafael Espindoladbee8a72015-01-15 21:36:08 +00004294 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00004295
John McCalla738c252011-03-09 04:27:21 +00004296 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00004297
Rafael Espindolae4e78132018-03-01 00:00:02 +00004298 setNonAliasAttributes(GD, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00004299 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00004300
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004301 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00004302 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004303 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00004304 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00004305 if (D->hasAttr<AnnotateAttr>())
4306 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00004307}
4308
John McCall7ec50432010-03-19 23:29:14 +00004309void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004310 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004311 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00004312 assert(AA && "Not an alias?");
4313
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004314 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00004315
Hal Finkel0e2b9752015-09-04 21:49:21 +00004316 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004317 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00004318 return;
4319 }
4320
John McCall7ec50432010-03-19 23:29:14 +00004321 // If there is a definition in the module, then it wins over the alias.
4322 // This is dubious, but allow it to be safe. Just ignore the alias.
4323 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4324 if (Entry && !Entry->isDeclaration())
4325 return;
4326
Rafael Espindola208b5c02013-10-22 19:26:13 +00004327 Aliases.push_back(GD);
4328
Chris Lattner2192fe52011-07-18 04:24:23 +00004329 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00004330
4331 // Create a reference to the named value. This ensures that it is emitted
4332 // if a deferred decl.
4333 llvm::Constant *Aliasee;
4334 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00004335 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00004336 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00004337 else
John McCall7ec50432010-03-19 23:29:14 +00004338 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00004339 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00004340 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00004341
4342 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00004343 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00004344 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00004345
Chris Lattner54041692009-03-22 21:47:11 +00004346 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00004347 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004348 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00004349 return;
4350 }
4351
John McCall7ec50432010-03-19 23:29:14 +00004352 assert(Entry->isDeclaration());
4353
Chris Lattner54041692009-03-22 21:47:11 +00004354 // If there is a declaration in the module, then we had an extern followed
4355 // by the alias, as in:
4356 // extern int test6();
4357 // ...
4358 // int test6() __attribute__((alias("test7")));
4359 //
4360 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00004361 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00004362
Owen Andersonade90fd2009-07-29 18:54:39 +00004363 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00004364 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00004365 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00004366 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00004367 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00004368 }
Mike Stump11289f42009-09-09 15:08:12 +00004369
Daniel Dunbar38932572009-04-14 08:05:55 +00004370 // Set attributes which are particular to an alias; this is a
4371 // specialization of the attributes which may be set on a global
4372 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00004373 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4374 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00004375 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4376 }
4377
David Majnemerbb525f7c2014-10-15 22:38:23 +00004378 if (const auto *VD = dyn_cast<VarDecl>(D))
4379 if (VD->getTLSKind())
4380 setTLSMode(GA, *VD);
4381
Rafael Espindolab7350042018-03-01 00:35:47 +00004382 SetCommonAttributes(GD, GA);
Chris Lattner54041692009-03-22 21:47:11 +00004383}
4384
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004385void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4386 const auto *D = cast<ValueDecl>(GD.getDecl());
4387 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4388 assert(IFA && "Not an ifunc?");
4389
4390 StringRef MangledName = getMangledName(GD);
4391
4392 if (IFA->getResolver() == MangledName) {
4393 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4394 return;
4395 }
4396
4397 // Report an error if some definition overrides ifunc.
4398 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4399 if (Entry && !Entry->isDeclaration()) {
4400 GlobalDecl OtherGD;
4401 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4402 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00004403 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4404 << MangledName;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004405 Diags.Report(OtherGD.getDecl()->getLocation(),
4406 diag::note_previous_definition);
4407 }
4408 return;
4409 }
4410
4411 Aliases.push_back(GD);
4412
4413 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4414 llvm::Constant *Resolver =
4415 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4416 /*ForVTable=*/false);
4417 llvm::GlobalIFunc *GIF =
4418 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4419 "", Resolver, &getModule());
4420 if (Entry) {
4421 if (GIF->getResolver() == Entry) {
4422 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4423 return;
4424 }
4425 assert(Entry->isDeclaration());
4426
4427 // If there is a declaration in the module, then we had an extern followed
4428 // by the ifunc, as in:
4429 // extern int test();
4430 // ...
4431 // int test() __attribute__((ifunc("resolver")));
4432 //
4433 // Remove it and replace uses of it with the ifunc.
4434 GIF->takeName(Entry);
4435
4436 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4437 Entry->getType()));
4438 Entry->eraseFromParent();
4439 } else
4440 GIF->setName(MangledName);
4441
Rafael Espindola75c649c2018-03-01 00:06:55 +00004442 SetCommonAttributes(GD, GIF);
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004443}
4444
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004445llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00004446 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00004447 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004448 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00004449}
Chris Lattner1eec6602007-08-31 04:31:45 +00004450
David Blaikie2e804282015-04-05 22:47:07 +00004451static llvm::StringMapEntry<llvm::GlobalVariable *> &
4452GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4453 const StringLiteral *Literal, bool TargetIsLSB,
4454 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004455 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004456 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00004457
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004458 // Check for simple case.
4459 if (!Literal->containsNonAsciiOrNull()) {
4460 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00004461 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004462 }
4463
Bill Wendling82b87f12012-03-30 00:26:17 +00004464 // Otherwise, convert the UTF8 literals into a string of shorts.
4465 IsUTF16 = true;
4466
Justin Lebar90910552016-09-30 00:38:45 +00004467 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4468 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4469 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00004470
Justin Lebar90910552016-09-30 00:38:45 +00004471 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4472 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00004473
Daniel Dunbar91ade142009-07-23 23:41:22 +00004474 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00004475 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00004476
Bill Wendling82b87f12012-03-30 00:26:17 +00004477 // Add an explicit null.
4478 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00004479 return *Map.insert(std::make_pair(
4480 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4481 (StringLength + 1) * 2),
4482 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00004483}
4484
John McCall7f416cc2015-09-08 08:05:57 +00004485ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00004486CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4487 unsigned StringLength = 0;
4488 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00004489 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4490 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4491 getDataLayout().isLittleEndian(), isUTF16,
4492 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004493
David Blaikie13156b62014-11-19 03:06:06 +00004494 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00004495 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00004496
Chris Lattnerece04092012-02-07 00:39:47 +00004497 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00004498 llvm::Constant *Zeros[] = { Zero, Zero };
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004499
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004500 const ASTContext &Context = getContext();
4501 const llvm::Triple &Triple = getTriple();
4502
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004503 const auto CFRuntime = getLangOpts().CFRuntime;
4504 const bool IsSwiftABI =
4505 static_cast<unsigned>(CFRuntime) >=
4506 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4507 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4508
Chris Lattneraa64ca22009-07-16 16:48:25 +00004509 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00004510 if (!CFConstantStringClassRef) {
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004511 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00004512 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00004513 Ty = llvm::ArrayType::get(Ty, 0);
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004514
4515 switch (CFRuntime) {
4516 default: break;
4517 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
Saleem Abdulrasool0c16a132018-10-25 17:52:13 +00004518 case LangOptions::CoreFoundationABI::Swift5_0:
4519 CFConstantStringClassName =
Saleem Abdulrasool98ac9982018-10-26 03:16:16 +00004520 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4521 : "$s10Foundation19_NSCFConstantStringCN";
Saleem Abdulrasool0c16a132018-10-25 17:52:13 +00004522 Ty = IntPtrTy;
4523 break;
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004524 case LangOptions::CoreFoundationABI::Swift4_2:
4525 CFConstantStringClassName =
Saleem Abdulrasool98ac9982018-10-26 03:16:16 +00004526 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4527 : "$S10Foundation19_NSCFConstantStringCN";
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004528 Ty = IntPtrTy;
4529 break;
4530 case LangOptions::CoreFoundationABI::Swift4_1:
4531 CFConstantStringClassName =
4532 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4533 : "__T010Foundation19_NSCFConstantStringCN";
4534 Ty = IntPtrTy;
4535 break;
4536 }
4537
4538 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004539
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004540 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
Kristina Brooks34e24d52018-09-25 22:27:40 +00004541 llvm::GlobalValue *GV = nullptr;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004542
Kristina Brooks34e24d52018-09-25 22:27:40 +00004543 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004544 IdentifierInfo &II = Context.Idents.get(GV->getName());
4545 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
Kristina Brooks34e24d52018-09-25 22:27:40 +00004546 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004547
Kristina Brooks34e24d52018-09-25 22:27:40 +00004548 const VarDecl *VD = nullptr;
4549 for (const auto &Result : DC->lookup(&II))
4550 if ((VD = dyn_cast<VarDecl>(Result)))
4551 break;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004552
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004553 if (Triple.isOSBinFormatELF()) {
Kristina Brooks34e24d52018-09-25 22:27:40 +00004554 if (!VD)
4555 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004556 } else {
4557 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4558 if (!VD || !VD->hasAttr<DLLExportAttr>())
Kristina Brooks34e24d52018-09-25 22:27:40 +00004559 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004560 else
Kristina Brooks34e24d52018-09-25 22:27:40 +00004561 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Kristina Brooks34e24d52018-09-25 22:27:40 +00004562 }
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004563
Kristina Brooks34e24d52018-09-25 22:27:40 +00004564 setDSOLocal(GV);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004565 }
4566 }
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004567
Daniel Dunbard644ad62008-08-23 18:37:06 +00004568 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00004569 CFConstantStringClassRef =
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004570 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4571 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004572 }
Mike Stump11289f42009-09-09 15:08:12 +00004573
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004574 QualType CFTy = Context.getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00004575
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004576 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00004577
John McCall23c9dc62016-11-28 22:18:27 +00004578 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00004579 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00004580
Anders Carlssonb04ea612007-08-21 00:21:21 +00004581 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004582 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00004583
Anders Carlssonb04ea612007-08-21 00:21:21 +00004584 // Flags.
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004585 if (IsSwiftABI) {
4586 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4587 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4588 } else {
4589 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4590 }
Anders Carlsson157c3212009-08-16 05:55:31 +00004591
Anders Carlssonb04ea612007-08-21 00:21:21 +00004592 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00004593 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00004594 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00004595 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00004596 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4597 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00004598 C = llvm::ConstantDataArray::get(VMContext, Arr);
4599 } else {
David Blaikie13156b62014-11-19 03:06:06 +00004600 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00004601 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00004602
Bill Wendling86131f22012-01-10 08:46:39 +00004603 // Note: -fwritable-strings doesn't make the backing store strings of
4604 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004605 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00004606 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4607 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004608 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00004609 // Don't enforce the target's minimum global alignment, since the only use
4610 // of the string is via this class initializer.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004611 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4612 : Context.getTypeAlignInChars(Context.CharTy);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004613 GV->setAlignment(Align.getQuantity());
4614
4615 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4616 // Without it LLVM can merge the string with a non unnamed_addr one during
4617 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004618 if (Triple.isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004619 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4620 : "__TEXT,__cstring,cstring_literals");
Kristina Brooks34e24d52018-09-25 22:27:40 +00004621 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4622 // the static linker to adjust permissions to read-only later on.
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004623 else if (Triple.isOSBinFormatELF())
Kristina Brooks34e24d52018-09-25 22:27:40 +00004624 GV->setSection(".rodata");
Takuto Ikuta8aa53702018-10-17 04:29:56 +00004625
Bill Wendling82b87f12012-03-30 00:26:17 +00004626 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004627 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00004628 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00004629
Bill Wendling82b87f12012-03-30 00:26:17 +00004630 if (isUTF16)
4631 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004632 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4633 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00004634
Anders Carlssonb04ea612007-08-21 00:21:21 +00004635 // String length.
Saleem Abdulrasool81a650e2018-10-24 23:28:28 +00004636 llvm::IntegerType *LengthTy =
4637 llvm::IntegerType::get(getModule().getContext(),
4638 Context.getTargetInfo().getLongWidth());
4639 if (IsSwiftABI) {
4640 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4641 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4642 LengthTy = Int32Ty;
4643 else
4644 LengthTy = IntPtrTy;
4645 }
4646 Fields.addInt(LengthTy, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004647
John McCall7f416cc2015-09-08 08:05:57 +00004648 CharUnits Alignment = getPointerAlign();
4649
Anders Carlssonb04ea612007-08-21 00:21:21 +00004650 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004651 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4652 /*isConstant=*/false,
4653 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasoold5a27882018-10-24 16:56:36 +00004654 switch (Triple.getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004655 case llvm::Triple::UnknownObjectFormat:
4656 llvm_unreachable("unknown file format");
Jason Liua03ae732019-03-12 22:01:10 +00004657 case llvm::Triple::XCOFF:
4658 llvm_unreachable("XCOFF is not yet implemented");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004659 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004660 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00004661 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00004662 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004663 break;
4664 case llvm::Triple::MachO:
4665 GV->setSection("__DATA,__cfstring");
4666 break;
4667 }
David Blaikie13156b62014-11-19 03:06:06 +00004668 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00004669
John McCall7f416cc2015-09-08 08:05:57 +00004670 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00004671}
Chris Lattnerfb300092007-11-28 05:34:05 +00004672
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00004673bool CodeGenModule::getExpressionLocationsEnabled() const {
4674 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4675}
4676
Douglas Gregor636e2002011-08-09 17:23:49 +00004677QualType CodeGenModule::getObjCFastEnumerationStateType() {
4678 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004679 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00004680 D->startDefinition();
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004681
Douglas Gregor636e2002011-08-09 17:23:49 +00004682 QualType FieldTypes[] = {
4683 Context.UnsignedLongTy,
4684 Context.getPointerType(Context.getObjCIdType()),
4685 Context.getPointerType(Context.UnsignedLongTy),
4686 Context.getConstantArrayType(Context.UnsignedLongTy,
4687 llvm::APInt(32, 5), ArrayType::Normal, 0)
4688 };
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004689
Douglas Gregor636e2002011-08-09 17:23:49 +00004690 for (size_t i = 0; i < 4; ++i) {
4691 FieldDecl *Field = FieldDecl::Create(Context,
4692 D,
4693 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004694 SourceLocation(), nullptr,
4695 FieldTypes[i], /*TInfo=*/nullptr,
4696 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00004697 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004698 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00004699 Field->setAccess(AS_public);
4700 D->addDecl(Field);
4701 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004702
Douglas Gregor636e2002011-08-09 17:23:49 +00004703 D->completeDefinition();
4704 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4705 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004706
Douglas Gregor636e2002011-08-09 17:23:49 +00004707 return ObjCFastEnumerationStateType;
4708}
4709
Eli Friedmanfcec6302011-11-01 02:23:42 +00004710llvm::Constant *
4711CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4712 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004713
Eli Friedmanfcec6302011-11-01 02:23:42 +00004714 // Don't emit it as the address of the string, emit the string data itself
4715 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00004716 if (E->getCharByteWidth() == 1) {
4717 SmallString<64> Str(E->getString());
4718
4719 // Resize the string to the right size, which is indicated by its type.
4720 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4721 Str.resize(CAT->getSize().getZExtValue());
4722 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4723 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004724
4725 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00004726 llvm::Type *ElemTy = AType->getElementType();
4727 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00004728
4729 // Wide strings have either 2-byte or 4-byte elements.
4730 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4731 SmallVector<uint16_t, 32> Elements;
4732 Elements.reserve(NumElements);
4733
4734 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4735 Elements.push_back(E->getCodeUnit(i));
4736 Elements.resize(NumElements);
4737 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00004738 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004739
Chris Lattner02cb1712012-02-06 22:52:04 +00004740 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4741 SmallVector<uint32_t, 32> Elements;
4742 Elements.reserve(NumElements);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004743
Chris Lattner02cb1712012-02-06 22:52:04 +00004744 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4745 Elements.push_back(E->getCodeUnit(i));
4746 Elements.resize(NumElements);
4747 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00004748}
4749
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004750static llvm::GlobalVariable *
4751GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4752 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00004753 CharUnits Alignment) {
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004754 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4755 CGM.getStringLiteralAddressSpace());
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004756
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004757 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004758 // Create a global variable for this string
4759 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004760 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4761 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00004762 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004763 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004764 if (GV->isWeakForLinker()) {
4765 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4766 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4767 }
Rafael Espindola0d40f122018-03-20 20:42:55 +00004768 CGM.setDSOLocal(GV);
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004769
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004770 return GV;
4771}
4772
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004773/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4774/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00004775ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00004776CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4777 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00004778 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00004779
Richard Smith00db2f12014-07-29 21:20:12 +00004780 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4781 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00004782 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004783 Entry = &ConstantStringMap[C];
4784 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004785 if (Alignment.getQuantity() > GV->getAlignment())
4786 GV->setAlignment(Alignment.getQuantity());
Michael Liao0ee7bd42019-02-21 19:40:20 +00004787 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4788 Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00004789 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00004790 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00004791
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004792 SmallString<256> MangledNameBuffer;
4793 StringRef GlobalVariableName;
4794 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00004795
Reid Kleckner7a368962018-09-06 18:25:39 +00004796 // Mangle the string literal if that's how the ABI merges duplicate strings.
4797 // Don't do it if they are writable, since we don't want writes in one TU to
4798 // affect strings in another.
4799 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4800 !LangOpts.WritableStrings) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004801 llvm::raw_svector_ostream Out(MangledNameBuffer);
4802 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004803 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4804 GlobalVariableName = MangledNameBuffer;
4805 } else {
4806 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00004807 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00004808 }
4809
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004810 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4811 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004812 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00004813
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00004814 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4815 QualType());
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004816
4817 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4818 Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004819}
4820
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004821/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4822/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00004823ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004824CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4825 std::string Str;
4826 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00004827
4828 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004829}
4830
Alexey Samsonovadc90372014-06-04 20:25:57 +00004831/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4832/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004833/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00004834ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4835 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00004836 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00004837 CharUnits Alignment =
4838 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004839
Richard Smith00db2f12014-07-29 21:20:12 +00004840 llvm::Constant *C =
4841 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4842
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004843 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00004844 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004845 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004846 Entry = &ConstantStringMap[C];
4847 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004848 if (Alignment.getQuantity() > GV->getAlignment())
4849 GV->setAlignment(Alignment.getQuantity());
Michael Liao0ee7bd42019-02-21 19:40:20 +00004850 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4851 Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004852 }
4853 }
4854
Daniel Dunbar08b216a2009-03-31 23:42:16 +00004855 // Get the default prefix if a name wasn't specified.
4856 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00004857 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00004858 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004859 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4860 GlobalName, Alignment);
4861 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004862 *Entry = GV;
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004863
4864 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4865 Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00004866}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004867
John McCall7f416cc2015-09-08 08:05:57 +00004868ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00004869 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00004870 assert((E->getStorageDuration() == SD_Static ||
4871 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004872 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00004873
4874 // If we're not materializing a subobject of the temporary, keep the
4875 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00004876 QualType MaterializedType = Init->getType();
4877 if (Init == E->GetTemporaryExpr())
4878 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004879
John McCall7f416cc2015-09-08 08:05:57 +00004880 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4881
David Majnemer2dcef9e2015-08-13 23:50:15 +00004882 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00004883 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004884
4885 // FIXME: If an externally-visible declaration extends multiple temporaries,
4886 // we need to give each temporary the same name in every translation unit (and
4887 // we also need to make the temporaries externally-visible).
4888 SmallString<256> Name;
4889 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00004890 getCXXABI().getMangleContext().mangleReferenceTemporary(
4891 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00004892
Craig Topper8a13c412014-05-21 05:09:00 +00004893 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004894 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00004895 // We might have a cached constant initializer for this temporary. Note
4896 // that this might have a different value from the value computed by
4897 // evaluating the initializer if the surrounding constant expression
4898 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00004899 Value = getContext().getMaterializedTemporaryValue(E, false);
Richard Smithe637cbe2019-05-21 23:15:18 +00004900 if (Value && Value->isAbsent())
Craig Topper8a13c412014-05-21 05:09:00 +00004901 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004902 }
4903
Richard Smitha509f2f2013-06-14 03:07:01 +00004904 // Try evaluating it now, it might have a constant initializer.
4905 Expr::EvalResult EvalResult;
4906 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4907 !EvalResult.hasSideEffects())
4908 Value = &EvalResult.Val;
4909
Alexander Richardson6d989432017-10-15 18:48:14 +00004910 LangAS AddrSpace =
John McCallde0fe072017-08-15 21:42:52 +00004911 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4912
4913 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00004914 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00004915 bool Constant = false;
4916 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00004917 if (Value) {
4918 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00004919 emitter.emplace(*this);
4920 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4921 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00004922 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4923 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004924 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00004925 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00004926 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00004927 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00004928 }
4929
4930 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00004931 llvm::GlobalValue::LinkageTypes Linkage =
4932 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004933 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4934 const VarDecl *InitVD;
4935 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4936 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4937 // Temporaries defined inside a class get linkonce_odr linkage because the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004938 // class can be defined in multiple translation units.
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004939 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4940 } else {
4941 // There is no need for this temporary to have external linkage if the
4942 // VarDecl has external linkage.
4943 Linkage = llvm::GlobalVariable::InternalLinkage;
4944 }
4945 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00004946 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004947 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00004948 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00004949 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00004950 if (emitter) emitter->finalize(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +00004951 setGVProperties(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00004952 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004953 if (supportsCOMDAT() && GV->isWeakForLinker())
4954 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00004955 if (VD->getTLSKind())
4956 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00004957 llvm::Constant *CV = GV;
4958 if (AddrSpace != LangAS::Default)
4959 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4960 *this, GV, AddrSpace, LangAS::Default,
4961 Type->getPointerTo(
4962 getContext().getTargetAddressSpace(LangAS::Default)));
4963 MaterializedGlobalTemporaryMap[E] = CV;
4964 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004965}
4966
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004967/// EmitObjCPropertyImplementations - Emit information for synthesized
4968/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00004969void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004970 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004971 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004972 // Dynamic is just for type-checking.
4973 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4974 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4975
4976 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00004977 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004978 // we want, that just indicates if the decl came from a
4979 // property. What we want to know is if the method is defined in
4980 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004981 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004982 CodeGenFunction(*this).GenerateObjCGetter(
4983 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004984 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004985 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004986 CodeGenFunction(*this).GenerateObjCSetter(
4987 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004988 }
4989 }
4990}
4991
John McCall6a4fa522011-03-22 07:05:39 +00004992static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004993 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4994 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00004995 ivar; ivar = ivar->getNextIvar())
4996 if (ivar->getType().isDestructedType())
4997 return true;
4998
4999 return false;
5000}
5001
Fariborz Jahanian800821a2014-11-12 22:37:43 +00005002static bool AllTrivialInitializers(CodeGenModule &CGM,
5003 ObjCImplementationDecl *D) {
5004 CodeGenFunction CGF(CGM);
5005 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5006 E = D->init_end(); B != E; ++B) {
5007 CXXCtorInitializer *CtorInitExp = *B;
5008 Expr *Init = CtorInitExp->getInit();
5009 if (!CGF.isTrivialInitializer(Init))
5010 return false;
5011 }
5012 return true;
5013}
5014
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00005015/// EmitObjCIvarInitializations - Emit information for ivar initialization
5016/// for an implementation.
5017void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00005018 // We might need a .cxx_destruct even if we don't have any ivar initializers.
5019 if (needsDestructMethod(D)) {
5020 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5021 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5022 ObjCMethodDecl *DTORMethod =
5023 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00005024 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00005025 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00005026 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00005027 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00005028 D->addInstanceMethod(DTORMethod);
5029 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00005030 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00005031 }
5032
5033 // If the implementation doesn't have any ivar initializers, we don't need
5034 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00005035 if (D->getNumIvarInitializers() == 0 ||
5036 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00005037 return;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00005038
John McCall6a4fa522011-03-22 07:05:39 +00005039 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5040 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00005041 // The constructor returns 'self'.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00005042 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00005043 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00005044 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00005045 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00005046 getContext().getObjCIdType(),
5047 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00005048 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00005049 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00005050 /*isImplicitlyDeclared=*/true,
5051 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00005052 ObjCMethodDecl::Required);
5053 D->addInstanceMethod(CTORMethod);
5054 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00005055 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00005056}
5057
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00005058// EmitLinkageSpec - Emit all declarations in a linkage spec.
5059void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00005060 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5061 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00005062 ErrorUnsupported(LSD, "linkage spec");
5063 return;
5064 }
5065
Richard Smith8df390f2016-09-08 23:14:54 +00005066 EmitDeclContext(LSD);
5067}
5068
5069void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5070 for (auto *I : DC->decls()) {
5071 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5072 // are themselves considered "top-level", so EmitTopLevelDecl on an
5073 // ObjCImplDecl does not recursively visit them. We need to do that in
5074 // case they're nested inside another construct (LinkageSpecDecl /
5075 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00005076 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00005077 for (auto *M : OID->methods())
5078 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00005079 }
Richard Smith8df390f2016-09-08 23:14:54 +00005080
Aaron Ballman629afae2014-03-07 19:56:05 +00005081 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00005082 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00005083}
5084
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005085/// EmitTopLevelDecl - Emit code for a single top level declaration.
5086void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00005087 // Ignore dependent declarations.
Richard Smith32b615c2018-02-01 00:28:36 +00005088 if (D->isTemplated())
Douglas Gregor70d83e22009-06-29 17:30:29 +00005089 return;
Mike Stump11289f42009-09-09 15:08:12 +00005090
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005091 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00005092 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00005093 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005094 case Decl::Function:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00005095 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00005096 // Always provide some coverage mapping
5097 // even for the functions that aren't emitted.
5098 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00005099 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00005100
Richard Smithada08882017-04-19 21:15:45 +00005101 case Decl::CXXDeductionGuide:
5102 // Function-like, but does not result in code emission.
5103 break;
5104
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005105 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00005106 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00005107 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00005108 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00005109 if (auto *DD = dyn_cast<DecompositionDecl>(D))
5110 for (auto *B : DD->bindings())
5111 if (auto *HD = B->getHoldingVar())
5112 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005113 break;
5114
John McCall32f44bd2011-04-12 01:01:22 +00005115 // Indirect fields from global anonymous structs and unions can be
5116 // ignored; only the actual variable requires IR gen support.
5117 case Decl::IndirectField:
5118 break;
5119
Anders Carlssonf7475242009-04-15 15:55:24 +00005120 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005121 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00005122 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005123 break;
Richard Smithe1246122017-11-03 01:26:01 +00005124 case Decl::ClassTemplateSpecialization: {
5125 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5126 if (DebugInfo &&
5127 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
5128 Spec->hasDefinition())
5129 DebugInfo->completeTemplateDefinition(*Spec);
5130 } LLVM_FALLTHROUGH;
Richard Smith62f19e72016-06-25 00:15:56 +00005131 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00005132 if (DebugInfo) {
5133 if (auto *ES = D->getASTContext().getExternalSource())
5134 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5135 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
5136 }
Richard Smith62f19e72016-06-25 00:15:56 +00005137 // Emit any static data members, they may be definitions.
5138 for (auto *I : cast<CXXRecordDecl>(D)->decls())
5139 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5140 EmitTopLevelDecl(I);
5141 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00005142 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00005143 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00005144 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00005145 case Decl::VarTemplate:
5146 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00005147 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00005148 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00005149 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00005150 case Decl::Empty:
Richard Smith7c7e5312018-10-26 03:21:20 +00005151 case Decl::Binding:
Douglas Gregorfec52632009-06-20 00:51:54 +00005152 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00005153 case Decl::Using: // using X; [C++]
5154 if (CGDebugInfo *DI = getModuleDebugInfo())
5155 DI->EmitUsingDecl(cast<UsingDecl>(*D));
5156 return;
David Blaikief121b932013-05-20 22:50:41 +00005157 case Decl::NamespaceAlias:
5158 if (CGDebugInfo *DI = getModuleDebugInfo())
5159 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5160 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00005161 case Decl::UsingDirective: // using namespace X; [C++]
5162 if (CGDebugInfo *DI = getModuleDebugInfo())
5163 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5164 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00005165 case Decl::CXXConstructor:
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00005166 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00005167 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00005168 case Decl::CXXDestructor:
Reid Klecknere7de47e2013-07-22 13:51:44 +00005169 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00005170 break;
Anders Carlsson87835432009-06-11 21:22:55 +00005171
5172 case Decl::StaticAssert:
5173 // Nothing to do.
5174 break;
5175
Anders Carlssonf7475242009-04-15 15:55:24 +00005176 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00005177
Fariborz Jahanian3654e652009-03-18 22:33:24 +00005178 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00005179 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00005180 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00005181 break;
5182
Douglas Gregorf6102672012-01-01 21:23:57 +00005183 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005184 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00005185 if (Proto->isThisDeclarationADefinition())
5186 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005187 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00005188 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00005189
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005190 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00005191 // Categories have properties but don't support synthesize so we
5192 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00005193 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005194 break;
5195
Daniel Dunbar89654ee2008-08-26 08:29:31 +00005196 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005197 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00005198 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00005199 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00005200 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00005201 // Emit global variable debug information.
5202 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00005203 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00005204 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5205 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005206 break;
Mike Stump11289f42009-09-09 15:08:12 +00005207 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005208 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005209 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005210 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005211 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005212 CodeGenFunction(*this).GenerateObjCMethod(OMD);
5213 break;
5214 }
Mike Stump11289f42009-09-09 15:08:12 +00005215 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00005216 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005217 break;
5218
Nico Weber66220292016-03-02 17:28:48 +00005219 case Decl::PragmaComment: {
5220 const auto *PCD = cast<PragmaCommentDecl>(D);
5221 switch (PCD->getCommentKind()) {
5222 case PCK_Unknown:
5223 llvm_unreachable("unexpected pragma comment kind");
5224 case PCK_Linker:
5225 AppendLinkerOptions(PCD->getArg());
5226 break;
5227 case PCK_Lib:
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00005228 AddDependentLib(PCD->getArg());
Nico Weber66220292016-03-02 17:28:48 +00005229 break;
5230 case PCK_Compiler:
5231 case PCK_ExeStr:
5232 case PCK_User:
5233 break; // We ignore all of these.
5234 }
5235 break;
5236 }
5237
Nico Webercbbaeb12016-03-02 19:28:54 +00005238 case Decl::PragmaDetectMismatch: {
5239 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5240 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5241 break;
5242 }
5243
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00005244 case Decl::LinkageSpec:
5245 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005246 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005247
5248 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00005249 // File-scope asm is ignored during device-side CUDA compilation.
5250 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5251 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005252 // File-scope asm is ignored during device-side OpenMP compilation.
5253 if (LangOpts.OpenMPIsDevice)
5254 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005255 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00005256 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005257 break;
5258 }
Mike Stump11289f42009-09-09 15:08:12 +00005259
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005260 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005261 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005262
Richard Smithdc1f0422016-07-20 19:10:16 +00005263 // If we've already imported this module, we're done.
5264 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00005265 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005266
Richard Smithdc1f0422016-07-20 19:10:16 +00005267 // Emit debug information for direct imports.
5268 if (!Import->getImportedOwningModule()) {
5269 if (CGDebugInfo *DI = getModuleDebugInfo())
5270 DI->EmitImportDecl(*Import);
5271 }
5272
Manman Ren3b5dbf22016-10-14 18:55:44 +00005273 // Find all of the submodules and emit the module initializers.
5274 llvm::SmallPtrSet<clang::Module *, 16> Visited;
5275 SmallVector<clang::Module *, 16> Stack;
5276 Visited.insert(Import->getImportedModule());
5277 Stack.push_back(Import->getImportedModule());
5278
5279 while (!Stack.empty()) {
5280 clang::Module *Mod = Stack.pop_back_val();
5281 if (!EmittedModuleInitializers.insert(Mod).second)
5282 continue;
5283
5284 for (auto *D : Context.getModuleInitializers(Mod))
5285 EmitTopLevelDecl(D);
5286
5287 // Visit the submodules of this module.
5288 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5289 SubEnd = Mod->submodule_end();
5290 Sub != SubEnd; ++Sub) {
5291 // Skip explicit children; they need to be explicitly imported to emit
5292 // the initializers.
5293 if ((*Sub)->IsExplicit)
5294 continue;
5295
5296 if (Visited.insert(*Sub).second)
5297 Stack.push_back(*Sub);
5298 }
5299 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00005300 break;
David Blaikie0e716b42014-03-03 23:48:23 +00005301 }
5302
Richard Smith8df390f2016-09-08 23:14:54 +00005303 case Decl::Export:
5304 EmitDeclContext(cast<ExportDecl>(D));
5305 break;
5306
Alexey Bataev97720002014-11-11 04:05:39 +00005307 case Decl::OMPThreadPrivate:
5308 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5309 break;
5310
Alexey Bataev25ed0c02019-03-07 17:54:44 +00005311 case Decl::OMPAllocate:
5312 break;
5313
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005314 case Decl::OMPDeclareReduction:
5315 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5316 break;
Takuto Ikuta8aa53702018-10-17 04:29:56 +00005317
Michael Kruse251e1482019-02-01 20:25:04 +00005318 case Decl::OMPDeclareMapper:
5319 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5320 break;
5321
Kelvin Li1408f912018-09-26 04:28:39 +00005322 case Decl::OMPRequires:
5323 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5324 break;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00005325
Mike Stump11289f42009-09-09 15:08:12 +00005326 default:
Mike Stump18bb9282009-05-16 07:57:57 +00005327 // Make sure we handled everything we should, every other kind is a
5328 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
5329 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005330 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00005331 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00005332 }
5333}
John McCall09ae0322010-07-06 23:57:41 +00005334
Alex Lorenzee024992014-08-04 18:41:51 +00005335void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5336 // Do we need to generate coverage mapping?
5337 if (!CodeGenOpts.CoverageMapping)
5338 return;
5339 switch (D->getKind()) {
5340 case Decl::CXXConversion:
5341 case Decl::CXXMethod:
5342 case Decl::Function:
5343 case Decl::ObjCMethod:
5344 case Decl::CXXConstructor:
5345 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00005346 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00005347 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00005348 SourceManager &SM = getContext().getSourceManager();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005349 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
Vedant Kumar0acf3432017-09-22 18:23:04 +00005350 return;
Alex Lorenzee024992014-08-04 18:41:51 +00005351 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5352 if (I == DeferredEmptyCoverageMappingDecls.end())
5353 DeferredEmptyCoverageMappingDecls[D] = true;
5354 break;
5355 }
5356 default:
5357 break;
5358 };
5359}
5360
5361void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5362 // Do we need to generate coverage mapping?
5363 if (!CodeGenOpts.CoverageMapping)
5364 return;
5365 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5366 if (Fn->isTemplateInstantiation())
5367 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5368 }
5369 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5370 if (I == DeferredEmptyCoverageMappingDecls.end())
5371 DeferredEmptyCoverageMappingDecls[D] = false;
5372 else
5373 I->second = false;
5374}
5375
5376void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Eli Friedman8516b7f2017-12-19 01:54:09 +00005377 // We call takeVector() here to avoid use-after-free.
5378 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5379 // we deserialize function bodies to emit coverage info for them, and that
5380 // deserializes more declarations. How should we handle that case?
5381 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
Eli Friedmandbcfade2017-12-13 00:14:17 +00005382 if (!Entry.second)
Alex Lorenzee024992014-08-04 18:41:51 +00005383 continue;
Eli Friedmandbcfade2017-12-13 00:14:17 +00005384 const Decl *D = Entry.first;
Alex Lorenzee024992014-08-04 18:41:51 +00005385 switch (D->getKind()) {
5386 case Decl::CXXConversion:
5387 case Decl::CXXMethod:
5388 case Decl::Function:
5389 case Decl::ObjCMethod: {
5390 CodeGenPGO PGO(*this);
5391 GlobalDecl GD(cast<FunctionDecl>(D));
5392 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5393 getFunctionLinkage(GD));
5394 break;
5395 }
5396 case Decl::CXXConstructor: {
5397 CodeGenPGO PGO(*this);
5398 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5399 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5400 getFunctionLinkage(GD));
5401 break;
5402 }
5403 case Decl::CXXDestructor: {
5404 CodeGenPGO PGO(*this);
5405 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5406 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5407 getFunctionLinkage(GD));
5408 break;
5409 }
5410 default:
5411 break;
5412 };
5413 }
5414}
5415
John McCall09ae0322010-07-06 23:57:41 +00005416/// Turns the given pointer into a constant.
5417static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5418 const void *Ptr) {
5419 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00005420 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00005421 return llvm::ConstantInt::get(i64, PtrInt);
5422}
5423
5424static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5425 llvm::NamedMDNode *&GlobalMetadata,
5426 GlobalDecl D,
5427 llvm::GlobalValue *Addr) {
5428 if (!GlobalMetadata)
5429 GlobalMetadata =
5430 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5431
5432 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005433 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5434 llvm::ConstantAsMetadata::get(GetPointerConstant(
5435 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00005436 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00005437}
5438
Richard Smithdf931ce2013-04-06 05:00:46 +00005439/// For each function which is declared within an extern "C" region and marked
5440/// as 'used', but has internal linkage, create an alias from the unmangled
5441/// name to the mangled name if possible. People expect to be able to refer
5442/// to such functions with an unmangled name from inline assembly within the
5443/// same translation unit.
5444void CodeGenModule::EmitStaticExternCAliases() {
Yaxun Liub0eee292018-03-29 14:50:00 +00005445 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00005446 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00005447 for (auto &I : StaticExternCValues) {
5448 IdentifierInfo *Name = I.first;
5449 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00005450 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00005451 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00005452 }
Richard Smithdf931ce2013-04-06 05:00:46 +00005453}
5454
Alp Tokerfb8d02b2014-06-05 22:10:59 +00005455bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5456 GlobalDecl &Result) const {
5457 auto Res = Manglings.find(MangledName);
5458 if (Res == Manglings.end())
5459 return false;
5460 Result = Res->getValue();
5461 return true;
5462}
5463
John McCall09ae0322010-07-06 23:57:41 +00005464/// Emits metadata nodes associating all the global values in the
5465/// current module with the Decls they came from. This is useful for
5466/// projects using IR gen as a subroutine.
5467///
5468/// Since there's currently no way to associate an MDNode directly
5469/// with an llvm::GlobalValue, we create a global named metadata
5470/// with the name 'clang.global.decl.ptrs'.
5471void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00005472 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005473
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005474 for (auto &I : MangledDeclNames) {
5475 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00005476 // Some mangled names don't necessarily have an associated GlobalValue
5477 // in this module, e.g. if we mangled it for DebugInfo.
5478 if (Addr)
5479 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00005480 }
5481}
5482
5483/// Emits metadata nodes for all the local variables in the current
5484/// function.
5485void CodeGenFunction::EmitDeclMetadata() {
5486 if (LocalDeclMap.empty()) return;
5487
5488 llvm::LLVMContext &Context = getLLVMContext();
5489
5490 // Find the unique metadata ID for this name.
5491 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5492
Craig Topper8a13c412014-05-21 05:09:00 +00005493 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005494
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005495 for (auto &I : LocalDeclMap) {
5496 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00005497 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005498 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005499 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005500 Alloca->setMetadata(
5501 DeclPtrKind, llvm::MDNode::get(
5502 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005503 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005504 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5505 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5506 }
5507 }
5508}
Daniel Dunbar900546d2010-07-16 00:00:15 +00005509
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005510void CodeGenModule::EmitVersionIdentMetadata() {
5511 llvm::NamedMDNode *IdentMetadata =
5512 TheModule.getOrInsertNamedMetadata("llvm.ident");
5513 std::string Version = getClangFullVersion();
5514 llvm::LLVMContext &Ctx = TheModule.getContext();
5515
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005516 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005517 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5518}
5519
Scott Linderde6beb02018-12-14 15:38:15 +00005520void CodeGenModule::EmitCommandLineMetadata() {
5521 llvm::NamedMDNode *CommandLineMetadata =
5522 TheModule.getOrInsertNamedMetadata("llvm.commandline");
5523 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5524 llvm::LLVMContext &Ctx = TheModule.getContext();
5525
5526 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5527 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5528}
5529
Robert Lytton57765d52014-07-03 09:30:33 +00005530void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00005531 // Warning, new MangledDeclNames may be appended within this loop.
5532 // We rely on MapVector insertions adding new elements to the end
5533 // of the container.
5534 // FIXME: Move this loop into the one target that needs it, and only
5535 // loop over those declarations for which we couldn't emit the target
5536 // metadata when we emitted the declaration.
5537 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00005538 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00005539 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5540 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00005541 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5542 }
5543}
5544
Nick Lewycky85c011d2011-05-05 00:08:20 +00005545void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00005546 if (getCodeGenOpts().CoverageDataFile.empty() &&
5547 getCodeGenOpts().CoverageNotesFile.empty())
5548 return;
5549
5550 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5551 if (!CUNode)
5552 return;
5553
5554 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5555 llvm::LLVMContext &Ctx = TheModule.getContext();
5556 auto *CoverageDataFile =
5557 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5558 auto *CoverageNotesFile =
5559 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5560 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5561 llvm::MDNode *CU = CUNode->getOperand(i);
5562 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5563 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00005564 }
5565}
Nico Webercf4ff5862012-10-11 10:13:44 +00005566
Nico Weber17d3a2c2014-09-08 16:26:36 +00005567llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00005568 // Sema has checked that all uuid strings are of the form
5569 // "12345678-1234-1234-1234-1234567890ab".
5570 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00005571 for (unsigned i = 0; i < 36; ++i) {
5572 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5573 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00005574 }
Nico Webercf4ff5862012-10-11 10:13:44 +00005575
Nico Weberdfa274e2014-09-08 16:11:15 +00005576 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00005577 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00005578
David Majnemerbbecd092013-08-15 19:59:14 +00005579 llvm::Constant *Field3[8];
5580 for (unsigned Idx = 0; Idx < 8; ++Idx)
5581 Field3[Idx] = llvm::ConstantInt::get(
5582 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5583
5584 llvm::Constant *Fields[4] = {
5585 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5586 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5587 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5588 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5589 };
5590
5591 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00005592}
David Majnemere2cb8d12014-07-07 06:20:47 +00005593
5594llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5595 bool ForEH) {
5596 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5597 // FIXME: should we even be calling this method if RTTI is disabled
5598 // and it's not for EH?
Yaxun Liu6328f9a2018-06-05 15:11:02 +00005599 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
David Majnemere2cb8d12014-07-07 06:20:47 +00005600 return llvm::Constant::getNullValue(Int8PtrTy);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00005601
David Majnemere2cb8d12014-07-07 06:20:47 +00005602 if (ForEH && Ty->isObjCObjectPointerType() &&
5603 LangOpts.ObjCRuntime.isGNUFamily())
5604 return ObjCRuntime->GetEHType(Ty);
5605
David Majnemer443250f2015-03-17 20:35:00 +00005606 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00005607}
5608
Alexey Bataev97720002014-11-11 04:05:39 +00005609void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005610 // Do not emit threadprivates in simd-only mode.
5611 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5612 return;
Alexey Bataev97720002014-11-11 04:05:39 +00005613 for (auto RefExpr : D->varlists()) {
5614 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5615 bool PerformInit =
5616 VD->getAnyInitializer() &&
5617 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5618 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00005619
5620 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00005621 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005622 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00005623 CXXGlobalInits.push_back(InitFunction);
5624 }
5625}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005626
Peter Collingbournee44acad2018-06-26 02:15:47 +00005627llvm::Metadata *
5628CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5629 StringRef Suffix) {
5630 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005631 if (InternalId)
5632 return InternalId;
5633
5634 if (isExternallyVisible(T->getLinkage())) {
5635 std::string OutName;
5636 llvm::raw_string_ostream Out(OutName);
5637 getCXXABI().getMangleContext().mangleTypeName(T, Out);
Peter Collingbournee44acad2018-06-26 02:15:47 +00005638 Out << Suffix;
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005639
5640 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5641 } else {
5642 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5643 llvm::ArrayRef<llvm::Metadata *>());
5644 }
5645
5646 return InternalId;
5647}
5648
Peter Collingbournee44acad2018-06-26 02:15:47 +00005649llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5650 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5651}
5652
5653llvm::Metadata *
5654CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5655 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5656}
5657
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005658// Generalize pointer types to a void pointer with the qualifiers of the
5659// originally pointed-to type, e.g. 'const char *' and 'char * const *'
5660// generalize to 'const void *' while 'char *' and 'const char **' generalize to
5661// 'void *'.
5662static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5663 if (!Ty->isPointerType())
5664 return Ty;
5665
5666 return Ctx.getPointerType(
5667 QualType(Ctx.VoidTy).withCVRQualifiers(
5668 Ty->getPointeeType().getCVRQualifiers()));
5669}
5670
5671// Apply type generalization to a FunctionType's return and argument types
5672static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5673 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5674 SmallVector<QualType, 8> GeneralizedParams;
5675 for (auto &Param : FnType->param_types())
5676 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5677
5678 return Ctx.getFunctionType(
5679 GeneralizeType(Ctx, FnType->getReturnType()),
5680 GeneralizedParams, FnType->getExtProtoInfo());
5681 }
5682
5683 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5684 return Ctx.getFunctionNoProtoType(
5685 GeneralizeType(Ctx, FnType->getReturnType()));
5686
5687 llvm_unreachable("Encountered unknown FunctionType");
5688}
5689
5690llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
Peter Collingbournee44acad2018-06-26 02:15:47 +00005691 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5692 GeneralizedMetadataIdMap, ".generalized");
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005693}
5694
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005695/// Returns whether this module needs the "all-vtables" type identifier.
5696bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005697 // Returns true if at least one of vtable-based CFI checkers is enabled and
5698 // is not in the trapping mode.
5699 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5700 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5701 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5702 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5703 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5704 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5705 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5706 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5707}
5708
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005709void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5710 CharUnits Offset,
5711 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005712 llvm::Metadata *MD =
5713 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005714 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005715
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005716 if (CodeGenOpts.SanitizeCfiCrossDso)
5717 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5718 VTable->addTypeMetadata(Offset.getQuantity(),
5719 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005720
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005721 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005722 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005723 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005724 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005725}
Eric Christopher2b90a642015-11-11 23:05:08 +00005726
Gabor Buella1a83d062018-06-07 08:48:36 +00005727TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5728 assert(TD != nullptr);
5729 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5730
5731 ParsedAttr.Features.erase(
5732 llvm::remove_if(ParsedAttr.Features,
5733 [&](const std::string &Feat) {
5734 return !Target.isValidFeatureName(
5735 StringRef{Feat}.substr(1));
5736 }),
5737 ParsedAttr.Features.end());
5738 return ParsedAttr;
5739}
5740
5741
Eric Christopher2b90a642015-11-11 23:05:08 +00005742// Fills in the supplied string map with the set of target features for the
5743// passed in function.
5744void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
Erich Keanede6480a32018-11-13 15:48:08 +00005745 GlobalDecl GD) {
Eric Christopher2b90a642015-11-11 23:05:08 +00005746 StringRef TargetCPU = Target.getTargetOpts().CPU;
Erich Keanede6480a32018-11-13 15:48:08 +00005747 const FunctionDecl *FD = GD.getDecl()->getAsFunction();
Eric Christopher2b90a642015-11-11 23:05:08 +00005748 if (const auto *TD = FD->getAttr<TargetAttr>()) {
Gabor Buella1a83d062018-06-07 08:48:36 +00005749 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
Erich Keanecf8807c2017-10-27 18:32:23 +00005750
Eric Christopher2b90a642015-11-11 23:05:08 +00005751 // Make a copy of the features as passed on the command line into the
5752 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00005753 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00005754 Target.getTargetOpts().FeaturesAsWritten.begin(),
5755 Target.getTargetOpts().FeaturesAsWritten.end());
5756
Erich Keanecf8807c2017-10-27 18:32:23 +00005757 if (ParsedAttr.Architecture != "" &&
5758 Target.isValidCPUName(ParsedAttr.Architecture))
5759 TargetCPU = ParsedAttr.Architecture;
Eric Christopher2b90a642015-11-11 23:05:08 +00005760
5761 // Now populate the feature map, first with the TargetCPU which is either
5762 // the default or a new one from the target attribute string. Then we'll use
5763 // the passed in features (FeaturesAsWritten) along with the new ones from
5764 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00005765 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5766 ParsedAttr.Features);
Erich Keane3efe0022018-07-20 14:13:28 +00005767 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5768 llvm::SmallVector<StringRef, 32> FeaturesTmp;
Erich Keanede6480a32018-11-13 15:48:08 +00005769 Target.getCPUSpecificCPUDispatchFeatures(
5770 SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
Erich Keane3efe0022018-07-20 14:13:28 +00005771 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5772 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00005773 } else {
5774 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5775 Target.getTargetOpts().Features);
5776 }
5777}
Peter Collingbournedc134532016-01-16 00:31:22 +00005778
5779llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5780 if (!SanStats)
5781 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5782
5783 return *SanStats;
5784}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005785llvm::Value *
5786CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5787 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00005788 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00005789 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005790 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5791 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5792 "__translate_sampler_initializer"),
5793 {C});
5794}