blob: 389f586443c8cf1b981dc61c68b0082b1ee5df31 [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
John McCall7f416cc2015-09-08 08:05:57 +000015#include "CGBlocks.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000016#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000017#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CGCall.h"
19#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000021#include "CGOpenCLRuntime.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "CGOpenMPRuntime.h"
Samuel Antao45bfe4c2016-02-08 15:59:20 +000023#include "CGOpenMPRuntimeNVPTX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000025#include "CodeGenPGO.h"
John McCallde0fe072017-08-15 21:42:52 +000026#include "ConstantEmitter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000027#include "CoverageMappingGen.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000028#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000029#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000030#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000031#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000033#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000035#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000036#include "clang/AST/RecursiveASTVisitor.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"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000039#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000040#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000041#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000042#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000043#include "clang/Basic/Version.h"
John McCall5ad74072017-03-02 20:04:19 +000044#include "clang/CodeGen/ConstantInitBuilder.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000045#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000046#include "clang/Sema/SemaDiagnostic.h"
John McCallbeec5a02010-03-06 00:35:14 +000047#include "llvm/ADT/Triple.h"
Matthias Brauna4519532017-05-20 01:29:55 +000048#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000049#include "llvm/IR/CallSite.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"
Justin Bogner837a6f62014-04-18 21:52:00 +000055#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000056#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000057#include "llvm/Support/ErrorHandling.h"
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +000058#include "llvm/Support/MD5.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000059
Chris Lattnerbed31442007-05-28 01:07:47 +000060using namespace clang;
61using namespace CodeGen;
62
Vedant Kumar0acf3432017-09-22 18:23:04 +000063static llvm::cl::opt<bool> LimitedCoverage(
Zachary Turner8065f0b2017-12-01 00:53:10 +000064 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
Vedant Kumar0acf3432017-09-22 18:23:04 +000065 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
66 llvm::cl::init(false));
67
Julien Lerouge5a6b6982011-09-09 22:41:49 +000068static const char AnnotationSection[] = "llvm.metadata";
69
Alp Toker82862252013-12-28 21:58:40 +000070static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000071 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000072 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000073 case TargetCXXABI::GenericARM:
74 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000075 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +000076 case TargetCXXABI::WatchOS:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000077 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000078 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +000079 case TargetCXXABI::WebAssembly:
Alp Toker82862252013-12-28 21:58:40 +000080 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000081 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000082 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000083 }
84
85 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000086}
87
Adrian Prantle74f5252015-06-30 02:26:03 +000088CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
89 const PreprocessorOptions &PPO,
90 const CodeGenOptions &CGO, llvm::Module &M,
Alex Lorenzee024992014-08-04 18:41:51 +000091 DiagnosticsEngine &diags,
92 CoverageSourceInfo *CoverageInfo)
Adrian Prantle74f5252015-06-30 02:26:03 +000093 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
94 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Mehdi Aminica3cf9e2015-07-24 16:04:29 +000095 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Reid Kleckner9305fd12016-04-13 23:37:17 +000096 VMContext(M.getContext()), Types(*this), VTables(*this),
Peter Collingbourne3afb2662016-04-28 17:09:37 +000097 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +000098
Chris Lattnerece04092012-02-07 00:39:47 +000099 // Initialize the type cache.
100 llvm::LLVMContext &LLVMContext = M.getContext();
101 VoidTy = llvm::Type::getVoidTy(LLVMContext);
102 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
Abderrazek Zaafranif58a1322017-12-21 19:20:01 +0000106 HalfTy = llvm::Type::getHalfTy(LLVMContext);
Chris Lattnerece04092012-02-07 00:39:47 +0000107 FloatTy = llvm::Type::getFloatTy(LLVMContext);
108 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
109 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
110 PointerAlignInBytes =
John McCall7f416cc2015-09-08 08:05:57 +0000111 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
Yaxun Liu26f75662016-08-19 05:17:25 +0000112 SizeSizeInBytes =
113 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +0000114 IntAlignInBytes =
115 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
Chris Lattnerece04092012-02-07 00:39:47 +0000116 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
Yaxun Liu26f75662016-08-19 05:17:25 +0000117 IntPtrTy = llvm::IntegerType::get(LLVMContext,
118 C.getTargetInfo().getMaxPointerWidth());
Chris Lattnerece04092012-02-07 00:39:47 +0000119 Int8PtrTy = Int8Ty->getPointerTo(0);
120 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000121 AllocaInt8PtrTy = Int8Ty->getPointerTo(
122 M.getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000123 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
Chris Lattnerece04092012-02-07 00:39:47 +0000124
John McCall882987f2013-02-28 19:01:20 +0000125 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
Anton Korobeynikovd90dd792014-12-02 16:04:58 +0000126 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
John McCall882987f2013-02-28 19:01:20 +0000127
David Blaikiebbafb8a2012-03-11 07:00:24 +0000128 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000129 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000130 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000131 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000132 if (LangOpts.OpenMP)
133 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000134 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000135 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000136
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000137 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000138 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000139 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000140 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
Reid Kleckner9305fd12016-04-13 23:37:17 +0000141 getCXXABI().getMangleContext()));
Dan Gohman947c9af2010-10-14 23:06:10 +0000142
Nick Lewycky207bce32011-04-21 23:44:07 +0000143 // If debug info or coverage generation is enabled, create the CGDebugInfo
144 // object.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000145 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
146 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000147 DebugInfo.reset(new CGDebugInfo(*this));
John McCallad7c5c12011-02-08 08:22:06 +0000148
149 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000150
John McCallb04ecb72015-10-21 18:06:43 +0000151 if (C.getLangOpts().ObjC1)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000152 ObjCData.reset(new ObjCEntrypoints());
Justin Bogneref512b92014-01-06 22:27:43 +0000153
Rong Xu9c6f1532016-03-02 20:59:36 +0000154 if (CodeGenOpts.hasProfileClangUse()) {
155 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
156 CodeGenOpts.ProfileInstrumentUsePath);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000157 if (auto E = ReaderOrErr.takeError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000158 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Diego Novillo5aecacb2015-06-25 22:56:00 +0000159 "Could not read profile %0: %1");
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000160 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
161 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
162 << EI.message();
163 });
Nico Weber176efac2015-04-06 04:16:48 +0000164 } else
165 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000166 }
Alex Lorenzee024992014-08-04 18:41:51 +0000167
168 // If coverage mapping generation is enabled, create the
169 // CoverageMappingModuleGen object.
170 if (CodeGenOpts.CoverageMapping)
171 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000172}
173
Reid Kleckner9305fd12016-04-13 23:37:17 +0000174CodeGenModule::~CodeGenModule() {}
Ted Kremenek2c674f62008-08-05 18:50:11 +0000175
David Chisnall481e3a82010-01-23 02:40:42 +0000176void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000177 // This is just isGNUFamily(), but we want to force implementors of
178 // new ABIs to decide how best to do this.
179 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000180 case ObjCRuntime::GNUstep:
181 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000182 case ObjCRuntime::ObjFW:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000183 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000184 return;
185
186 case ObjCRuntime::FragileMacOSX:
187 case ObjCRuntime::MacOSX:
188 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000189 case ObjCRuntime::WatchOS:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000190 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000191 return;
192 }
193 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000194}
195
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000196void CodeGenModule::createOpenCLRuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000197 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000198}
199
Alexey Bataev9959db52014-05-06 10:08:46 +0000200void CodeGenModule::createOpenMPRuntime() {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000201 // Select a specialized code generation class based on the target, if any.
202 // If it does not exist use the default implementation.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000203 switch (getTriple().getArch()) {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000204 case llvm::Triple::nvptx:
205 case llvm::Triple::nvptx64:
206 assert(getLangOpts().OpenMPIsDevice &&
207 "OpenMP NVPTX is only prepared to deal with device code.");
Reid Kleckner9305fd12016-04-13 23:37:17 +0000208 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000209 break;
210 default:
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000211 if (LangOpts.OpenMPSimd)
212 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
213 else
214 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000215 break;
216 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000217}
218
Peter Collingbournefe883422011-10-06 18:29:37 +0000219void CodeGenModule::createCUDARuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000220 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbournefe883422011-10-06 18:29:37 +0000221}
222
Rafael Espindola1e4df922014-09-16 15:18:21 +0000223void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
224 Replacements[Name] = C;
225}
226
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000227void CodeGenModule::applyReplacements() {
Yaron Kerenb54db522015-06-11 12:33:25 +0000228 for (auto &I : Replacements) {
229 StringRef MangledName = I.first();
230 llvm::Constant *Replacement = I.second;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000231 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
232 if (!Entry)
233 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000234 auto *OldF = cast<llvm::Function>(Entry);
235 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000236 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000237 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000238 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000239 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000240 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000241 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
242 CE->getOpcode() == llvm::Instruction::GetElementPtr);
243 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
244 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000245 }
246
247 // Replace old with new, but keep the old order.
248 OldF->replaceAllUsesWith(Replacement);
249 if (NewF) {
250 NewF->removeFromParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000251 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
252 NewF);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000253 }
254 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000255 }
256}
257
Andrey Bokhankocab58582015-08-31 13:20:44 +0000258void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
259 GlobalValReplacements.push_back(std::make_pair(GV, C));
260}
261
262void CodeGenModule::applyGlobalValReplacements() {
263 for (auto &I : GlobalValReplacements) {
264 llvm::GlobalValue *GV = I.first;
265 llvm::Constant *C = I.second;
266
267 GV->replaceAllUsesWith(C);
268 GV->eraseFromParent();
269 }
270}
271
Rafael Espindola27c60b52014-06-03 02:42:01 +0000272// This is only used in aliases that we created and we know they have a
273// linear structure.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000274static const llvm::GlobalObject *getAliasedGlobal(
275 const llvm::GlobalIndirectSymbol &GIS) {
276 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
277 const llvm::Constant *C = &GIS;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000278 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000279 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000280 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
281 return GO;
282 // stripPointerCasts will not walk over weak aliases.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000283 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
284 if (!GIS2)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000285 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000286 if (!Visited.insert(GIS2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000287 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000288 C = GIS2->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000289 }
290}
291
Rafael Espindola208b5c02013-10-22 19:26:13 +0000292void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000293 // Check if the constructed aliases are well formed. It is really unfortunate
294 // that we have to do this in CodeGen, but we only construct mangled names
295 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000296 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000297 DiagnosticsEngine &Diags = getDiags();
Yaron Kerenb54db522015-06-11 12:33:25 +0000298 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000299 const auto *D = cast<ValueDecl>(GD.getDecl());
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000300 SourceLocation Location;
301 bool IsIFunc = D->hasAttr<IFuncAttr>();
302 if (const Attr *A = D->getDefiningAttr())
303 Location = A->getLocation();
304 else
305 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindola208b5c02013-10-22 19:26:13 +0000306 StringRef MangledName = getMangledName(GD);
307 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000308 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000309 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
310 if (!GV) {
311 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000312 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000313 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000314 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000315 Diags.Report(Location, diag::err_alias_to_undefined)
316 << IsIFunc << IsIFunc;
317 } else if (IsIFunc) {
318 // Check resolver function type.
319 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
320 GV->getType()->getPointerElementType());
321 assert(FTy);
322 if (!FTy->getReturnType()->isPointerTy())
323 Diags.Report(Location, diag::err_ifunc_resolver_return);
324 if (FTy->getNumParams())
325 Diags.Report(Location, diag::err_ifunc_resolver_params);
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();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000401 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000402 if (ObjCRuntime)
403 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000404 AddGlobalCtor(ObjCInitFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000405 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
406 CUDARuntime) {
407 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
408 AddGlobalCtor(CudaCtorFunction);
409 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
410 AddGlobalDtor(CudaDtorFunction);
411 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000412 if (OpenMPRuntime)
413 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000414 OpenMPRuntime->emitRegistrationFunction()) {
415 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
416 OpenMPRegistrationFunction : nullptr;
417 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
418 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000419 if (PGOReader) {
Easwaran Raman81608122016-03-24 21:32:25 +0000420 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Easwaran Raman695890c2015-12-17 19:14:27 +0000421 if (PGOStats.hasDiagnostics())
422 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
423 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000424 EmitCtorList(GlobalCtors, "llvm.global_ctors");
425 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000426 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000427 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000428 EmitDeferredUnusedCoverageMappings();
429 if (CoverageMapping)
430 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000431 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000432 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000433 CodeGenFunction(*this).EmitCfiCheckStub();
434 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000435 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000436 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000437 if (SanStats)
438 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000439
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000440 if (CodeGenOpts.Autolink &&
441 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000442 EmitModuleLinkOptions();
443 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000444
Nirav Dave741dea02017-03-30 13:41:44 +0000445 // Record mregparm value now so it is visible through rest of codegen.
446 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
447 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
448 CodeGenOpts.NumRegisterParameters);
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000449
Reid Kleckner124955a2015-08-05 18:51:13 +0000450 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000451 // We actually want the latest version when there are conflicts.
452 // We can change from Warning to Latest if such mode is supported.
453 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
454 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000455 }
456 if (CodeGenOpts.EmitCodeView) {
457 // Indicate that we want CodeView in the metadata.
458 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
459 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000460 if (CodeGenOpts.ControlFlowGuard) {
461 // We want function ID tables for Control Flow Guard.
462 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
463 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000464 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
465 // We don't support LTO with 2 with different StrictVTablePointers
466 // FIXME: we could support it by stripping all the information introduced
467 // by StrictVTablePointers.
468
469 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
470
471 llvm::Metadata *Ops[2] = {
472 llvm::MDString::get(VMContext, "StrictVTablePointers"),
473 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
474 llvm::Type::getInt32Ty(VMContext), 1))};
475
476 getModule().addModuleFlag(llvm::Module::Require,
477 "StrictVTablePointersRequirement",
478 llvm::MDNode::get(VMContext, Ops));
479 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000480 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000481 // We support a single version in the linked module. The LLVM
482 // parser will drop debug info with a different version number
483 // (and warn about it, too).
484 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000485 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000486
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000487 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000488 // the correct build attributes in the ARM backend. wchar_size is also used by
489 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000490 uint64_t WCharWidth =
491 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000492 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
493
Justin Bogner9bb7f152014-06-23 20:03:28 +0000494 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000495 if ( Arch == llvm::Triple::arm
496 || Arch == llvm::Triple::armeb
497 || Arch == llvm::Triple::thumb
498 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000499 // The minimum width of an enum in bytes
500 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
501 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
502 }
503
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000504 if (CodeGenOpts.SanitizeCfiCrossDso) {
505 // Indicate that we want cross-DSO control flow integrity checks.
506 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
507 }
508
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000509 if (CodeGenOpts.CFProtectionReturn &&
510 Target.checkCFProtectionReturnSupported(getDiags())) {
511 // Indicate that we want to instrument return control flow protection.
512 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
513 1);
514 }
515
516 if (CodeGenOpts.CFProtectionBranch &&
517 Target.checkCFProtectionBranchSupported(getDiags())) {
518 // Indicate that we want to instrument branch control flow protection.
519 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
520 1);
521 }
522
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000523 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000524 // Indicate whether __nvvm_reflect should be configured to flush denormal
525 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
526 // property.)
527 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
528 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
529 }
530
Alexey Bader364a1162017-06-20 14:30:18 +0000531 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
532 if (LangOpts.OpenCL) {
533 EmitOpenCLMetadata();
534 // Emit SPIR version.
535 if (getTriple().getArch() == llvm::Triple::spir ||
536 getTriple().getArch() == llvm::Triple::spir64) {
537 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
538 // opencl.spir.version named metadata.
539 llvm::Metadata *SPIRVerElts[] = {
540 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
541 Int32Ty, LangOpts.OpenCLVersion / 100)),
542 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
543 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
544 llvm::NamedMDNode *SPIRVerMD =
545 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
546 llvm::LLVMContext &Ctx = TheModule.getContext();
547 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
548 }
549 }
550
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000551 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000552 assert(PLevel < 3 && "Invalid PIC Level");
553 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000554 if (Context.getLangOpts().PIE)
555 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000556 }
557
Sriraman Tallam80af0052018-02-23 21:27:33 +0000558 if (CodeGenOpts.NoPLT)
559 getModule().setRtLibUseGOT();
560
John McCall0bdb1fd2010-09-16 06:16:50 +0000561 SimplifyPersonality();
562
John McCall09ae0322010-07-06 23:57:41 +0000563 if (getCodeGenOpts().EmitDeclMetadata)
564 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000565
566 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000567 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000568
569 if (DebugInfo)
570 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000571
572 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000573
574 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000575}
576
Alexey Bader364a1162017-06-20 14:30:18 +0000577void CodeGenModule::EmitOpenCLMetadata() {
578 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
579 // opencl.ocl.version named metadata node.
580 llvm::Metadata *OCLVerElts[] = {
581 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
582 Int32Ty, LangOpts.OpenCLVersion / 100)),
583 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
584 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
585 llvm::NamedMDNode *OCLVerMD =
586 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
587 llvm::LLVMContext &Ctx = TheModule.getContext();
588 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
589}
590
Devang Patel945b8ae2011-03-23 16:29:39 +0000591void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
592 // Make sure that this type is translated.
593 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000594}
595
David Majnemer929025d2016-01-26 19:30:26 +0000596void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
597 // Make sure that this type is translated.
598 Types.RefreshTypeCacheForClass(RD);
599}
600
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000601llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
Dan Gohman947c9af2010-10-14 23:06:10 +0000602 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000603 return nullptr;
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000604 return TBAA->getTypeInfo(QTy);
Dan Gohman947c9af2010-10-14 23:06:10 +0000605}
606
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000607TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
Ivan A. Kosarev124a2182018-02-20 12:33:04 +0000608 if (!TBAA)
609 return TBAAAccessInfo();
610 return TBAA->getAccessInfo(AccessType);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000611}
612
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000613TBAAAccessInfo
614CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000615 if (!TBAA)
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000616 return TBAAAccessInfo();
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000617 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000618}
619
Dan Gohman22695fc2012-09-28 21:58:29 +0000620llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
621 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000622 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000623 return TBAA->getTBAAStructInfo(QTy);
624}
625
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000626llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
627 if (!TBAA)
628 return nullptr;
629 return TBAA->getBaseTypeInfo(QTy);
630}
631
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000632llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
Manman Renc451e572013-04-04 21:53:22 +0000633 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000634 return nullptr;
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000635 return TBAA->getAccessTagInfo(Info);
Manman Renc451e572013-04-04 21:53:22 +0000636}
637
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000638TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
639 TBAAAccessInfo TargetInfo) {
640 if (!TBAA)
641 return TBAAAccessInfo();
642 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
643}
644
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000645TBAAAccessInfo
646CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
647 TBAAAccessInfo InfoB) {
648 if (!TBAA)
649 return TBAAAccessInfo();
650 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
651}
652
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000653TBAAAccessInfo
654CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
655 TBAAAccessInfo SrcInfo) {
656 if (!TBAA)
657 return TBAAAccessInfo();
658 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
659}
660
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000661void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000662 TBAAAccessInfo TBAAInfo) {
663 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
664 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
Dan Gohman947c9af2010-10-14 23:06:10 +0000665}
666
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000667void CodeGenModule::DecorateInstructionWithInvariantGroup(
668 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000669 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
670 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000671}
672
Alp Toker29cb66b2014-01-26 06:17:37 +0000673void CodeGenModule::Error(SourceLocation loc, StringRef message) {
674 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
675 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000676}
677
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000678/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000679/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000680void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000681 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000682 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000683 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000684 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
685 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000686}
Chris Lattner41af8182007-12-02 06:27:33 +0000687
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000688/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000689/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000690void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000691 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000692 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000693 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000694 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000695}
696
John McCall23c29fe2011-06-24 21:55:10 +0000697llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
698 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
699}
700
Mike Stump11289f42009-09-09 15:08:12 +0000701void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000702 const NamedDecl *D) const {
Rafael Espindola123ce972018-01-24 18:58:32 +0000703 if (GV->hasDLLImportStorageClass())
704 return;
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000705 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000706 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000707 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000708 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000709 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000710
John McCallc273f242010-10-30 11:50:40 +0000711 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000712 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000713 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
Rafael Espindola4a5da442013-02-27 02:56:45 +0000714 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000715}
716
Rafael Espindola699f5d62018-02-07 22:15:33 +0000717static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
Rafael Espindola3dd49812018-02-23 00:22:15 +0000718 llvm::GlobalValue *GV) {
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000719 // DLLImport explicitly marks the GV as external.
720 if (GV->hasDLLImportStorageClass())
721 return false;
722
Rafael Espindola699f5d62018-02-07 22:15:33 +0000723 const llvm::Triple &TT = CGM.getTriple();
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000724 // Every other GV is local on COFF.
725 // Make an exception for windows OS in the triple: Some firmware builds use
726 // *-win32-macho triples. This (accidentally?) produced windows relocations
727 // without GOT tables in older clang versions; Keep this behaviour.
728 // FIXME: even thread local variables?
729 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
730 return true;
731
732 // Only handle COFF and ELF for now.
Rafael Espindola699f5d62018-02-07 22:15:33 +0000733 if (!TT.isOSBinFormatELF())
734 return false;
735
736 // If this is not an executable, don't assume anything is local.
737 const auto &CGOpts = CGM.getCodeGenOpts();
738 llvm::Reloc::Model RM = CGOpts.RelocationModel;
739 const auto &LOpts = CGM.getLangOpts();
740 if (RM != llvm::Reloc::Static && !LOpts.PIE)
741 return false;
742
743 // A definition cannot be preempted from an executable.
744 if (!GV->isDeclarationForLinker())
745 return true;
746
747 // Most PIC code sequences that assume that a symbol is local cannot produce a
748 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
749 // depended, it seems worth it to handle it here.
750 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
751 return false;
752
753 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
754 llvm::Triple::ArchType Arch = TT.getArch();
755 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
756 Arch == llvm::Triple::ppc64le)
757 return false;
758
759 // If we can use copy relocations we can assume it is local.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000760 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
761 if (!Var->isThreadLocal() &&
Rafael Espindola75e57362018-02-07 23:04:06 +0000762 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
763 return true;
Rafael Espindola699f5d62018-02-07 22:15:33 +0000764
765 // If we can use a plt entry as the symbol address we can assume it
766 // is local.
767 // FIXME: This should work for PIE, but the gold linker doesn't support it.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000768 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000769 return true;
770
771 // Otherwise don't assue it is local.
772 return false;
773}
774
Rafael Espindola3dd49812018-02-23 00:22:15 +0000775void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
776 if (shouldAssumeDSOLocal(*this, GV))
Rafael Espindola699f5d62018-02-07 22:15:33 +0000777 GV->setDSOLocal(true);
778}
779
Rafael Espindolab7350042018-03-01 00:35:47 +0000780void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
781 GlobalDecl GD) const {
782 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
783 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
784 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
785 // Don't dllexport/import destructor thunks.
786 GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
787 return;
788 }
789 }
790 setDLLImportDLLExport(GV, D);
791}
792
793void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
794 const NamedDecl *D) const {
795 if (D->isExternallyVisible()) {
796 if (D->hasAttr<DLLImportAttr>())
797 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
798 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
799 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
800 }
801}
802
803void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
804 GlobalDecl GD) const {
805 setDLLImportDLLExport(GV, GD);
806 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
807}
808
Rafael Espindola699f5d62018-02-07 22:15:33 +0000809void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
810 const NamedDecl *D) const {
Rafael Espindolab7350042018-03-01 00:35:47 +0000811 setDLLImportDLLExport(GV, D);
812 setGlobalVisibilityAndLocal(GV, D);
813}
814
815void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
816 const NamedDecl *D) const {
Rafael Espindola699f5d62018-02-07 22:15:33 +0000817 setGlobalVisibility(GV, D);
Rafael Espindola3dd49812018-02-23 00:22:15 +0000818 setDSOLocal(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000819}
820
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000821static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
822 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
823 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
824 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
825 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
826 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
827}
828
829static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
830 CodeGenOptions::TLSModel M) {
831 switch (M) {
832 case CodeGenOptions::GeneralDynamicTLSModel:
833 return llvm::GlobalVariable::GeneralDynamicTLSModel;
834 case CodeGenOptions::LocalDynamicTLSModel:
835 return llvm::GlobalVariable::LocalDynamicTLSModel;
836 case CodeGenOptions::InitialExecTLSModel:
837 return llvm::GlobalVariable::InitialExecTLSModel;
838 case CodeGenOptions::LocalExecTLSModel:
839 return llvm::GlobalVariable::LocalExecTLSModel;
840 }
841 llvm_unreachable("Invalid TLS model!");
842}
843
David Majnemerbb525f7c2014-10-15 22:38:23 +0000844void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000845 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000846
David Majnemerbb525f7c2014-10-15 22:38:23 +0000847 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000848 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000849
850 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000851 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000852 TLM = GetLLVMTLSModel(Attr->getModel());
853 }
854
855 GV->setThreadLocalMode(TLM);
856}
857
Erich Keane281d20b2018-01-08 21:34:17 +0000858static void AppendTargetMangling(const CodeGenModule &CGM,
859 const TargetAttr *Attr, raw_ostream &Out) {
860 if (Attr->isDefaultVersion())
861 return;
862
863 Out << '.';
864 const auto &Target = CGM.getTarget();
865 TargetAttr::ParsedTargetAttr Info =
866 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
George Burgess IV19131152018-01-17 04:46:04 +0000867 // Multiversioning doesn't allow "no-${feature}", so we can
868 // only have "+" prefixes here.
869 assert(LHS.startswith("+") && RHS.startswith("+") &&
870 "Features should always have a prefix.");
871 return Target.multiVersionSortPriority(LHS.substr(1)) >
872 Target.multiVersionSortPriority(RHS.substr(1));
Erich Keane281d20b2018-01-08 21:34:17 +0000873 });
874
875 bool IsFirst = true;
876
877 if (!Info.Architecture.empty()) {
878 IsFirst = false;
879 Out << "arch_" << Info.Architecture;
880 }
881
882 for (StringRef Feat : Info.Features) {
883 if (!IsFirst)
884 Out << '_';
885 IsFirst = false;
886 Out << Feat.substr(1);
887 }
888}
889
890static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
891 const NamedDecl *ND,
892 bool OmitTargetMangling = false) {
893 SmallString<256> Buffer;
894 llvm::raw_svector_ostream Out(Buffer);
895 MangleContext &MC = CGM.getCXXABI().getMangleContext();
896 if (MC.shouldMangleDeclName(ND)) {
897 llvm::raw_svector_ostream Out(Buffer);
898 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
899 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
900 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
901 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
902 else
903 MC.mangleName(ND, Out);
904 } else {
905 IdentifierInfo *II = ND->getIdentifier();
906 assert(II && "Attempt to mangle unnamed decl.");
907 const auto *FD = dyn_cast<FunctionDecl>(ND);
908
909 if (FD &&
910 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
911 llvm::raw_svector_ostream Out(Buffer);
912 Out << "__regcall3__" << II->getName();
913 } else {
914 Out << II->getName();
915 }
916 }
917
918 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
919 if (FD->isMultiVersion() && !OmitTargetMangling)
920 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
921 return Out.str();
922}
923
924void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
925 const FunctionDecl *FD) {
926 if (!FD->isMultiVersion())
927 return;
928
929 // Get the name of what this would be without the 'target' attribute. This
930 // allows us to lookup the version that was emitted when this wasn't a
931 // multiversion function.
932 std::string NonTargetName =
933 getMangledNameImpl(*this, GD, FD, /*OmitTargetMangling=*/true);
934 GlobalDecl OtherGD;
935 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
936 assert(OtherGD.getCanonicalDecl()
937 .getDecl()
938 ->getAsFunction()
939 ->isMultiVersion() &&
940 "Other GD should now be a multiversioned function");
941 // OtherFD is the version of this function that was mangled BEFORE
942 // becoming a MultiVersion function. It potentially needs to be updated.
943 const FunctionDecl *OtherFD =
944 OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
945 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
946 // This is so that if the initial version was already the 'default'
947 // version, we don't try to update it.
948 if (OtherName != NonTargetName) {
Erich Keanebc40c5c2018-01-09 01:09:12 +0000949 // Remove instead of erase, since others may have stored the StringRef
950 // to this.
951 const auto ExistingRecord = Manglings.find(NonTargetName);
952 if (ExistingRecord != std::end(Manglings))
953 Manglings.remove(&(*ExistingRecord));
Erich Keane281d20b2018-01-08 21:34:17 +0000954 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
955 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
956 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
957 Entry->setName(OtherName);
958 }
959 }
960}
961
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000962StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +0000963 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
964
965 // Some ABIs don't have constructor variants. Make sure that base and
966 // complete constructors get mangled the same.
967 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
968 if (!getTarget().getCXXABI().hasConstructorVariants()) {
969 CXXCtorType OrigCtorType = GD.getCtorType();
970 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
971 if (OrigCtorType == Ctor_Base)
972 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
973 }
974 }
975
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +0000976 auto FoundName = MangledDeclNames.find(CanonicalGD);
977 if (FoundName != MangledDeclNames.end())
978 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000979
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000980
Richard Smith6d0e97a2014-08-02 00:50:16 +0000981 // Keep the first result in the case of a mangling collision.
Erich Keane281d20b2018-01-08 21:34:17 +0000982 const auto *ND = cast<NamedDecl>(GD.getDecl());
983 auto Result =
984 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +0000985 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000986}
987
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000988StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
989 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000990 MangleContext &MangleCtx = getCXXABI().getMangleContext();
991 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000992
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000993 SmallString<256> Buffer;
994 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +0000995 if (!D)
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000996 MangleCtx.mangleGlobalBlock(BD,
Fariborz Jahanian63628032012-06-26 16:06:38 +0000997 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000998 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000999 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001000 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001001 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001002 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001003 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001004
Richard Smith6d0e97a2014-08-02 00:50:16 +00001005 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1006 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +00001007}
1008
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001009llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +00001010 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +00001011}
1012
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001013/// AddGlobalCtor - Add a function to the list that will be called before
1014/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001015void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1016 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001017 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001018 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001019}
1020
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001021/// AddGlobalDtor - Add a function to the list that will be called
1022/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001023void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001024 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +00001025 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001026}
1027
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001028void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001029 if (Fns.empty()) return;
1030
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001031 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +00001032 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001033 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001034
Reid Kleckner563f0e82014-05-23 21:13:45 +00001035 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1036 llvm::StructType *CtorStructTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00001037 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001038
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001039 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +00001040 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001041 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +00001042 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001043 auto ctor = ctors.beginStruct(CtorStructTy);
1044 ctor.addInt(Int32Ty, I.Priority);
1045 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1046 if (I.AssociatedData)
1047 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1048 else
1049 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +00001050 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001051 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001052
John McCall18081af2016-11-19 20:12:25 +00001053 auto list =
1054 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1055 /*constant*/ false,
1056 llvm::GlobalValue::AppendingLinkage);
1057
1058 // The LTO linker doesn't seem to like it when we set an alignment
1059 // on appending variables. Take it off as a workaround.
1060 list->setAlignment(0);
1061
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001062 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001063}
1064
John McCalld4324142010-02-19 01:32:20 +00001065llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001066CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001067 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +00001068
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001069 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +00001070
Hans Wennborg275efb92014-05-28 01:52:23 +00001071 if (isa<CXXDestructorDecl>(D) &&
Reid Klecknera283e482017-12-21 19:44:23 +00001072 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1073 GD.getDtorType())) {
1074 // Destructor variants in the Microsoft C++ ABI are always internal or
1075 // linkonce_odr thunks emitted on an as-needed basis.
1076 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
1077 : llvm::GlobalValue::LinkOnceODRLinkage;
Hans Wennborg275efb92014-05-28 01:52:23 +00001078 }
Reid Klecknera283e482017-12-21 19:44:23 +00001079
Richard Smith5179eb72016-06-28 19:03:57 +00001080 if (isa<CXXConstructorDecl>(D) &&
1081 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1082 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1083 // Our approach to inheriting constructors is fundamentally different from
1084 // that used by the MS ABI, so keep our inheriting constructor thunks
1085 // internal rather than trying to pick an unambiguous mangling for them.
1086 return llvm::GlobalValue::InternalLinkage;
1087 }
1088
Hans Wennborg275efb92014-05-28 01:52:23 +00001089 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +00001090}
Nuno Lopesb6f79532008-06-08 15:45:52 +00001091
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001092llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001093 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1094 if (!MDS) return nullptr;
1095
Benjamin Kramer630cf8c2016-11-23 11:20:27 +00001096 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001097}
1098
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001099void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +00001100 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001101 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001102 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00001103 llvm::AttributeList PAL;
1104 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1105 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001106 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +00001107}
1108
John McCall9b0a7ce2011-10-02 01:16:38 +00001109/// Determines whether the language options require us to model
1110/// unwind exceptions. We treat -fexceptions as mandating this
1111/// except under the fragile ObjC ABI with only ObjC exceptions
1112/// enabled. This means, for example, that C with -fexceptions
1113/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001114static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +00001115 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001116 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +00001117
1118 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001119 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +00001120
1121 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001122 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +00001123 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +00001124 }
1125
1126 return true;
1127}
1128
Daniel Dunbar38932572009-04-14 08:05:55 +00001129void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1130 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001131 llvm::AttrBuilder B;
1132
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001133 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001134 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001135
David Blaikiebbafb8a2012-03-11 07:00:24 +00001136 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001137 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +00001138
Akira Hatanaka200500d2015-10-08 19:30:57 +00001139 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1140 B.addAttribute(llvm::Attribute::StackProtect);
1141 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1142 B.addAttribute(llvm::Attribute::StackProtectStrong);
1143 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1144 B.addAttribute(llvm::Attribute::StackProtectReq);
1145
1146 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001147 // If we don't have a declaration to control inlining, the function isn't
1148 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1149 // disabled, mark the function as noinline.
1150 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1151 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1152 B.addAttribute(llvm::Attribute::NoInline);
1153
Reid Kleckneree4930b2017-05-02 22:07:37 +00001154 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +00001155 return;
1156 }
1157
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001158 // Track whether we need to add the optnone LLVM attribute,
1159 // starting with the default for this optimization level.
1160 bool ShouldAddOptNone =
1161 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1162 // We can't add optnone in the following cases, it won't pass the verifier.
1163 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1164 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1165 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1166
1167 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001168 B.addAttribute(llvm::Attribute::OptimizeNone);
1169
1170 // OptimizeNone implies noinline; we should not be inlining such functions.
1171 B.addAttribute(llvm::Attribute::NoInline);
1172 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1173 "OptimizeNone and AlwaysInline on same function!");
1174
1175 // We still need to handle naked functions even though optnone subsumes
1176 // much of their semantics.
1177 if (D->hasAttr<NakedAttr>())
1178 B.addAttribute(llvm::Attribute::Naked);
1179
1180 // OptimizeNone wins over OptimizeForSize and MinSize.
1181 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1182 F->removeFnAttr(llvm::Attribute::MinSize);
1183 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +00001184 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001185 B.addAttribute(llvm::Attribute::Naked);
1186 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001187 } else if (D->hasAttr<NoDuplicateAttr>()) {
1188 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001189 } else if (D->hasAttr<NoInlineAttr>()) {
1190 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +00001191 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +00001192 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001193 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001194 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001195 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1196 // If we're not inlining, then force everything that isn't always_inline to
1197 // carry an explicit noinline attribute.
1198 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1199 B.addAttribute(llvm::Attribute::NoInline);
1200 } else {
1201 // Otherwise, propagate the inline hint attribute and potentially use its
1202 // absence to mark things as noinline.
1203 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1204 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
1205 return Redecl->isInlineSpecified();
1206 })) {
1207 B.addAttribute(llvm::Attribute::InlineHint);
1208 } else if (CodeGenOpts.getInlining() ==
1209 CodeGenOptions::OnlyHintInlining &&
1210 !FD->isInlined() &&
1211 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1212 B.addAttribute(llvm::Attribute::NoInline);
1213 }
1214 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001215 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001216
Chandler Carruthfcd33142016-12-23 01:24:49 +00001217 // Add other optimization related attributes if we are optimizing this
1218 // function.
1219 if (!D->hasAttr<OptimizeNoneAttr>()) {
1220 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001221 if (!ShouldAddOptNone)
1222 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001223 B.addAttribute(llvm::Attribute::Cold);
1224 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001225
Chandler Carruthfcd33142016-12-23 01:24:49 +00001226 if (D->hasAttr<MinSizeAttr>())
1227 B.addAttribute(llvm::Attribute::MinSize);
1228 }
Richard Smithb555a762012-09-28 22:46:07 +00001229
Reid Kleckneree4930b2017-05-02 22:07:37 +00001230 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001231
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001232 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1233 if (alignment)
1234 F->setAlignment(alignment);
1235
Dan Gohmanc2853072015-09-03 22:51:53 +00001236 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1237 // reserve a bit for differentiating between virtual and non-virtual member
1238 // functions. If the current target's C++ ABI requires this and this is a
1239 // member function, set its alignment accordingly.
1240 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1241 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1242 F->setAlignment(2);
1243 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001244
1245 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1246 if (CodeGenOpts.SanitizeCfiCrossDso)
1247 if (auto *FD = dyn_cast<FunctionDecl>(D))
1248 CreateFunctionTypeMetadata(FD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001249}
1250
Rafael Espindola75c649c2018-03-01 00:06:55 +00001251void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1252 const Decl *D = GD.getDecl();
Rafael Espindolab7350042018-03-01 00:35:47 +00001253 if (dyn_cast_or_null<NamedDecl>(D))
1254 setGVProperties(GV, GD);
John McCall457a04e2010-10-22 21:05:15 +00001255 else
1256 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001257
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001258 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001259 addUsedGlobal(GV);
Rafael Espindola502f65a2014-05-05 20:21:03 +00001260}
1261
Erich Keane93e58662018-02-12 17:01:41 +00001262bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1263 llvm::AttrBuilder &Attrs) {
1264 // Add target-cpu and target-features attributes to functions. If
1265 // we have a decl for the function and it has a target attribute then
1266 // parse that and add it to the feature set.
1267 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1268 std::vector<std::string> Features;
1269 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1270 FD = FD ? FD->getMostRecentDecl() : FD;
1271 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1272 bool AddedAttr = false;
1273 if (TD) {
1274 llvm::StringMap<bool> FeatureMap;
1275 getFunctionFeatureMap(FeatureMap, FD);
1276
1277 // Produce the canonical string for this set of features.
1278 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1279 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1280
1281 // Now add the target-cpu and target-features to the function.
1282 // While we populated the feature map above, we still need to
1283 // get and parse the target attribute so we can get the cpu for
1284 // the function.
1285 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1286 if (ParsedAttr.Architecture != "" &&
1287 getTarget().isValidCPUName(ParsedAttr.Architecture))
1288 TargetCPU = ParsedAttr.Architecture;
1289 } else {
1290 // Otherwise just add the existing target cpu and target features to the
1291 // function.
1292 Features = getTarget().getTargetOpts().Features;
1293 }
1294
1295 if (TargetCPU != "") {
1296 Attrs.addAttribute("target-cpu", TargetCPU);
1297 AddedAttr = true;
1298 }
1299 if (!Features.empty()) {
1300 std::sort(Features.begin(), Features.end());
1301 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1302 AddedAttr = true;
1303 }
1304
1305 return AddedAttr;
1306}
1307
Rafael Espindola285271c2018-02-28 23:54:23 +00001308void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001309 llvm::GlobalObject *GO) {
Rafael Espindola285271c2018-02-28 23:54:23 +00001310 const Decl *D = GD.getDecl();
Rafael Espindola75c649c2018-03-01 00:06:55 +00001311 SetCommonAttributes(GD, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001312
Javed Absar2a67c9e2017-06-05 10:11:57 +00001313 if (D) {
1314 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1315 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1316 GV->addAttribute("bss-section", SA->getName());
1317 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1318 GV->addAttribute("data-section", SA->getName());
1319 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1320 GV->addAttribute("rodata-section", SA->getName());
1321 }
1322
1323 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1324 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
Erich Keane30994d22018-02-08 20:04:22 +00001325 if (!D->getAttr<SectionAttr>())
1326 F->addFnAttr("implicit-section-name", SA->getName());
Erich Keane93e58662018-02-12 17:01:41 +00001327
1328 llvm::AttrBuilder Attrs;
1329 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1330 // We know that GetCPUAndFeaturesAttributes will always have the
1331 // newest set, since it has the newest possible FunctionDecl, so the
1332 // new ones should replace the old.
1333 F->removeFnAttr("target-cpu");
1334 F->removeFnAttr("target-features");
1335 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1336 }
Javed Absar2a67c9e2017-06-05 10:11:57 +00001337 }
1338
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001339 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1340 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001341 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001342
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001343 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001344}
1345
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001346void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001347 llvm::Function *F,
1348 const CGFunctionInfo &FI) {
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001349 const Decl *D = GD.getDecl();
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001350 SetLLVMFunctionAttributes(D, FI, F);
1351 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001352
1353 F->setLinkage(llvm::Function::InternalLinkage);
1354
Rafael Espindola285271c2018-02-28 23:54:23 +00001355 setNonAliasAttributes(GD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001356}
1357
Rafael Espindolab7350042018-03-01 00:35:47 +00001358static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
David Majnemerf6acb762014-04-25 17:07:16 +00001359 // Set linkage and visibility in case we never see a definition.
1360 LinkageInfo LV = ND->getLinkageAndVisibility();
Rafael Espindolab7350042018-03-01 00:35:47 +00001361 // Don't set internal linkage on declarations.
1362 // "extern_weak" is overloaded in LLVM; we probably should have
1363 // separate linkage types for this.
1364 if (isExternallyVisible(LV.getLinkage()) &&
1365 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1366 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001367}
1368
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001369void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1370 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001371 // Only if we are checking indirect calls.
1372 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1373 return;
1374
1375 // Non-static class methods are handled via vtable pointer checks elsewhere.
1376 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1377 return;
1378
1379 // Additionally, if building with cross-DSO support...
1380 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001381 // Skip available_externally functions. They won't be codegen'ed in the
1382 // current module anyway.
1383 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1384 return;
1385 }
1386
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001387 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001388 F->addTypeMetadata(0, MD);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001389 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001390
1391 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001392 if (CodeGenOpts.SanitizeCfiCrossDso)
1393 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1394 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001395}
1396
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001397void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1398 bool IsIncompleteFunction,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001399 bool IsThunk) {
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001400
Pete Cooper2f1637a2015-05-20 17:17:45 +00001401 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001402 // If this is an intrinsic function, set the function's attributes
1403 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001404 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001405 return;
1406 }
1407
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001408 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001409
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001410 if (!IsIncompleteFunction) {
John McCalla729c622012-02-17 03:33:10 +00001411 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001412 // Setup target-specific attributes.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001413 if (F->isDeclaration())
1414 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001415 }
Mike Stump11289f42009-09-09 15:08:12 +00001416
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001417 // Add the Returned attribute for "this", except for iOS 5 and earlier
1418 // where substantial code, including the libstdc++ dylib, was compiled with
1419 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001420 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001421 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001422 assert(!F->arg_empty() &&
1423 F->arg_begin()->getType()
1424 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1425 "unexpected this return");
1426 F->addAttribute(1, llvm::Attribute::Returned);
1427 }
1428
Daniel Dunbar38932572009-04-14 08:05:55 +00001429 // Only a few attributes are set on declarations; these may later be
1430 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001431
Jake Ehrlichba874ad2017-11-29 00:54:20 +00001432 setLinkageForGV(F, FD);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001433 setGVProperties(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001434
Javed Absar2a67c9e2017-06-05 10:11:57 +00001435 if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1436 F->addFnAttr("implicit-section-name");
1437 }
1438
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001439 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +00001440 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001441
Richard Smith351241c2016-04-07 21:46:12 +00001442 if (FD->isReplaceableGlobalAllocationFunction()) {
1443 // A replaceable global allocation function does not act like a builtin by
1444 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001445 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001446 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001447
Richard Smith351241c2016-04-07 21:46:12 +00001448 // A sane operator new returns a non-aliasing pointer.
1449 // FIXME: Also add NonNull attribute to the return value
1450 // for the non-nothrow forms?
1451 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1452 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1453 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001454 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001455 llvm::Attribute::NoAlias);
1456 }
1457
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001458 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001459 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001460 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1461 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001462 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001463
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001464 // Don't emit entries for function declarations in the cross-DSO mode. This
1465 // is handled with better precision by the receiving DSO.
1466 if (!CodeGenOpts.SanitizeCfiCrossDso)
1467 CreateFunctionTypeMetadata(FD, F);
Alexey Bataevb952e632017-12-15 16:28:31 +00001468
1469 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1470 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001471}
1472
Rafael Espindola060062a2014-03-06 22:15:10 +00001473void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001474 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001475 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001476 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001477}
1478
Rafael Espindola060062a2014-03-06 22:15:10 +00001479void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1480 assert(!GV->isDeclaration() &&
1481 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001482 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001483}
1484
1485static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001486 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001487 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001488 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001489 return;
1490
Rafael Espindola060062a2014-03-06 22:15:10 +00001491 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001492 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001493 UsedArray.resize(List.size());
1494 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001495 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001496 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1497 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001498 }
Mike Stump11289f42009-09-09 15:08:12 +00001499
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001500 if (UsedArray.empty())
1501 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001502 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001503
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001504 auto *GV = new llvm::GlobalVariable(
1505 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1506 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001507
1508 GV->setSection("llvm.metadata");
1509}
1510
Rafael Espindola060062a2014-03-06 22:15:10 +00001511void CodeGenModule::emitLLVMUsed() {
1512 emitUsed(*this, "llvm.used", LLVMUsed);
1513 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1514}
1515
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001516void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001517 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001518 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1519}
1520
Aaron Ballman5d041be2013-06-04 02:07:14 +00001521void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1522 llvm::SmallString<32> Opt;
1523 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001524 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001525 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1526}
1527
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00001528void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1529 auto &C = getLLVMContext();
1530 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1531 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1532}
1533
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001534void CodeGenModule::AddDependentLib(StringRef Lib) {
1535 llvm::SmallString<24> Opt;
1536 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001537 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001538 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1539}
1540
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001541/// \brief Add link options implied by the given module, including modules
1542/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001543static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001544 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001545 llvm::SmallPtrSet<Module *, 16> &Visited) {
1546 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001547 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001548 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001549 }
1550
1551 // Import this module's dependencies.
1552 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001553 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001554 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001555 }
1556
1557 // Add linker options to link against the libraries/frameworks
1558 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001559 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001560 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001561 // Link against a framework. Frameworks are currently Darwin only, so we
1562 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001563 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001564 llvm::Metadata *Args[2] = {
1565 llvm::MDString::get(Context, "-framework"),
1566 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001567
1568 Metadata.push_back(llvm::MDNode::get(Context, Args));
1569 continue;
1570 }
1571
1572 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001573 llvm::SmallString<24> Opt;
1574 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1575 Mod->LinkLibraries[I-1].Library, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001576 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001577 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1578 }
1579}
1580
1581void CodeGenModule::EmitModuleLinkOptions() {
1582 // Collect the set of all of the modules we want to visit to emit link
1583 // options, which is essentially the imported modules and all of their
1584 // non-explicit child modules.
1585 llvm::SetVector<clang::Module *> LinkModules;
1586 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1587 SmallVector<clang::Module *, 16> Stack;
1588
1589 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001590 for (Module *M : ImportedModules) {
1591 // Do not add any link flags when an implementation TU of a module imports
1592 // a header of that same module.
1593 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1594 !getLangOpts().isCompilingModule())
1595 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001596 if (Visited.insert(M).second)
1597 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001598 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001599
1600 // Find all of the modules to import, making a little effort to prune
1601 // non-leaf modules.
1602 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001603 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001604
1605 bool AnyChildren = false;
1606
1607 // Visit the submodules of this module.
1608 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1609 SubEnd = Mod->submodule_end();
1610 Sub != SubEnd; ++Sub) {
1611 // Skip explicit children; they need to be explicitly imported to be
1612 // linked against.
1613 if ((*Sub)->IsExplicit)
1614 continue;
1615
David Blaikie82e95a32014-11-19 07:49:47 +00001616 if (Visited.insert(*Sub).second) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001617 Stack.push_back(*Sub);
1618 AnyChildren = true;
1619 }
1620 }
1621
1622 // We didn't find any children, so add this module to the list of
1623 // modules to link against.
1624 if (!AnyChildren) {
1625 LinkModules.insert(Mod);
1626 }
1627 }
1628
1629 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001630 // order. We don't do anything to try to order import link flags with respect
1631 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00001632 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001633 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001634 for (Module *M : LinkModules)
1635 if (Visited.insert(M).second)
1636 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001637 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001638 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001639
Daniel Dunbar69e47462013-01-17 01:35:06 +00001640 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00001641 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1642 for (auto *MD : LinkerOptionsMetadata)
1643 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001644}
1645
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001646void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +00001647 // Emit code for any potentially referenced deferred decls. Since a
1648 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001649 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001650
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001651 if (!DeferredVTables.empty()) {
1652 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001653
Eric Christopherd160c502016-01-29 01:35:53 +00001654 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001655 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001656 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001657 assert(DeferredVTables.empty());
1658 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001659
Eric Christopherd160c502016-01-29 01:35:53 +00001660 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001661 if (DeferredDeclsToEmit.empty())
1662 return;
John McCall6bd2a892013-01-25 22:31:03 +00001663
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001664 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1665 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001666 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001667 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1668
Sanjoy Das70a60512017-05-01 06:12:13 +00001669 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001670 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1671 // to get GlobalValue with exactly the type we need, not something that
1672 // might had been created for another decl with the same mangled name but
1673 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001674 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001675 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001676
1677 // In case of different address spaces, we may still get a cast, even with
1678 // IsForDefinition equal to true. Query mangled names table to get
1679 // GlobalValue.
1680 if (!GV)
1681 GV = GetGlobalValue(getMangledName(D));
1682
1683 // Make sure GetGlobalValue returned non-null.
1684 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001685
John McCallc2af9392010-05-27 01:45:30 +00001686 // Check to see if we've already emitted this. This is necessary
1687 // for a couple of reasons: first, decls can end up in the
1688 // deferred-decls queue multiple times, and second, decls can end
1689 // up with definitions in unusual ways (e.g. by an extern inline
1690 // function acquiring a strong function redefinition). Just
1691 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001692 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001693 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001694
Chris Lattner45470942009-03-21 09:44:56 +00001695 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001696 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001697
1698 // If we found out that we need to emit more decls, do that recursively.
1699 // This has the advantage that the decls are emitted in a DFS and related
1700 // ones are close together, which is convenient for testing.
1701 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1702 EmitDeferred();
1703 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1704 }
Chris Lattner45470942009-03-21 09:44:56 +00001705 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001706}
Chris Lattner09153c02007-06-22 18:48:09 +00001707
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001708void CodeGenModule::EmitVTablesOpportunistically() {
1709 // Try to emit external vtables as available_externally if they have emitted
1710 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1711 // is not allowed to create new references to things that need to be emitted
1712 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1713
Piotr Padlewski05547742017-06-01 09:24:36 +00001714 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1715 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001716
1717 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1718 assert(getVTables().isVTableExternal(RD) &&
1719 "This queue should only contain external vtables");
1720 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1721 VTables.GenerateClassData(RD);
1722 }
1723 OpportunisticVTables.clear();
1724}
1725
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001726void CodeGenModule::EmitGlobalAnnotations() {
1727 if (Annotations.empty())
1728 return;
1729
1730 // Create a new global variable for the ConstantStruct in the Module.
1731 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1732 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001733 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1734 llvm::GlobalValue::AppendingLinkage,
1735 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001736 gv->setSection(AnnotationSection);
1737}
1738
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001739llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001740 llvm::Constant *&AStr = AnnotationStrings[Str];
1741 if (AStr)
1742 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001743
1744 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001745 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001746 auto *gv =
1747 new llvm::GlobalVariable(getModule(), s->getType(), true,
1748 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001749 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001750 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001751 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001752 return gv;
1753}
1754
1755llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1756 SourceManager &SM = getContext().getSourceManager();
1757 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1758 if (PLoc.isValid())
1759 return EmitAnnotationString(PLoc.getFilename());
1760 return EmitAnnotationString(SM.getBufferName(Loc));
1761}
1762
1763llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1764 SourceManager &SM = getContext().getSourceManager();
1765 PresumedLoc PLoc = SM.getPresumedLoc(L);
1766 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1767 SM.getExpansionLineNumber(L);
1768 return llvm::ConstantInt::get(Int32Ty, LineNo);
1769}
1770
Mike Stump11289f42009-09-09 15:08:12 +00001771llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001772 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001773 SourceLocation L) {
1774 // Get the globals for file name, annotation, and the line number.
1775 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1776 *UnitGV = EmitAnnotationUnit(L),
1777 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001778
Daniel Dunbar346892a2009-04-14 22:41:13 +00001779 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001780 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001781 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1782 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1783 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1784 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001785 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001786 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001787}
1788
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001789void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1790 llvm::GlobalValue *GV) {
1791 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1792 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001793 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1794 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001795}
1796
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001797bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1798 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001799 SourceLocation Loc) const {
1800 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1801 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001802 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001803 return true;
1804 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001805 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001806 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001807 // If location is unknown, this may be a compiler-generated function. Assume
1808 // it's located in the main file.
1809 auto &SM = Context.getSourceManager();
1810 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001811 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001812 }
1813 return false;
1814}
1815
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001816bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1817 SourceLocation Loc, QualType Ty,
1818 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001819 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001820 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
Evgeniy Stepanov12817e52017-12-09 01:32:07 +00001821 (SanitizerKind::Address | SanitizerKind::KernelAddress | SanitizerKind::HWAddress);
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001822 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001823 return false;
1824 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001825 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001826 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001827 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001828 return true;
1829 // Check global type.
1830 if (!Ty.isNull()) {
1831 // Drill down the array types: if global variable of a fixed type is
1832 // blacklisted, we also don't instrument arrays of them.
1833 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1834 Ty = AT->getElementType();
1835 Ty = Ty.getCanonicalType().getUnqualifiedType();
1836 // We allow to blacklist only record types (classes, structs etc.)
1837 if (Ty->isRecordType()) {
1838 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001839 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001840 return true;
1841 }
1842 }
1843 return false;
1844}
1845
Dean Michael Berris835832d2017-03-30 00:29:36 +00001846bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1847 StringRef Category) const {
1848 if (!LangOpts.XRayInstrument)
1849 return false;
1850 const auto &XRayFilter = getContext().getXRayFilter();
1851 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1852 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1853 if (Loc.isValid())
1854 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1855 if (Attr == ImbueAttr::NONE)
1856 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1857 switch (Attr) {
1858 case ImbueAttr::NONE:
1859 return false;
1860 case ImbueAttr::ALWAYS:
1861 Fn->addFnAttr("function-instrument", "xray-always");
1862 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00001863 case ImbueAttr::ALWAYS_ARG1:
1864 Fn->addFnAttr("function-instrument", "xray-always");
1865 Fn->addFnAttr("xray-log-args", "1");
1866 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001867 case ImbueAttr::NEVER:
1868 Fn->addFnAttr("function-instrument", "xray-never");
1869 break;
1870 }
1871 return true;
1872}
1873
Hans Wennborg43a0f992015-01-10 01:19:48 +00001874bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001875 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001876 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00001877 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001878
Hans Wennborg43a0f992015-01-10 01:19:48 +00001879 return getContext().DeclMustBeEmitted(Global);
1880}
1881
1882bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1883 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1884 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1885 // Implicit template instantiations may change linkage if they are later
1886 // explicitly instantiated, so they should not be emitted eagerly.
1887 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00001888 if (const auto *VD = dyn_cast<VarDecl>(Global))
1889 if (Context.getInlineVariableDefinitionKind(VD) ==
1890 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1891 // A definition of an inline constexpr static data member may change
1892 // linkage later if it's redeclared outside the class.
1893 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00001894 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1895 // codegen for global variables, because they may be marked as threadprivate.
1896 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1897 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1898 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00001899
1900 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001901}
1902
John McCall7f416cc2015-09-08 08:05:57 +00001903ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00001904 const CXXUuidofExpr* E) {
1905 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1906 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00001907 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00001908 std::string Name = "_GUID_" + Uuid.lower();
1909 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001910
David Majnemer65687602016-03-27 04:46:14 +00001911 // The UUID descriptor should be pointer aligned.
1912 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00001913
Nico Webercf4ff5862012-10-11 10:13:44 +00001914 // Look for an existing global.
1915 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00001916 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001917
Nico Weber17d3a2c2014-09-08 16:26:36 +00001918 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00001919 assert(Init && "failed to initialize as constant");
1920
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001921 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00001922 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001923 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001924 if (supportsCOMDAT())
1925 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
John McCall7f416cc2015-09-08 08:05:57 +00001926 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001927}
1928
John McCall7f416cc2015-09-08 08:05:57 +00001929ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001930 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1931 assert(AA && "No alias?");
1932
John McCall7f416cc2015-09-08 08:05:57 +00001933 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00001934 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001935
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001936 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001937 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001938 if (Entry) {
1939 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001940 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1941 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001942 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001943
1944 llvm::Constant *Aliasee;
1945 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001946 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1947 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001948 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001949 else
John McCall7ec50432010-03-19 23:29:14 +00001950 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00001951 llvm::PointerType::getUnqual(DeclTy),
1952 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001953
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001954 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001955 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1956 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001957
John McCall7f416cc2015-09-08 08:05:57 +00001958 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001959}
1960
Chris Lattnere0be0df2009-05-12 21:21:08 +00001961void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001962 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001963
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001964 // Weak references don't produce any output by themselves.
1965 if (Global->hasAttr<WeakRefAttr>())
1966 return;
1967
Chris Lattner54041692009-03-22 21:47:11 +00001968 // If this is an alias definition (which otherwise looks like a declaration)
1969 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001970 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001971 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001972
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001973 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1974 if (Global->hasAttr<IFuncAttr>())
1975 return emitIFuncDefinition(GD);
1976
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001977 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001978 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00001979 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001980 if (!Global->hasAttr<CUDADeviceAttr>() &&
1981 !Global->hasAttr<CUDAGlobalAttr>() &&
1982 !Global->hasAttr<CUDAConstantAttr>() &&
1983 !Global->hasAttr<CUDASharedAttr>())
1984 return;
1985 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00001986 // We need to emit host-side 'shadows' for all global
1987 // device-side variables because the CUDA runtime needs their
1988 // size and host-side address in order to provide access to
1989 // their device-side incarnations.
1990
1991 // So device-only functions are the only things we skip.
1992 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1993 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001994 return;
Artem Belevich42e19492016-03-02 18:28:50 +00001995
1996 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1997 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001998 }
1999 }
2000
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002001 if (LangOpts.OpenMP) {
2002 // If this is OpenMP device, check if it is legal to emit this global
2003 // normally.
2004 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2005 return;
2006 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2007 if (MustBeEmitted(Global))
2008 EmitOMPDeclareReduction(DRD);
2009 return;
2010 }
2011 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002012
Chris Lattner45470942009-03-21 09:44:56 +00002013 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002014 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002015 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002016 if (!FD->doesThisDeclarationHaveABody()) {
2017 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2018 return;
2019
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002020 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00002021
2022 // Compute the function info and LLVM type.
2023 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2024 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2025
2026 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2027 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002028 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002029 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002030 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002031 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002032 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich42e19492016-03-02 18:28:50 +00002033 // We need to emit device-side global CUDA variables even if a
2034 // variable does not have a definition -- we still need to define
2035 // host-side shadow for it.
2036 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2037 !VD->hasDefinition() &&
2038 (VD->hasAttr<CUDAConstantAttr>() ||
2039 VD->hasAttr<CUDADeviceAttr>());
2040 if (!MustEmitForCuda &&
2041 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00002042 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2043 // If this declaration may have caused an inline variable definition to
2044 // change linkage, make sure that it's emitted.
2045 if (Context.getInlineVariableDefinitionKind(VD) ==
2046 ASTContext::InlineVariableDefinitionKind::Strong)
2047 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00002048 return;
Richard Smithd9b90092016-07-02 01:32:16 +00002049 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002050 }
2051
Hans Wennborg43a0f992015-01-10 01:19:48 +00002052 // Defer code generation to first use when possible, e.g. if this is an inline
2053 // function. If the global must always be emitted, do it eagerly if possible
2054 // to benefit from cache locality.
2055 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002056 // Emit the definition if it can't be deferred.
2057 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002058 return;
2059 }
John McCall70013b62010-07-15 23:40:35 +00002060
2061 // If we're deferring emission of a C++ variable with an
2062 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002063 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00002064 cast<VarDecl>(Global)->hasInit()) {
2065 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00002066 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00002067 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00002068
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002069 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00002070 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00002071 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00002072 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002073 } else if (MustBeEmitted(Global)) {
2074 // The value must be emitted, but cannot be emitted eagerly.
2075 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00002076 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002077 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002078 // Otherwise, remember that we saw a deferred decl with this name. The
2079 // first use of the mangled name will cause it to move into
2080 // DeferredDeclsToEmit.
2081 DeferredDecls[MangledName] = GD;
2082 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002083}
2084
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002085// Check if T is a class type with a destructor that's not dllimport.
2086static bool HasNonDllImportDtor(QualType T) {
2087 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2088 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2089 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2090 return true;
2091
2092 return false;
2093}
2094
Rafael Espindolac5941352011-10-26 20:41:06 +00002095namespace {
2096 struct FunctionIsDirectlyRecursive :
2097 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2098 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002099 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00002100 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002101 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2102 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002103 }
2104 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2105
2106 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002107 const FunctionDecl *FD = E->getDirectCallee();
2108 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00002109 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002110 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2111 if (Attr && Name == Attr->getLabel()) {
2112 Result = true;
2113 return false;
2114 }
2115 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00002116 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolac5941352011-10-26 20:41:06 +00002117 return true;
Eric Christopher02d5d862015-08-06 01:01:12 +00002118 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00002119 if (BuiltinName.startswith("__builtin_") &&
2120 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002121 Result = true;
2122 return false;
2123 }
2124 return true;
2125 }
2126 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002127
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002128 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002129 struct DLLImportFunctionVisitor
2130 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2131 bool SafeToInline = true;
2132
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002133 bool shouldVisitImplicitCode() const { return true; }
2134
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002135 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002136 if (VD->getTLSKind()) {
2137 // A thread-local variable cannot be imported.
2138 SafeToInline = false;
2139 return SafeToInline;
2140 }
2141
2142 // A variable definition might imply a destructor call.
2143 if (VD->isThisDeclarationADefinition())
2144 SafeToInline = !HasNonDllImportDtor(VD->getType());
2145
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002146 return SafeToInline;
2147 }
2148
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002149 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2150 if (const auto *D = E->getTemporary()->getDestructor())
2151 SafeToInline = D->hasAttr<DLLImportAttr>();
2152 return SafeToInline;
2153 }
2154
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002155 bool VisitDeclRefExpr(DeclRefExpr *E) {
2156 ValueDecl *VD = E->getDecl();
2157 if (isa<FunctionDecl>(VD))
2158 SafeToInline = VD->hasAttr<DLLImportAttr>();
2159 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2160 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2161 return SafeToInline;
2162 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002163
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002164 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2165 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2166 return SafeToInline;
2167 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002168
Hans Wennborg251c2042017-01-23 23:57:50 +00002169 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2170 CXXMethodDecl *M = E->getMethodDecl();
2171 if (!M) {
2172 // Call through a pointer to member function. This is safe to inline.
2173 SafeToInline = true;
2174 } else {
2175 SafeToInline = M->hasAttr<DLLImportAttr>();
2176 }
2177 return SafeToInline;
2178 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002179
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002180 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2181 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2182 return SafeToInline;
2183 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002184
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002185 bool VisitCXXNewExpr(CXXNewExpr *E) {
2186 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2187 return SafeToInline;
2188 }
2189 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002190}
Rafael Espindolac5941352011-10-26 20:41:06 +00002191
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002192// isTriviallyRecursive - Check if this function calls another
2193// decl that, because of the asm attribute or the other decl being a builtin,
2194// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00002195bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002196CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2197 StringRef Name;
2198 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00002199 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002200 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2201 if (!Attr)
2202 return false;
2203 Name = Attr->getLabel();
2204 } else {
2205 Name = FD->getName();
2206 }
Rafael Espindolac5941352011-10-26 20:41:06 +00002207
David Majnemer64b0bdf2015-06-30 04:41:18 +00002208 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002209 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00002210 return Walker.Result;
2211}
2212
Hans Wennborg93f75472016-09-13 21:08:20 +00002213bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002214 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00002215 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002216 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00002217 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00002218 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002219
2220 if (F->hasAttr<DLLImportAttr>()) {
2221 // Check whether it would be safe to inline this dllimport function.
2222 DLLImportFunctionVisitor Visitor;
2223 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2224 if (!Visitor.SafeToInline)
2225 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00002226
2227 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2228 // Implicit destructor invocations aren't captured in the AST, so the
2229 // check above can't see them. Check for them manually here.
2230 for (const Decl *Member : Dtor->getParent()->decls())
2231 if (isa<FieldDecl>(Member))
2232 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2233 return false;
2234 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2235 if (HasNonDllImportDtor(B.getType()))
2236 return false;
2237 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002238 }
2239
Rafael Espindolac5941352011-10-26 20:41:06 +00002240 // PR9614. Avoid cases where the source code is lying to us. An available
2241 // externally function should have an equivalent function somewhere else,
2242 // but a function that calls itself is clearly not equivalent to the real
2243 // implementation.
2244 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002245 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00002246}
2247
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002248bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2249 return CodeGenOpts.OptimizationLevel > 0;
2250}
2251
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002252void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002253 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002254
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002255 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00002256 Context.getSourceManager(),
2257 "Generating code for declaration");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002258
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002259 if (isa<FunctionDecl>(D)) {
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002260 // At -O0, don't generate IR for functions with available_externally
Douglas Gregora700f682010-07-13 06:02:28 +00002261 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002262 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002263 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002264
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002265 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002266 // Make sure to emit the definition(s) before we emit the thunks.
2267 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002268 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002269 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002270 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002271 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman49a94b12011-05-06 17:27:27 +00002272 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002273 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002274
Douglas Gregora700f682010-07-13 06:02:28 +00002275 if (Method->isVirtual())
2276 getVTables().EmitThunks(GD);
2277
Eli Friedman49a94b12011-05-06 17:27:27 +00002278 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002279 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002280
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002281 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002282 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002283
2284 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002285 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002286
David Blaikie83d382b2011-09-23 05:06:16 +00002287 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002288}
2289
Andrey Bokhankocab58582015-08-31 13:20:44 +00002290static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2291 llvm::Function *NewFn);
2292
Erich Keane281d20b2018-01-08 21:34:17 +00002293void CodeGenModule::emitMultiVersionFunctions() {
2294 for (GlobalDecl GD : MultiVersionFuncs) {
2295 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2296 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2297 getContext().forEachMultiversionedFunctionVersion(
2298 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2299 GlobalDecl CurGD{
2300 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2301 StringRef MangledName = getMangledName(CurGD);
2302 llvm::Constant *Func = GetGlobalValue(MangledName);
2303 if (!Func) {
2304 if (CurFD->isDefined()) {
2305 EmitGlobalFunctionDefinition(CurGD, nullptr);
2306 Func = GetGlobalValue(MangledName);
2307 } else {
2308 const CGFunctionInfo &FI =
2309 getTypes().arrangeGlobalDeclaration(GD);
2310 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2311 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2312 /*DontDefer=*/false, ForDefinition);
2313 }
2314 assert(Func && "This should have just been created");
2315 }
2316 Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
2317 CurFD->getAttr<TargetAttr>()->parse());
2318 });
2319
2320 llvm::Function *ResolverFunc = cast<llvm::Function>(
2321 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
Erich Keane0a6fde42018-01-16 19:49:52 +00002322 if (supportsCOMDAT())
2323 ResolverFunc->setComdat(
2324 getModule().getOrInsertComdat(ResolverFunc->getName()));
Erich Keane281d20b2018-01-08 21:34:17 +00002325 std::stable_sort(
2326 Options.begin(), Options.end(),
2327 std::greater<CodeGenFunction::MultiVersionResolverOption>());
2328 CodeGenFunction CGF(*this);
2329 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2330 }
2331}
2332
2333/// If an ifunc for the specified mangled name is not in the module, create and
2334/// return an llvm IFunc Function with the specified type.
2335llvm::Constant *
2336CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
2337 StringRef MangledName,
2338 const FunctionDecl *FD) {
2339 std::string IFuncName = (MangledName + ".ifunc").str();
2340 if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2341 return IFuncGV;
2342
2343 // Since this is the first time we've created this IFunc, make sure
2344 // that we put this multiversioned function into the list to be
2345 // replaced later.
2346 MultiVersionFuncs.push_back(GD);
2347
2348 std::string ResolverName = (MangledName + ".resolver").str();
2349 llvm::Type *ResolverType = llvm::FunctionType::get(
2350 llvm::PointerType::get(DeclTy,
2351 Context.getTargetAddressSpace(FD->getType())),
2352 false);
2353 llvm::Constant *Resolver =
2354 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2355 /*ForVTable=*/false);
2356 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2357 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2358 GIF->setName(IFuncName);
2359 SetCommonAttributes(FD, GIF);
2360
2361 return GIF;
2362}
2363
Chris Lattnerd4808922009-03-22 21:03:39 +00002364/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2365/// module, create and return an llvm Function with the specified type. If there
2366/// is something in the module with the specified name, return it potentially
2367/// bitcasted to the right type.
2368///
2369/// If D is non-null, it specifies a decl that correspond to this. This is used
2370/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002371llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2372 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2373 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2374 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002375 const Decl *D = GD.getDecl();
2376
Erich Keane281d20b2018-01-08 21:34:17 +00002377 // Any attempts to use a MultiVersion function should result in retrieving
2378 // the iFunc instead. Name Mangling will handle the rest of the changes.
2379 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2380 if (FD->isMultiVersion() && FD->getAttr<TargetAttr>()->isDefaultVersion()) {
2381 UpdateMultiVersionNames(GD, FD);
2382 if (!IsForDefinition)
2383 return GetOrCreateMultiVersionIFunc(GD, Ty, MangledName, FD);
2384 }
2385 }
2386
Chris Lattnera85d68e2009-03-21 09:25:43 +00002387 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002388 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002389 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002390 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002391 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002392 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002393 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002394 }
2395
Hans Wennborg0a20f542014-08-29 00:16:06 +00002396 // Handle dropped DLL attributes.
2397 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2398 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2399
Andrey Bokhankocab58582015-08-31 13:20:44 +00002400 // If there are two attempts to define the same mangled name, issue an
2401 // error.
2402 if (IsForDefinition && !Entry->isDeclaration()) {
2403 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002404 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2405 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002406 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2407 (GD.getCanonicalDecl().getDecl() !=
2408 OtherGD.getCanonicalDecl().getDecl()) &&
2409 DiagnosedConflictingDefinitions.insert(GD).second) {
2410 getDiags().Report(D->getLocation(),
2411 diag::err_duplicate_mangled_name);
2412 getDiags().Report(OtherGD.getDecl()->getLocation(),
2413 diag::note_previous_definition);
2414 }
2415 }
2416
2417 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2418 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002419 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002420 }
Mike Stump11289f42009-09-09 15:08:12 +00002421
Chris Lattnera85d68e2009-03-21 09:25:43 +00002422 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002423 // (If function is requested for a definition, we always need to create a new
2424 // function, not just return a bitcast.)
2425 if (!IsForDefinition)
2426 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002427 }
Mike Stump11289f42009-09-09 15:08:12 +00002428
Eli Friedmancc522d92009-11-09 05:07:37 +00002429 // This function doesn't have a complete type (for example, the return
2430 // type is an incomplete struct). Use a fake type instead, and make
2431 // sure not to try to set attributes.
2432 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002433
Chris Lattner2192fe52011-07-18 04:24:23 +00002434 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002435 if (isa<llvm::FunctionType>(Ty)) {
2436 FTy = cast<llvm::FunctionType>(Ty);
2437 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002438 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002439 IsIncompleteFunction = true;
2440 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002441
2442 llvm::Function *F =
2443 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2444 Entry ? StringRef() : MangledName, &getModule());
2445
2446 // If we already created a function with the same mangled name (but different
2447 // type) before, take its name and add it to the list of functions to be
2448 // replaced with F at the end of CodeGen.
2449 //
2450 // This happens if there is a prototype for a function (e.g. "int f()") and
2451 // then a definition of a different type (e.g. "int f(int x)").
2452 if (Entry) {
2453 F->takeName(Entry);
2454
2455 // This might be an implementation of a function without a prototype, in
2456 // which case, try to do special replacement of calls which match the new
2457 // prototype. The really key thing here is that we also potentially drop
2458 // arguments from the call site so as to make a direct call, which makes the
2459 // inliner happier and suppresses a number of optimizer warnings (!) about
2460 // dropping arguments.
2461 if (!Entry->use_empty()) {
2462 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2463 Entry->removeDeadConstantUsers();
2464 }
2465
2466 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2467 F, Entry->getType()->getElementType()->getPointerTo());
2468 addGlobalValReplacement(Entry, BC);
2469 }
2470
John McCall7ec50432010-03-19 23:29:14 +00002471 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002472 if (D)
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002473 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00002474 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2475 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002476 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002477 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002478
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002479 if (!DontDefer) {
2480 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2481 // each other bottoming out with the base dtor. Therefore we emit non-base
2482 // dtors on usage, even if there is no dtor definition in the TU.
2483 if (D && isa<CXXDestructorDecl>(D) &&
2484 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2485 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002486 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002487
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002488 // This is the first use or definition of a mangled name. If there is a
2489 // deferred decl with this name, remember that we need to emit it at the end
2490 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002491 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002492 if (DDI != DeferredDecls.end()) {
2493 // Move the potentially referenced deferred decl to the
2494 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2495 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002496 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002497 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002498
2499 // Otherwise, there are cases we have to worry about where we're
2500 // using a declaration for which we must emit a definition but where
2501 // we might not find a top-level definition:
2502 // - member functions defined inline in their classes
2503 // - friend functions defined inline in some class
2504 // - special member functions with implicit definitions
2505 // If we ever change our AST traversal to walk into class methods,
2506 // this will be unnecessary.
2507 //
2508 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002509 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002510 } else if (getLangOpts().CPlusPlus && D) {
2511 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002512 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2513 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002514 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002515 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002516 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002517 break;
2518 }
John McCall357d0f32010-12-15 04:00:32 +00002519 }
Richard Smith46bb5812014-08-01 01:56:39 +00002520 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002521 }
Chris Lattner45470942009-03-21 09:44:56 +00002522 }
Mike Stump11289f42009-09-09 15:08:12 +00002523
John McCalld06fb862010-04-28 00:00:30 +00002524 // Make sure the result is of the requested type.
2525 if (!IsIncompleteFunction) {
2526 assert(F->getType()->getElementType() == Ty);
2527 return F;
2528 }
2529
Chris Lattnera5f58b02011-07-09 17:41:47 +00002530 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002531 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002532}
2533
Chris Lattnerd4808922009-03-22 21:03:39 +00002534/// GetAddrOfFunction - Return the address of the given function. If Ty is
2535/// non-null, then this function will use the specified type if it has to
2536/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002537llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002538 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002539 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002540 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002541 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002542 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002543 if (!Ty) {
2544 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2545 auto CanonTy = Context.getCanonicalType(FD->getType());
2546 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2547 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002548
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002549 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002550 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002551 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002552 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002553}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002554
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002555static const FunctionDecl *
2556GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2557 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2558 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2559
2560 IdentifierInfo &CII = C.Idents.get(Name);
2561 for (const auto &Result : DC->lookup(&CII))
2562 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2563 return FD;
2564
2565 if (!C.getLangOpts().CPlusPlus)
2566 return nullptr;
2567
2568 // Demangle the premangled name from getTerminateFn()
2569 IdentifierInfo &CXXII =
2570 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2571 ? C.Idents.get("terminate")
2572 : C.Idents.get(Name);
2573
2574 for (const auto &N : {"__cxxabiv1", "std"}) {
2575 IdentifierInfo &NS = C.Idents.get(N);
2576 for (const auto &Result : DC->lookup(&NS)) {
2577 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2578 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2579 for (const auto &Result : LSD->lookup(&NS))
2580 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2581 break;
2582
2583 if (ND)
2584 for (const auto &Result : ND->lookup(&CXXII))
2585 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2586 return FD;
2587 }
2588 }
2589
2590 return nullptr;
2591}
2592
Chris Lattnerd4808922009-03-22 21:03:39 +00002593/// CreateRuntimeFunction - Create a new runtime function with the specified
2594/// type and name.
2595llvm::Constant *
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002596CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002597 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002598 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002599 llvm::Constant *C =
2600 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002601 /*DontDefer=*/false, /*IsThunk=*/false,
2602 ExtraAttrs);
2603
2604 if (auto *F = dyn_cast<llvm::Function>(C)) {
2605 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00002606 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002607
2608 if (!Local && getTriple().isOSBinFormatCOFF() &&
Martell Maloneb22e6002017-11-04 02:15:49 +00002609 !getCodeGenOpts().LTOVisibilityPublicStd &&
2610 !getTriple().isWindowsGNUEnvironment()) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002611 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2612 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2613 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2614 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2615 }
2616 }
2617 }
2618 }
2619
John McCall882987f2013-02-28 19:01:20 +00002620 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00002621}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002622
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002623/// CreateBuiltinFunction - Create a new builtin function with the specified
2624/// type and name.
2625llvm::Constant *
Reid Klecknerde864822017-03-21 16:57:30 +00002626CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2627 llvm::AttributeList ExtraAttrs) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002628 llvm::Constant *C =
2629 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2630 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2631 if (auto *F = dyn_cast<llvm::Function>(C))
2632 if (F->empty())
2633 F->setCallingConv(getBuiltinCC());
2634 return C;
2635}
2636
Richard Smithe070fd22012-02-17 06:48:11 +00002637/// isTypeConstant - Determine whether an object of this type can be emitted
2638/// as a constant.
2639///
2640/// If ExcludeCtor is true, the duration when the object's constructor runs
2641/// will not be considered. The caller will need to verify that the object is
2642/// not written to during its construction.
2643bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2644 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00002645 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00002646
David Blaikiebbafb8a2012-03-11 07:00:24 +00002647 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00002648 if (const CXXRecordDecl *Record
2649 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2650 return ExcludeCtor && !Record->hasMutableFields() &&
2651 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00002652 }
Richard Smithe070fd22012-02-17 06:48:11 +00002653
Eli Friedmanb095e152009-12-11 21:23:03 +00002654 return true;
2655}
2656
Chris Lattnerd4808922009-03-22 21:03:39 +00002657/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2658/// create and return an llvm GlobalVariable with the specified type. If there
2659/// is something in the module with the specified name, return it potentially
2660/// bitcasted to the right type.
2661///
2662/// If D is non-null, it specifies a decl that correspond to this. This is used
2663/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002664///
2665/// If IsForDefinition is true, it is guranteed that an actual global with
2666/// type Ty will be returned, not conversion of a variable with the same
2667/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00002668llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002669CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00002670 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002671 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00002672 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00002673 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002674 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00002675 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002676 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002677 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002678 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002679 }
2680
Hans Wennborg0a20f542014-08-29 00:16:06 +00002681 // Handle dropped DLL attributes.
2682 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2683 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2684
Chris Lattnerd4808922009-03-22 21:03:39 +00002685 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00002686 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00002687
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002688 // If there are two attempts to define the same mangled name, issue an
2689 // error.
2690 if (IsForDefinition && !Entry->isDeclaration()) {
2691 GlobalDecl OtherGD;
2692 const VarDecl *OtherD;
2693
2694 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2695 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00002696 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002697 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2698 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2699 OtherD->hasInit() &&
2700 DiagnosedConflictingDefinitions.insert(D).second) {
2701 getDiags().Report(D->getLocation(),
2702 diag::err_duplicate_mangled_name);
2703 getDiags().Report(OtherGD.getDecl()->getLocation(),
2704 diag::note_previous_definition);
2705 }
2706 }
2707
Chris Lattner3bfce182009-03-21 08:03:33 +00002708 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00002709 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2710 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2711
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002712 // (If global is requested for a definition, we always need to create a new
2713 // global, not just return a bitcast.)
2714 if (!IsForDefinition)
2715 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00002716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
Yaxun Liucbf647c2017-07-08 13:24:52 +00002718 auto AddrSpace = GetGlobalVarAddressSpace(D);
2719 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2720
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002721 auto *GV = new llvm::GlobalVariable(
2722 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002723 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00002724 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00002725
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002726 // If we already created a global with the same mangled name (but different
2727 // type) before, take its name and remove it from its parent.
2728 if (Entry) {
2729 GV->takeName(Entry);
2730
2731 if (!Entry->use_empty()) {
2732 llvm::Constant *NewPtrForOldDecl =
2733 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2734 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2735 }
2736
2737 Entry->eraseFromParent();
2738 }
2739
Chris Lattner45470942009-03-21 09:44:56 +00002740 // This is the first use or definition of a mangled name. If there is a
2741 // deferred decl with this name, remember that we need to emit it at the end
2742 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002743 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00002744 if (DDI != DeferredDecls.end()) {
2745 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2746 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002747 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00002748 DeferredDecls.erase(DDI);
2749 }
Mike Stump11289f42009-09-09 15:08:12 +00002750
Chris Lattner3bfce182009-03-21 08:03:33 +00002751 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00002752 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00002753 // FIXME: This code is overly simple and should be merged with other global
2754 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00002755 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00002756
Ulrich Weigand46084382015-04-21 17:27:59 +00002757 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2758
Jake Ehrlichba874ad2017-11-29 00:54:20 +00002759 setLinkageForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00002760
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002761 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00002762 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00002763 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00002764 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002765 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00002766
Rafael Espindola3dd49812018-02-23 00:22:15 +00002767 setGVProperties(GV, D);
2768
Hans Wennborgfeedf852013-11-21 00:15:56 +00002769 // If required by the ABI, treat declarations of static data members with
2770 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002771 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00002772 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002773 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00002774
Erich Keane99fdfb62017-09-26 23:42:34 +00002775 // Emit section information for extern variables.
2776 if (D->hasExternalStorage()) {
2777 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
2778 GV->setSection(SA->getName());
2779 }
2780
Robert Lyttonf80d6882014-05-02 09:33:30 +00002781 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00002782 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00002783 D->getLanguageLinkage() == CLanguageLinkage &&
2784 D->getType().isConstant(Context) &&
2785 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2786 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00002787
2788 // Check if we a have a const declaration with an initializer, we may be
2789 // able to emit it as available_externally to expose it's value to the
2790 // optimizer.
2791 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2792 D->getType().isConstQualified() && !GV->hasInitializer() &&
2793 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
2794 const auto *Record =
2795 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
2796 bool HasMutableFields = Record && Record->hasMutableFields();
2797 if (!HasMutableFields) {
2798 const VarDecl *InitDecl;
2799 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2800 if (InitExpr) {
2801 ConstantEmitter emitter(*this);
2802 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
2803 if (Init) {
2804 auto *InitType = Init->getType();
2805 if (GV->getType()->getElementType() != InitType) {
2806 // The type of the initializer does not match the definition.
2807 // This happens when an initializer has a different type from
2808 // the type of the global (because of padding at the end of a
2809 // structure for instance).
2810 GV->setName(StringRef());
2811 // Make a new global with the correct type, this is now guaranteed
2812 // to work.
2813 auto *NewGV = cast<llvm::GlobalVariable>(
2814 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
2815
2816 // Erase the old global, since it is no longer used.
George Burgess IV00f70bd2018-03-01 05:43:23 +00002817 GV->eraseFromParent();
Mehdi Amini7cb1b302017-09-05 03:58:35 +00002818 GV = NewGV;
2819 } else {
2820 GV->setInitializer(Init);
2821 GV->setConstant(true);
2822 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
2823 }
2824 emitter.finalize(GV);
2825 }
2826 }
2827 }
2828 }
Chris Lattnerd4808922009-03-22 21:03:39 +00002829 }
Mike Stump11289f42009-09-09 15:08:12 +00002830
Alexander Richardson6d989432017-10-15 18:48:14 +00002831 LangAS ExpectedAS =
Yaxun Liucbf647c2017-07-08 13:24:52 +00002832 D ? D->getType().getAddressSpace()
Alexander Richardson6d989432017-10-15 18:48:14 +00002833 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00002834 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2835 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00002836 if (AddrSpace != ExpectedAS)
2837 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2838 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00002839
2840 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002841}
2842
Andrey Bokhankocab58582015-08-31 13:20:44 +00002843llvm::Constant *
2844CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00002845 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002846 const Decl *D = GD.getDecl();
2847 if (isa<CXXConstructorDecl>(D))
2848 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002849 getFromCtorType(GD.getCtorType()),
2850 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2851 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002852 else if (isa<CXXDestructorDecl>(D))
2853 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002854 getFromDtorType(GD.getDtorType()),
2855 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2856 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002857 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002858 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002859 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00002860 auto Ty = getTypes().GetFunctionType(*FInfo);
2861 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2862 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002863 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002864 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2865 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2866 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2867 IsForDefinition);
2868 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002869 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002870 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002871}
Chris Lattnerd4808922009-03-22 21:03:39 +00002872
Anders Carlssonda80af32011-01-29 18:20:20 +00002873llvm::GlobalVariable *
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002874CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00002875 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00002876 llvm::GlobalValue::LinkageTypes Linkage) {
2877 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00002878 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00002879
Anders Carlssonda80af32011-01-29 18:20:20 +00002880 if (GV) {
2881 // Check if the variable has the right type.
2882 if (GV->getType()->getElementType() == Ty)
2883 return GV;
2884
2885 // Because C++ name mangling, the only way we can end up with an already
2886 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00002887 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00002888 OldGV = GV;
2889 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002890
Anders Carlssonda80af32011-01-29 18:20:20 +00002891 // Create a new variable.
2892 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00002893 Linkage, nullptr, Name);
2894
Anders Carlssonda80af32011-01-29 18:20:20 +00002895 if (OldGV) {
2896 // Replace occurrences of the old variable if needed.
2897 GV->takeName(OldGV);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002898
Anders Carlssonda80af32011-01-29 18:20:20 +00002899 if (!OldGV->use_empty()) {
2900 llvm::Constant *NewPtrForOldDecl =
2901 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2902 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2903 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002904
Anders Carlssonda80af32011-01-29 18:20:20 +00002905 OldGV->eraseFromParent();
2906 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00002907
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002908 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2909 !GV->hasAvailableExternallyLinkage())
2910 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00002911
Anders Carlssonda80af32011-01-29 18:20:20 +00002912 return GV;
2913}
2914
Chris Lattnerd4808922009-03-22 21:03:39 +00002915/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2916/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00002917/// then it will be created with the specified type instead of whatever the
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002918/// normal requested type would be. If IsForDefinition is true, it is guranteed
2919/// that an actual global with type Ty will be returned, not conversion of a
2920/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00002921llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002922 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00002923 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002924 assert(D->hasGlobalStorage() && "Not a global variable");
2925 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00002926 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00002927 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00002928
Chris Lattner2192fe52011-07-18 04:24:23 +00002929 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002930 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00002931
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002932 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002933 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002934}
2935
2936/// CreateRuntimeVariable - Create a new runtime global variable with the
2937/// specified type and name.
2938llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00002939CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002940 StringRef Name) {
Rafael Espindolab73c9732014-05-22 23:33:27 +00002941 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
Chris Lattnerd4808922009-03-22 21:03:39 +00002942}
2943
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002944void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2945 assert(!D->getInit() && "Cannot emit definite definitions here!");
2946
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002947 StringRef MangledName = getMangledName(D);
2948 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2949
2950 // We already have a definition, not declaration, with the same mangled name.
2951 // Emitting of declaration is not required (and actually overwrites emitted
2952 // definition).
2953 if (GV && !GV->isDeclaration())
2954 return;
2955
2956 // If we have not seen a reference to this variable yet, place it into the
2957 // deferred declarations table to be emitted if needed later.
2958 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002959 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002960 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00002961 }
2962
2963 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00002964 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002965}
2966
Chris Lattner2192fe52011-07-18 04:24:23 +00002967CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00002968 return Context.toCharUnitsFromBits(
2969 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00002970}
2971
Alexander Richardson6d989432017-10-15 18:48:14 +00002972LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
2973 LangAS AddrSpace = LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +00002974 if (LangOpts.OpenCL) {
Alexander Richardson6d989432017-10-15 18:48:14 +00002975 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
Yaxun Liucbf647c2017-07-08 13:24:52 +00002976 assert(AddrSpace == LangAS::opencl_global ||
2977 AddrSpace == LangAS::opencl_constant ||
2978 AddrSpace == LangAS::opencl_local ||
2979 AddrSpace >= LangAS::FirstTargetAddressSpace);
2980 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002981 }
2982
Yaxun Liucbf647c2017-07-08 13:24:52 +00002983 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2984 if (D && D->hasAttr<CUDAConstantAttr>())
2985 return LangAS::cuda_constant;
2986 else if (D && D->hasAttr<CUDASharedAttr>())
2987 return LangAS::cuda_shared;
2988 else
2989 return LangAS::cuda_device;
2990 }
2991
2992 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002993}
2994
Richard Smithdf931ce2013-04-06 05:00:46 +00002995template<typename SomeDecl>
2996void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2997 llvm::GlobalValue *GV) {
2998 if (!getLangOpts().CPlusPlus)
2999 return;
3000
3001 // Must have 'used' attribute, or else inline assembly can't rely on
3002 // the name existing.
3003 if (!D->template hasAttr<UsedAttr>())
3004 return;
3005
3006 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00003007 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00003008 return;
3009
3010 // Must be in an extern "C" context. Entities declared directly within
3011 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003012 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00003013 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00003014 return;
3015
3016 // OK, this is an internal linkage entity inside an extern "C" linkage
3017 // specification. Make a note of that so we can give it the "expected"
3018 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00003019 std::pair<StaticExternCMap::iterator, bool> R =
3020 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00003021
3022 // If we have multiple internal linkage entities with the same name
3023 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00003024 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00003025 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00003026}
3027
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003028static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3029 if (!CGM.supportsCOMDAT())
3030 return false;
3031
3032 if (D.hasAttr<SelectAnyAttr>())
3033 return true;
3034
3035 GVALinkage Linkage;
3036 if (auto *VD = dyn_cast<VarDecl>(&D))
3037 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3038 else
3039 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3040
3041 switch (Linkage) {
3042 case GVA_Internal:
3043 case GVA_AvailableExternally:
3044 case GVA_StrongExternal:
3045 return false;
3046 case GVA_DiscardableODR:
3047 case GVA_StrongODR:
3048 return true;
3049 }
3050 llvm_unreachable("No such linkage");
3051}
3052
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003053void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3054 llvm::GlobalObject &GO) {
3055 if (!shouldBeInCOMDAT(*this, D))
3056 return;
3057 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3058}
3059
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003060/// Pass IsTentative as true if you want to create a tentative definition.
3061void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3062 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003063 // OpenCL global variables of sampler type are translated to function calls,
3064 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003065 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003066 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3067 return;
3068
3069 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00003070 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3071 bool NeedsGlobalCtor = false;
3072 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00003073
Richard Smithdafff942012-01-14 04:30:29 +00003074 const VarDecl *InitDecl;
3075 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003076
John McCallde0fe072017-08-15 21:42:52 +00003077 Optional<ConstantEmitter> emitter;
3078
Artem Belevich97c01c32016-02-02 22:29:48 +00003079 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3080 // as part of their declaration." Sema has already checked for
3081 // error cases, so we just need to set Init to UndefValue.
3082 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3083 D->hasAttr<CUDASharedAttr>())
Jingyue Wu284ebe22015-08-22 05:49:28 +00003084 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00003085 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00003086 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003087 // implicitly initialized with { 0 }.
3088 //
3089 // Note that tentative definitions are only emitted at the end of
3090 // a translation unit, so they should never have incomplete
3091 // type. In addition, EmitTentativeDefinition makes sure that we
3092 // never attempt to emit a tentative definition if a real one
3093 // exists. A use may still exists, however, so we still may need
3094 // to do a RAUW.
3095 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00003096 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003097 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003098 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00003099 emitter.emplace(*this);
3100 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003101
Fariborz Jahanian63628032012-06-26 16:06:38 +00003102 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00003103 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00003104 if (D->getType()->isReferenceType())
3105 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00003106
David Blaikiebbafb8a2012-03-11 07:00:24 +00003107 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003108 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00003109 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003110 } else {
3111 ErrorUnsupported(D, "static initializer");
3112 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3113 }
John McCall70013b62010-07-15 23:40:35 +00003114 } else {
3115 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00003116 // initializer position (just in case this entry was delayed) if we
3117 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003118 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00003119 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00003120 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003121 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003122
Chris Lattner2192fe52011-07-18 04:24:23 +00003123 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003124 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00003125 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00003126
Chris Lattner149927c2009-03-21 09:16:30 +00003127 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003128 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00003129 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00003130 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3131 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00003132 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00003133 Entry = CE->getOperand(0);
3134 }
Mike Stump11289f42009-09-09 15:08:12 +00003135
Chris Lattner149927c2009-03-21 09:16:30 +00003136 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003137 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003138
Chris Lattner149927c2009-03-21 09:16:30 +00003139 // We have a definition after a declaration with the wrong type.
3140 // We must make a new GlobalVariable* and update everything that used OldGV
3141 // (a declaration or tentative definition) with the new GlobalVariable*
3142 // (which will be a definition).
3143 //
3144 // This happens if there is a prototype for a global (e.g.
3145 // "extern int x[];") and then a definition of a different type (e.g.
3146 // "int x[10];"). This also happens when an initializer has a different type
3147 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00003148 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003149 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00003150 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00003151
John McCall7ec50432010-03-19 23:29:14 +00003152 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003153 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00003154
Chris Lattner149927c2009-03-21 09:16:30 +00003155 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003156 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00003157 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00003158
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003159 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00003160 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00003161 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00003162 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003163
3164 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00003165 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00003166 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00003167
Richard Smithdf931ce2013-04-06 05:00:46 +00003168 MaybeHandleStaticInExternC(D, GV);
3169
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003170 if (D->hasAttr<AnnotateAttr>())
3171 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00003172
Artem Belevich42e19492016-03-02 18:28:50 +00003173 // Set the llvm linkage type as appropriate.
3174 llvm::GlobalValue::LinkageTypes Linkage =
3175 getLLVMLinkageVarDefinition(D, GV->isConstant());
3176
Jingyue Wu284ebe22015-08-22 05:49:28 +00003177 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3178 // the device. [...]"
3179 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3180 // __device__, declares a variable that: [...]
3181 // Is accessible from all the threads within the grid and from the host
3182 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3183 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00003184 if (GV && LangOpts.CUDA) {
3185 if (LangOpts.CUDAIsDevice) {
3186 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3187 GV->setExternallyInitialized(true);
3188 } else {
3189 // Host-side shadows of external declarations of device-side
3190 // global variables become internal definitions. These have to
3191 // be internal in order to prevent name conflicts with global
3192 // host variables with the same name in a different TUs.
3193 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3194 Linkage = llvm::GlobalValue::InternalLinkage;
3195
3196 // Shadow variables and their properties must be registered
3197 // with CUDA runtime.
3198 unsigned Flags = 0;
3199 if (!D->hasDefinition())
3200 Flags |= CGCUDARuntime::ExternDeviceVar;
3201 if (D->hasAttr<CUDAConstantAttr>())
3202 Flags |= CGCUDARuntime::ConstantDeviceVar;
3203 getCUDARuntime().registerDeviceVar(*GV, Flags);
3204 } else if (D->hasAttr<CUDASharedAttr>())
3205 // __shared__ variables are odd. Shadows do get created, but
3206 // they are not registered with the CUDA runtime, so they
3207 // can't really be used to access their device-side
3208 // counterparts. It's not clear yet whether it's nvcc's bug or
3209 // a feature, but we've got to do the same for compatibility.
3210 Linkage = llvm::GlobalValue::InternalLinkage;
3211 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00003212 }
John McCallde0fe072017-08-15 21:42:52 +00003213
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003214 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00003215 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00003216
3217 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00003218 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3219 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00003220
Hans Wennborg899ded92014-10-16 20:52:46 +00003221 // If it is in a read-only section, mark it 'constant'.
3222 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3223 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3224 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3225 GV->setConstant(true);
3226 }
3227
Ken Dyck160146e2010-01-27 17:10:57 +00003228 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00003229
David Majnemer35ab3282014-06-11 04:08:55 +00003230
Manman Ren68150262015-11-11 22:42:31 +00003231 // On Darwin, if the normal linkage of a C++ thread_local variable is
3232 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3233 // copies within a linkage unit; otherwise, the backing variable has
3234 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00003235 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00003236 // variable. This is to preserve the ability to change the implementation
3237 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00003238 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00003239 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00003240 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3241 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00003242 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00003243
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003244 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00003245 if (D->hasAttr<DLLImportAttr>())
3246 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3247 else if (D->hasAttr<DLLExportAttr>())
3248 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00003249 else
3250 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00003251
Yaxun Liu402804b2016-12-15 08:09:08 +00003252 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00003253 // common vars aren't constant even if declared const.
3254 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00003255 // Tentative definition of global variables may be initialized with
3256 // non-zero null pointers. In this case they should have weak linkage
3257 // since common linkage must have zero initializer and must not have
3258 // explicit section therefore cannot have non-zero initial value.
3259 if (!GV->getInitializer()->isNullValue())
3260 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3261 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00003262
Rafael Espindola502f65a2014-05-05 20:21:03 +00003263 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00003264
David Majnemerbb525f7c2014-10-15 22:38:23 +00003265 if (D->getTLSKind() && !GV->isThreadLocal()) {
3266 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003267 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00003268 setTLSMode(GV, *D);
3269 }
3270
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003271 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003272
John McCallcdf7ef52010-11-06 09:44:32 +00003273 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00003274 if (NeedsGlobalCtor || NeedsGlobalDtor)
3275 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00003276
Alexey Samsonov4b8de112014-08-01 21:35:28 +00003277 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00003278
Sanjiv Gupta158143a2008-06-05 08:59:10 +00003279 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00003280 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003281 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00003282 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003283}
Chris Lattner09153c02007-06-22 18:48:09 +00003284
David Majnemerc017d362014-08-05 00:01:13 +00003285static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00003286 CodeGenModule &CGM, const VarDecl *D,
3287 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00003288 // Don't give variables common linkage if -fno-common was specified unless it
3289 // was overridden by a NoCommon attribute.
3290 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3291 return true;
3292
3293 // C11 6.9.2/2:
3294 // A declaration of an identifier for an object that has file scope without
3295 // an initializer, and without a storage-class specifier or with the
3296 // storage-class specifier static, constitutes a tentative definition.
3297 if (D->getInit() || D->hasExternalStorage())
3298 return true;
3299
3300 // A variable cannot be both common and exist in a section.
3301 if (D->hasAttr<SectionAttr>())
3302 return true;
3303
Javed Absar2a67c9e2017-06-05 10:11:57 +00003304 // A variable cannot be both common and exist in a section.
3305 // We dont try to determine which is the right section in the front-end.
3306 // If no specialized section name is applicable, it will resort to default.
3307 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3308 D->hasAttr<PragmaClangDataSectionAttr>() ||
3309 D->hasAttr<PragmaClangRodataSectionAttr>())
3310 return true;
3311
David Majnemer9832a3d2014-04-10 16:53:16 +00003312 // Thread local vars aren't considered common linkage.
3313 if (D->getTLSKind())
3314 return true;
3315
3316 // Tentative definitions marked with WeakImportAttr are true definitions.
3317 if (D->hasAttr<WeakImportAttr>())
3318 return true;
3319
Nico Weber608e7682015-04-15 23:04:24 +00003320 // A variable cannot be both common and exist in a comdat.
3321 if (shouldBeInCOMDAT(CGM, *D))
3322 return true;
3323
Sanjay Patel2f9303a2016-06-30 21:02:40 +00003324 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00003325 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00003326 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00003327 if (D->hasAttr<AlignedAttr>())
3328 return true;
3329 QualType VarType = D->getType();
3330 if (Context.isAlignmentRequired(VarType))
3331 return true;
3332
3333 if (const auto *RT = VarType->getAs<RecordType>()) {
3334 const RecordDecl *RD = RT->getDecl();
3335 for (const FieldDecl *FD : RD->fields()) {
3336 if (FD->isBitField())
3337 continue;
3338 if (FD->hasAttr<AlignedAttr>())
3339 return true;
3340 if (Context.isAlignmentRequired(FD->getType()))
3341 return true;
3342 }
3343 }
3344 }
David Majnemerc017d362014-08-05 00:01:13 +00003345
David Majnemer9832a3d2014-04-10 16:53:16 +00003346 return false;
3347}
3348
Hans Wennborg1a3a0742014-05-14 19:54:53 +00003349llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00003350 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003351 if (Linkage == GVA_Internal)
3352 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003353
3354 if (D->hasAttr<WeakAttr>()) {
3355 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003356 return llvm::GlobalVariable::WeakODRLinkage;
3357 else
3358 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003359 }
3360
3361 // We are guaranteed to have a strong definition somewhere else,
3362 // so we can use available_externally linkage.
3363 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003364 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003365
David Majnemer27d69db2014-04-28 22:17:59 +00003366 // Note that Apple's kernel linker doesn't support symbol
3367 // coalescing, so we need to avoid linkonce and weak linkages there.
3368 // Normally, this means we just map to internal, but for explicit
3369 // instantiations we'll map to external.
3370
3371 // In C++, the compiler has to emit a definition in every translation unit
3372 // that references the function. We should use linkonce_odr because
3373 // a) if all references in this translation unit are optimized away, we
3374 // don't need to codegen it. b) if the function persists, it needs to be
3375 // merged with other definitions. c) C++ has the ODR, so we know the
3376 // definition is dependable.
3377 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00003378 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00003379 : llvm::Function::InternalLinkage;
3380
3381 // An explicit instantiation of a template has weak linkage, since
3382 // explicit instantiations can occur in multiple translation units
3383 // and must all be equivalent. However, we are not allowed to
3384 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00003385 //
3386 // We don't currently support CUDA device code spread out across multiple TUs,
3387 // so say that CUDA templates are either external (for kernels) or internal.
3388 // This lets llvm perform aggressive inter-procedural optimizations.
3389 if (Linkage == GVA_StrongODR) {
3390 if (Context.getLangOpts().AppleKext)
3391 return llvm::Function::ExternalLinkage;
3392 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3393 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3394 : llvm::Function::InternalLinkage;
3395 return llvm::Function::WeakODRLinkage;
3396 }
David Majnemer27d69db2014-04-28 22:17:59 +00003397
David Majnemer27d69db2014-04-28 22:17:59 +00003398 // C++ doesn't have tentative definitions and thus cannot have common
3399 // linkage.
3400 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00003401 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00003402 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00003403 return llvm::GlobalVariable::CommonLinkage;
3404
David Majnemer27d69db2014-04-28 22:17:59 +00003405 // selectany symbols are externally visible, so use weak instead of
3406 // linkonce. MSVC optimizes away references to const selectany globals, so
3407 // all definitions should be the same and ODR linkage should be used.
3408 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3409 if (D->hasAttr<SelectAnyAttr>())
3410 return llvm::GlobalVariable::WeakODRLinkage;
3411
3412 // Otherwise, we have strong external linkage.
3413 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003414 return llvm::GlobalVariable::ExternalLinkage;
3415}
3416
David Majnemer27d69db2014-04-28 22:17:59 +00003417llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3418 const VarDecl *VD, bool IsConstant) {
3419 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00003420 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00003421}
3422
John McCall49954ca2012-12-12 22:21:47 +00003423/// Replace the uses of a function that was declared with a non-proto type.
3424/// We want to silently drop extra arguments from call sites
3425static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3426 llvm::Function *newFn) {
3427 // Fast path.
3428 if (old->use_empty()) return;
3429
3430 llvm::Type *newRetTy = newFn->getReturnType();
3431 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00003432 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00003433
3434 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3435 ui != ue; ) {
3436 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003437 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00003438
3439 // Recognize and replace uses of bitcasts. Most calls to
3440 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003441 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00003442 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3443 replaceUsesOfNonProtoConstant(bitcast, newFn);
3444 continue;
3445 }
3446
3447 // Recognize calls to the function.
3448 llvm::CallSite callSite(user);
3449 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003450 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00003451
3452 // If the return types don't match exactly, then we can't
3453 // transform this call unless it's dead.
3454 if (callSite->getType() != newRetTy && !callSite->use_empty())
3455 continue;
3456
3457 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00003458 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
Reid Klecknerde864822017-03-21 16:57:30 +00003459 llvm::AttributeList oldAttrs = callSite.getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00003460
John McCall49954ca2012-12-12 22:21:47 +00003461 // If the function was passed too few arguments, don't transform.
3462 unsigned newNumArgs = newFn->arg_size();
3463 if (callSite.arg_size() < newNumArgs) continue;
3464
3465 // If extra arguments were passed, we silently drop them.
3466 // If any of the types mismatch, we don't transform.
3467 unsigned argNo = 0;
3468 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00003469 for (llvm::Argument &A : newFn->args()) {
3470 if (callSite.getArgument(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00003471 dontTransform = true;
3472 break;
3473 }
3474
3475 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00003476 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00003477 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00003478 }
3479 if (dontTransform)
3480 continue;
3481
John McCall49954ca2012-12-12 22:21:47 +00003482 // Okay, we can transform this. Create the new call instruction and copy
3483 // over the required information.
3484 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3485
David Majnemer0b17d442015-12-15 21:27:59 +00003486 // Copy over any operand bundles.
3487 callSite.getOperandBundlesAsDefs(newBundles);
3488
John McCall49954ca2012-12-12 22:21:47 +00003489 llvm::CallSite newCall;
3490 if (callSite.isCall()) {
David Majnemer0b17d442015-12-15 21:27:59 +00003491 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003492 callSite.getInstruction());
3493 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003494 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00003495 newCall = llvm::InvokeInst::Create(newFn,
3496 oldInvoke->getNormalDest(),
3497 oldInvoke->getUnwindDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003498 newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003499 callSite.getInstruction());
3500 }
3501 newArgs.clear(); // for the next iteration
3502
3503 if (!newCall->getType()->isVoidTy())
3504 newCall->takeName(callSite.getInstruction());
Reid Kleckner7f720332017-04-13 00:58:09 +00003505 newCall.setAttributes(llvm::AttributeList::get(
3506 newFn->getContext(), oldAttrs.getFnAttributes(),
3507 oldAttrs.getRetAttributes(), newArgAttrs));
John McCall49954ca2012-12-12 22:21:47 +00003508 newCall.setCallingConv(callSite.getCallingConv());
3509
3510 // Finally, remove the old call, replacing any uses with the new one.
3511 if (!callSite->use_empty())
3512 callSite->replaceAllUsesWith(newCall.getInstruction());
3513
3514 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003515 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003516 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003517
John McCall49954ca2012-12-12 22:21:47 +00003518 callSite->eraseFromParent();
3519 }
3520}
3521
Chris Lattner36797ab2009-05-05 06:16:31 +00003522/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3523/// implement a function with no prototype, e.g. "int foo() {}". If there are
3524/// existing call uses of the old function in the module, this adjusts them to
3525/// call the new function directly.
3526///
3527/// This is not just a cleanup: the always_inline pass requires direct calls to
3528/// functions to be able to inline them. If there is a bitcast in the way, it
3529/// won't inline them. Instcombine normally deletes these calls, but it isn't
3530/// run at -O0.
3531static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3532 llvm::Function *NewFn) {
3533 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003534 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003535
John McCall49954ca2012-12-12 22:21:47 +00003536 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003537}
3538
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003539void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00003540 auto DK = VD->isThisDeclarationADefinition();
3541 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3542 return;
3543
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003544 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3545 // If we have a definition, this might be a deferred decl. If the
3546 // instantiation is explicit, make sure we emit it at the end.
3547 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3548 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003549
3550 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00003551}
Daniel Dunbar9c426522008-07-29 23:18:29 +00003552
Rafael Espindolacd7743b2013-12-09 16:01:03 +00003553void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3554 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003555 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00003556
John McCall46288ef2011-03-09 08:12:35 +00003557 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00003558 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3559 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00003560
Chris Lattnereb7466d2009-05-12 20:58:15 +00003561 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003562 if (!GV || (GV->getType()->getElementType() != Ty))
3563 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3564 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00003565 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00003566
Andrey Bokhankocab58582015-08-31 13:20:44 +00003567 // Already emitted.
3568 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00003569 return;
Mike Stump11289f42009-09-09 15:08:12 +00003570
John McCall8e7cb6d2010-11-02 21:04:24 +00003571 // We need to set linkage and visibility on the function before
3572 // generating code for it because various parts of IR generation
3573 // want to propagate this information down (e.g. to local static
3574 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003575 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00003576 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003577
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003578 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Rafael Espindolab7350042018-03-01 00:35:47 +00003579 setGVProperties(Fn, GD);
John McCall8e7cb6d2010-11-02 21:04:24 +00003580
Richard Smithdf931ce2013-04-06 05:00:46 +00003581 MaybeHandleStaticInExternC(D, Fn);
3582
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003583 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003584
John McCalla738c252011-03-09 04:27:21 +00003585 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00003586
Rafael Espindolae4e78132018-03-01 00:00:02 +00003587 setNonAliasAttributes(GD, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00003588 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00003589
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003590 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003591 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003592 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003593 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003594 if (D->hasAttr<AnnotateAttr>())
3595 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003596}
3597
John McCall7ec50432010-03-19 23:29:14 +00003598void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003599 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003600 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00003601 assert(AA && "Not an alias?");
3602
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003603 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00003604
Hal Finkel0e2b9752015-09-04 21:49:21 +00003605 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003606 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00003607 return;
3608 }
3609
John McCall7ec50432010-03-19 23:29:14 +00003610 // If there is a definition in the module, then it wins over the alias.
3611 // This is dubious, but allow it to be safe. Just ignore the alias.
3612 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3613 if (Entry && !Entry->isDeclaration())
3614 return;
3615
Rafael Espindola208b5c02013-10-22 19:26:13 +00003616 Aliases.push_back(GD);
3617
Chris Lattner2192fe52011-07-18 04:24:23 +00003618 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00003619
3620 // Create a reference to the named value. This ensures that it is emitted
3621 // if a deferred decl.
3622 llvm::Constant *Aliasee;
3623 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00003624 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00003625 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00003626 else
John McCall7ec50432010-03-19 23:29:14 +00003627 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00003628 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00003629 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00003630
3631 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00003632 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00003633 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00003634
Chris Lattner54041692009-03-22 21:47:11 +00003635 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00003636 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003637 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00003638 return;
3639 }
3640
John McCall7ec50432010-03-19 23:29:14 +00003641 assert(Entry->isDeclaration());
3642
Chris Lattner54041692009-03-22 21:47:11 +00003643 // If there is a declaration in the module, then we had an extern followed
3644 // by the alias, as in:
3645 // extern int test6();
3646 // ...
3647 // int test6() __attribute__((alias("test7")));
3648 //
3649 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00003650 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003651
Owen Andersonade90fd2009-07-29 18:54:39 +00003652 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00003653 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00003654 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00003655 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00003656 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00003657 }
Mike Stump11289f42009-09-09 15:08:12 +00003658
Daniel Dunbar38932572009-04-14 08:05:55 +00003659 // Set attributes which are particular to an alias; this is a
3660 // specialization of the attributes which may be set on a global
3661 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00003662 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3663 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00003664 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3665 }
3666
David Majnemerbb525f7c2014-10-15 22:38:23 +00003667 if (const auto *VD = dyn_cast<VarDecl>(D))
3668 if (VD->getTLSKind())
3669 setTLSMode(GA, *VD);
3670
Rafael Espindolab7350042018-03-01 00:35:47 +00003671 SetCommonAttributes(GD, GA);
Chris Lattner54041692009-03-22 21:47:11 +00003672}
3673
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003674void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3675 const auto *D = cast<ValueDecl>(GD.getDecl());
3676 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3677 assert(IFA && "Not an ifunc?");
3678
3679 StringRef MangledName = getMangledName(GD);
3680
3681 if (IFA->getResolver() == MangledName) {
3682 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3683 return;
3684 }
3685
3686 // Report an error if some definition overrides ifunc.
3687 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3688 if (Entry && !Entry->isDeclaration()) {
3689 GlobalDecl OtherGD;
3690 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3691 DiagnosedConflictingDefinitions.insert(GD).second) {
3692 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3693 Diags.Report(OtherGD.getDecl()->getLocation(),
3694 diag::note_previous_definition);
3695 }
3696 return;
3697 }
3698
3699 Aliases.push_back(GD);
3700
3701 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3702 llvm::Constant *Resolver =
3703 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3704 /*ForVTable=*/false);
3705 llvm::GlobalIFunc *GIF =
3706 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3707 "", Resolver, &getModule());
3708 if (Entry) {
3709 if (GIF->getResolver() == Entry) {
3710 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3711 return;
3712 }
3713 assert(Entry->isDeclaration());
3714
3715 // If there is a declaration in the module, then we had an extern followed
3716 // by the ifunc, as in:
3717 // extern int test();
3718 // ...
3719 // int test() __attribute__((ifunc("resolver")));
3720 //
3721 // Remove it and replace uses of it with the ifunc.
3722 GIF->takeName(Entry);
3723
3724 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3725 Entry->getType()));
3726 Entry->eraseFromParent();
3727 } else
3728 GIF->setName(MangledName);
3729
Rafael Espindola75c649c2018-03-01 00:06:55 +00003730 SetCommonAttributes(GD, GIF);
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003731}
3732
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003733llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00003734 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00003735 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003736 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00003737}
Chris Lattner1eec6602007-08-31 04:31:45 +00003738
David Blaikie2e804282015-04-05 22:47:07 +00003739static llvm::StringMapEntry<llvm::GlobalVariable *> &
3740GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3741 const StringLiteral *Literal, bool TargetIsLSB,
3742 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003743 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003744 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00003745
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003746 // Check for simple case.
3747 if (!Literal->containsNonAsciiOrNull()) {
3748 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00003749 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003750 }
3751
Bill Wendling82b87f12012-03-30 00:26:17 +00003752 // Otherwise, convert the UTF8 literals into a string of shorts.
3753 IsUTF16 = true;
3754
Justin Lebar90910552016-09-30 00:38:45 +00003755 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3756 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3757 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00003758
Justin Lebar90910552016-09-30 00:38:45 +00003759 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3760 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00003761
Daniel Dunbar91ade142009-07-23 23:41:22 +00003762 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00003763 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00003764
Bill Wendling82b87f12012-03-30 00:26:17 +00003765 // Add an explicit null.
3766 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00003767 return *Map.insert(std::make_pair(
3768 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3769 (StringLength + 1) * 2),
3770 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00003771}
3772
John McCall7f416cc2015-09-08 08:05:57 +00003773ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00003774CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3775 unsigned StringLength = 0;
3776 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00003777 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3778 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3779 getDataLayout().isLittleEndian(), isUTF16,
3780 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003781
David Blaikie13156b62014-11-19 03:06:06 +00003782 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00003783 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00003784
Chris Lattnerece04092012-02-07 00:39:47 +00003785 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00003786 llvm::Constant *Zeros[] = { Zero, Zero };
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003787
Chris Lattneraa64ca22009-07-16 16:48:25 +00003788 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00003789 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003790 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00003791 Ty = llvm::ArrayType::get(Ty, 0);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003792 llvm::Constant *GV =
3793 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003794
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003795 if (getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003796 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3797 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3798 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3799 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3800
3801 const VarDecl *VD = nullptr;
3802 for (const auto &Result : DC->lookup(&II))
3803 if ((VD = dyn_cast<VarDecl>(Result)))
3804 break;
3805
3806 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3807 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3808 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3809 } else {
3810 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3811 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3812 }
3813 }
3814
Daniel Dunbard644ad62008-08-23 18:37:06 +00003815 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00003816 CFConstantStringClassRef =
3817 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003818 }
Mike Stump11289f42009-09-09 15:08:12 +00003819
Anders Carlssonc2480a52008-11-15 18:54:24 +00003820 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00003821
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003822 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00003823
John McCall23c9dc62016-11-28 22:18:27 +00003824 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003825 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00003826
Anders Carlssonb04ea612007-08-21 00:21:21 +00003827 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003828 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00003829
Anders Carlssonb04ea612007-08-21 00:21:21 +00003830 // Flags.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003831 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
Anders Carlsson157c3212009-08-16 05:55:31 +00003832
Anders Carlssonb04ea612007-08-21 00:21:21 +00003833 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00003834 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00003835 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00003836 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00003837 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3838 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00003839 C = llvm::ConstantDataArray::get(VMContext, Arr);
3840 } else {
David Blaikie13156b62014-11-19 03:06:06 +00003841 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00003842 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00003843
Bill Wendling86131f22012-01-10 08:46:39 +00003844 // Note: -fwritable-strings doesn't make the backing store strings of
3845 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003846 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00003847 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3848 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003849 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00003850 // Don't enforce the target's minimum global alignment, since the only use
3851 // of the string is via this class initializer.
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003852 CharUnits Align = isUTF16
3853 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3854 : getContext().getTypeAlignInChars(getContext().CharTy);
3855 GV->setAlignment(Align.getQuantity());
3856
3857 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3858 // Without it LLVM can merge the string with a non unnamed_addr one during
3859 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003860 if (getTriple().isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003861 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3862 : "__TEXT,__cstring,cstring_literals");
Bill Wendling82b87f12012-03-30 00:26:17 +00003863
3864 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003865 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00003866 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00003867
Bill Wendling82b87f12012-03-30 00:26:17 +00003868 if (isUTF16)
3869 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003870 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3871 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00003872
Anders Carlssonb04ea612007-08-21 00:21:21 +00003873 // String length.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003874 auto Ty = getTypes().ConvertType(getContext().LongTy);
3875 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003876
John McCall7f416cc2015-09-08 08:05:57 +00003877 CharUnits Alignment = getPointerAlign();
3878
Anders Carlssonb04ea612007-08-21 00:21:21 +00003879 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003880 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3881 /*isConstant=*/false,
3882 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003883 switch (getTriple().getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003884 case llvm::Triple::UnknownObjectFormat:
3885 llvm_unreachable("unknown file format");
3886 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003887 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00003888 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00003889 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003890 break;
3891 case llvm::Triple::MachO:
3892 GV->setSection("__DATA,__cfstring");
3893 break;
3894 }
David Blaikie13156b62014-11-19 03:06:06 +00003895 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00003896
John McCall7f416cc2015-09-08 08:05:57 +00003897 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00003898}
Chris Lattnerfb300092007-11-28 05:34:05 +00003899
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00003900bool CodeGenModule::getExpressionLocationsEnabled() const {
3901 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
3902}
3903
Douglas Gregor636e2002011-08-09 17:23:49 +00003904QualType CodeGenModule::getObjCFastEnumerationStateType() {
3905 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00003906 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00003907 D->startDefinition();
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003908
Douglas Gregor636e2002011-08-09 17:23:49 +00003909 QualType FieldTypes[] = {
3910 Context.UnsignedLongTy,
3911 Context.getPointerType(Context.getObjCIdType()),
3912 Context.getPointerType(Context.UnsignedLongTy),
3913 Context.getConstantArrayType(Context.UnsignedLongTy,
3914 llvm::APInt(32, 5), ArrayType::Normal, 0)
3915 };
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003916
Douglas Gregor636e2002011-08-09 17:23:49 +00003917 for (size_t i = 0; i < 4; ++i) {
3918 FieldDecl *Field = FieldDecl::Create(Context,
3919 D,
3920 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003921 SourceLocation(), nullptr,
3922 FieldTypes[i], /*TInfo=*/nullptr,
3923 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00003924 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003925 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00003926 Field->setAccess(AS_public);
3927 D->addDecl(Field);
3928 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003929
Douglas Gregor636e2002011-08-09 17:23:49 +00003930 D->completeDefinition();
3931 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3932 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003933
Douglas Gregor636e2002011-08-09 17:23:49 +00003934 return ObjCFastEnumerationStateType;
3935}
3936
Eli Friedmanfcec6302011-11-01 02:23:42 +00003937llvm::Constant *
3938CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3939 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003940
Eli Friedmanfcec6302011-11-01 02:23:42 +00003941 // Don't emit it as the address of the string, emit the string data itself
3942 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00003943 if (E->getCharByteWidth() == 1) {
3944 SmallString<64> Str(E->getString());
3945
3946 // Resize the string to the right size, which is indicated by its type.
3947 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3948 Str.resize(CAT->getSize().getZExtValue());
3949 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3950 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003951
3952 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00003953 llvm::Type *ElemTy = AType->getElementType();
3954 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00003955
3956 // Wide strings have either 2-byte or 4-byte elements.
3957 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3958 SmallVector<uint16_t, 32> Elements;
3959 Elements.reserve(NumElements);
3960
3961 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3962 Elements.push_back(E->getCodeUnit(i));
3963 Elements.resize(NumElements);
3964 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00003965 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003966
Chris Lattner02cb1712012-02-06 22:52:04 +00003967 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3968 SmallVector<uint32_t, 32> Elements;
3969 Elements.reserve(NumElements);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003970
Chris Lattner02cb1712012-02-06 22:52:04 +00003971 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3972 Elements.push_back(E->getCodeUnit(i));
3973 Elements.resize(NumElements);
3974 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00003975}
3976
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003977static llvm::GlobalVariable *
3978GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3979 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00003980 CharUnits Alignment) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003981 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3982 unsigned AddrSpace = 0;
3983 if (CGM.getLangOpts().OpenCL)
3984 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3985
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003986 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003987 // Create a global variable for this string
3988 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003989 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3990 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00003991 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003992 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003993 if (GV->isWeakForLinker()) {
3994 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3995 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3996 }
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003997
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003998 return GV;
3999}
4000
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004001/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4002/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00004003ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00004004CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4005 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00004006 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00004007
Richard Smith00db2f12014-07-29 21:20:12 +00004008 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4009 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00004010 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004011 Entry = &ConstantStringMap[C];
4012 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004013 if (Alignment.getQuantity() > GV->getAlignment())
4014 GV->setAlignment(Alignment.getQuantity());
4015 return ConstantAddress(GV, Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00004016 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00004017 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00004018
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004019 SmallString<256> MangledNameBuffer;
4020 StringRef GlobalVariableName;
4021 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00004022
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004023 // Mangle the string literal if the ABI allows for it. However, we cannot
4024 // do this if we are compiling with ASan or -fwritable-strings because they
4025 // rely on strings having normal linkage.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004026 if (!LangOpts.WritableStrings &&
4027 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004028 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
4029 llvm::raw_svector_ostream Out(MangledNameBuffer);
4030 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
David Majnemer58e5bee2014-03-24 21:43:36 +00004031
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004032 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4033 GlobalVariableName = MangledNameBuffer;
4034 } else {
4035 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00004036 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00004037 }
4038
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004039 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4040 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004041 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00004042
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00004043 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4044 QualType());
John McCall7f416cc2015-09-08 08:05:57 +00004045 return ConstantAddress(GV, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004046}
4047
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004048/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4049/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00004050ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004051CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4052 std::string Str;
4053 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00004054
4055 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004056}
4057
Alexey Samsonovadc90372014-06-04 20:25:57 +00004058/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4059/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004060/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00004061ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4062 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00004063 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00004064 CharUnits Alignment =
4065 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004066
Richard Smith00db2f12014-07-29 21:20:12 +00004067 llvm::Constant *C =
4068 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4069
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004070 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00004071 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004072 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004073 Entry = &ConstantStringMap[C];
4074 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004075 if (Alignment.getQuantity() > GV->getAlignment())
4076 GV->setAlignment(Alignment.getQuantity());
4077 return ConstantAddress(GV, Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004078 }
4079 }
4080
Daniel Dunbar08b216a2009-03-31 23:42:16 +00004081 // Get the default prefix if a name wasn't specified.
4082 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00004083 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00004084 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004085 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4086 GlobalName, Alignment);
4087 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004088 *Entry = GV;
John McCall7f416cc2015-09-08 08:05:57 +00004089 return ConstantAddress(GV, Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00004090}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004091
John McCall7f416cc2015-09-08 08:05:57 +00004092ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00004093 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00004094 assert((E->getStorageDuration() == SD_Static ||
4095 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004096 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00004097
4098 // If we're not materializing a subobject of the temporary, keep the
4099 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00004100 QualType MaterializedType = Init->getType();
4101 if (Init == E->GetTemporaryExpr())
4102 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004103
John McCall7f416cc2015-09-08 08:05:57 +00004104 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4105
David Majnemer2dcef9e2015-08-13 23:50:15 +00004106 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00004107 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004108
4109 // FIXME: If an externally-visible declaration extends multiple temporaries,
4110 // we need to give each temporary the same name in every translation unit (and
4111 // we also need to make the temporaries externally-visible).
4112 SmallString<256> Name;
4113 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00004114 getCXXABI().getMangleContext().mangleReferenceTemporary(
4115 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00004116
Craig Topper8a13c412014-05-21 05:09:00 +00004117 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004118 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00004119 // We might have a cached constant initializer for this temporary. Note
4120 // that this might have a different value from the value computed by
4121 // evaluating the initializer if the surrounding constant expression
4122 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00004123 Value = getContext().getMaterializedTemporaryValue(E, false);
4124 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00004125 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004126 }
4127
Richard Smitha509f2f2013-06-14 03:07:01 +00004128 // Try evaluating it now, it might have a constant initializer.
4129 Expr::EvalResult EvalResult;
4130 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4131 !EvalResult.hasSideEffects())
4132 Value = &EvalResult.Val;
4133
Alexander Richardson6d989432017-10-15 18:48:14 +00004134 LangAS AddrSpace =
John McCallde0fe072017-08-15 21:42:52 +00004135 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4136
4137 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00004138 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00004139 bool Constant = false;
4140 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00004141 if (Value) {
4142 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00004143 emitter.emplace(*this);
4144 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4145 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00004146 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4147 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004148 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00004149 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00004150 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00004151 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00004152 }
4153
4154 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00004155 llvm::GlobalValue::LinkageTypes Linkage =
4156 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004157 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4158 const VarDecl *InitVD;
4159 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4160 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4161 // Temporaries defined inside a class get linkonce_odr linkage because the
4162 // class can be defined in multipe translation units.
4163 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4164 } else {
4165 // There is no need for this temporary to have external linkage if the
4166 // VarDecl has external linkage.
4167 Linkage = llvm::GlobalVariable::InternalLinkage;
4168 }
4169 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00004170 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004171 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00004172 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00004173 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00004174 if (emitter) emitter->finalize(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +00004175 setGVProperties(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00004176 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004177 if (supportsCOMDAT() && GV->isWeakForLinker())
4178 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00004179 if (VD->getTLSKind())
4180 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00004181 llvm::Constant *CV = GV;
4182 if (AddrSpace != LangAS::Default)
4183 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4184 *this, GV, AddrSpace, LangAS::Default,
4185 Type->getPointerTo(
4186 getContext().getTargetAddressSpace(LangAS::Default)));
4187 MaterializedGlobalTemporaryMap[E] = CV;
4188 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004189}
4190
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004191/// EmitObjCPropertyImplementations - Emit information for synthesized
4192/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00004193void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004194 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004195 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004196 // Dynamic is just for type-checking.
4197 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4198 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4199
4200 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00004201 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004202 // we want, that just indicates if the decl came from a
4203 // property. What we want to know is if the method is defined in
4204 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004205 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004206 CodeGenFunction(*this).GenerateObjCGetter(
4207 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004208 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004209 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004210 CodeGenFunction(*this).GenerateObjCSetter(
4211 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004212 }
4213 }
4214}
4215
John McCall6a4fa522011-03-22 07:05:39 +00004216static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004217 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4218 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00004219 ivar; ivar = ivar->getNextIvar())
4220 if (ivar->getType().isDestructedType())
4221 return true;
4222
4223 return false;
4224}
4225
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004226static bool AllTrivialInitializers(CodeGenModule &CGM,
4227 ObjCImplementationDecl *D) {
4228 CodeGenFunction CGF(CGM);
4229 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4230 E = D->init_end(); B != E; ++B) {
4231 CXXCtorInitializer *CtorInitExp = *B;
4232 Expr *Init = CtorInitExp->getInit();
4233 if (!CGF.isTrivialInitializer(Init))
4234 return false;
4235 }
4236 return true;
4237}
4238
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004239/// EmitObjCIvarInitializations - Emit information for ivar initialization
4240/// for an implementation.
4241void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00004242 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4243 if (needsDestructMethod(D)) {
4244 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4245 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4246 ObjCMethodDecl *DTORMethod =
4247 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004248 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004249 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004250 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004251 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00004252 D->addInstanceMethod(DTORMethod);
4253 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00004254 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00004255 }
4256
4257 // If the implementation doesn't have any ivar initializers, we don't need
4258 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004259 if (D->getNumIvarInitializers() == 0 ||
4260 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004261 return;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004262
John McCall6a4fa522011-03-22 07:05:39 +00004263 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4264 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004265 // The constructor returns 'self'.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004266 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004267 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004268 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004269 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00004270 getContext().getObjCIdType(),
4271 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004272 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004273 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004274 /*isImplicitlyDeclared=*/true,
4275 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004276 ObjCMethodDecl::Required);
4277 D->addInstanceMethod(CTORMethod);
4278 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00004279 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004280}
4281
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004282// EmitLinkageSpec - Emit all declarations in a linkage spec.
4283void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00004284 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4285 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004286 ErrorUnsupported(LSD, "linkage spec");
4287 return;
4288 }
4289
Richard Smith8df390f2016-09-08 23:14:54 +00004290 EmitDeclContext(LSD);
4291}
4292
4293void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4294 for (auto *I : DC->decls()) {
4295 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4296 // are themselves considered "top-level", so EmitTopLevelDecl on an
4297 // ObjCImplDecl does not recursively visit them. We need to do that in
4298 // case they're nested inside another construct (LinkageSpecDecl /
4299 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00004300 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004301 for (auto *M : OID->methods())
4302 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004303 }
Richard Smith8df390f2016-09-08 23:14:54 +00004304
Aaron Ballman629afae2014-03-07 19:56:05 +00004305 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004306 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004307}
4308
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004309/// EmitTopLevelDecl - Emit code for a single top level declaration.
4310void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00004311 // Ignore dependent declarations.
Richard Smith32b615c2018-02-01 00:28:36 +00004312 if (D->isTemplated())
Douglas Gregor70d83e22009-06-29 17:30:29 +00004313 return;
Mike Stump11289f42009-09-09 15:08:12 +00004314
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004315 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00004316 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00004317 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004318 case Decl::Function:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004319 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00004320 // Always provide some coverage mapping
4321 // even for the functions that aren't emitted.
4322 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004323 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004324
Richard Smithada08882017-04-19 21:15:45 +00004325 case Decl::CXXDeductionGuide:
4326 // Function-like, but does not result in code emission.
4327 break;
4328
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004329 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00004330 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004331 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004332 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00004333 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4334 for (auto *B : DD->bindings())
4335 if (auto *HD = B->getHoldingVar())
4336 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004337 break;
4338
John McCall32f44bd2011-04-12 01:01:22 +00004339 // Indirect fields from global anonymous structs and unions can be
4340 // ignored; only the actual variable requires IR gen support.
4341 case Decl::IndirectField:
4342 break;
4343
Anders Carlssonf7475242009-04-15 15:55:24 +00004344 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004345 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00004346 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004347 break;
Richard Smithe1246122017-11-03 01:26:01 +00004348 case Decl::ClassTemplateSpecialization: {
4349 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4350 if (DebugInfo &&
4351 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4352 Spec->hasDefinition())
4353 DebugInfo->completeTemplateDefinition(*Spec);
4354 } LLVM_FALLTHROUGH;
Richard Smith62f19e72016-06-25 00:15:56 +00004355 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00004356 if (DebugInfo) {
4357 if (auto *ES = D->getASTContext().getExternalSource())
4358 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4359 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4360 }
Richard Smith62f19e72016-06-25 00:15:56 +00004361 // Emit any static data members, they may be definitions.
4362 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4363 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4364 EmitTopLevelDecl(I);
4365 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00004366 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00004367 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004368 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004369 case Decl::VarTemplate:
4370 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004371 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00004372 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00004373 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00004374 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00004375 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00004376 case Decl::Using: // using X; [C++]
4377 if (CGDebugInfo *DI = getModuleDebugInfo())
4378 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4379 return;
David Blaikief121b932013-05-20 22:50:41 +00004380 case Decl::NamespaceAlias:
4381 if (CGDebugInfo *DI = getModuleDebugInfo())
4382 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4383 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00004384 case Decl::UsingDirective: // using namespace X; [C++]
4385 if (CGDebugInfo *DI = getModuleDebugInfo())
4386 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4387 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00004388 case Decl::CXXConstructor:
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00004389 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00004390 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004391 case Decl::CXXDestructor:
Reid Klecknere7de47e2013-07-22 13:51:44 +00004392 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004393 break;
Anders Carlsson87835432009-06-11 21:22:55 +00004394
4395 case Decl::StaticAssert:
4396 // Nothing to do.
4397 break;
4398
Anders Carlssonf7475242009-04-15 15:55:24 +00004399 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00004400
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004401 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00004402 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00004403 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00004404 break;
4405
Douglas Gregorf6102672012-01-01 21:23:57 +00004406 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004407 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00004408 if (Proto->isThisDeclarationADefinition())
4409 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004410 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00004411 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004412
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004413 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004414 // Categories have properties but don't support synthesize so we
4415 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00004416 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004417 break;
4418
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004419 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004420 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004421 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004422 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00004423 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00004424 // Emit global variable debug information.
4425 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00004426 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00004427 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4428 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004429 break;
Mike Stump11289f42009-09-09 15:08:12 +00004430 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004431 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004432 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004433 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004434 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004435 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4436 break;
4437 }
Mike Stump11289f42009-09-09 15:08:12 +00004438 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00004439 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004440 break;
4441
Nico Weber66220292016-03-02 17:28:48 +00004442 case Decl::PragmaComment: {
4443 const auto *PCD = cast<PragmaCommentDecl>(D);
4444 switch (PCD->getCommentKind()) {
4445 case PCK_Unknown:
4446 llvm_unreachable("unexpected pragma comment kind");
4447 case PCK_Linker:
4448 AppendLinkerOptions(PCD->getArg());
4449 break;
4450 case PCK_Lib:
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00004451 if (getTarget().getTriple().isOSBinFormatELF() &&
4452 !getTarget().getTriple().isPS4())
4453 AddELFLibDirective(PCD->getArg());
4454 else
4455 AddDependentLib(PCD->getArg());
Nico Weber66220292016-03-02 17:28:48 +00004456 break;
4457 case PCK_Compiler:
4458 case PCK_ExeStr:
4459 case PCK_User:
4460 break; // We ignore all of these.
4461 }
4462 break;
4463 }
4464
Nico Webercbbaeb12016-03-02 19:28:54 +00004465 case Decl::PragmaDetectMismatch: {
4466 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4467 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4468 break;
4469 }
4470
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004471 case Decl::LinkageSpec:
4472 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004473 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004474
4475 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00004476 // File-scope asm is ignored during device-side CUDA compilation.
4477 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4478 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004479 // File-scope asm is ignored during device-side OpenMP compilation.
4480 if (LangOpts.OpenMPIsDevice)
4481 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004482 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00004483 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004484 break;
4485 }
Mike Stump11289f42009-09-09 15:08:12 +00004486
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004487 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004488 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004489
Richard Smithdc1f0422016-07-20 19:10:16 +00004490 // If we've already imported this module, we're done.
4491 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00004492 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004493
Richard Smithdc1f0422016-07-20 19:10:16 +00004494 // Emit debug information for direct imports.
4495 if (!Import->getImportedOwningModule()) {
4496 if (CGDebugInfo *DI = getModuleDebugInfo())
4497 DI->EmitImportDecl(*Import);
4498 }
4499
Manman Ren3b5dbf22016-10-14 18:55:44 +00004500 // Find all of the submodules and emit the module initializers.
4501 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4502 SmallVector<clang::Module *, 16> Stack;
4503 Visited.insert(Import->getImportedModule());
4504 Stack.push_back(Import->getImportedModule());
4505
4506 while (!Stack.empty()) {
4507 clang::Module *Mod = Stack.pop_back_val();
4508 if (!EmittedModuleInitializers.insert(Mod).second)
4509 continue;
4510
4511 for (auto *D : Context.getModuleInitializers(Mod))
4512 EmitTopLevelDecl(D);
4513
4514 // Visit the submodules of this module.
4515 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4516 SubEnd = Mod->submodule_end();
4517 Sub != SubEnd; ++Sub) {
4518 // Skip explicit children; they need to be explicitly imported to emit
4519 // the initializers.
4520 if ((*Sub)->IsExplicit)
4521 continue;
4522
4523 if (Visited.insert(*Sub).second)
4524 Stack.push_back(*Sub);
4525 }
4526 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004527 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004528 }
4529
Richard Smith8df390f2016-09-08 23:14:54 +00004530 case Decl::Export:
4531 EmitDeclContext(cast<ExportDecl>(D));
4532 break;
4533
Alexey Bataev97720002014-11-11 04:05:39 +00004534 case Decl::OMPThreadPrivate:
4535 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4536 break;
4537
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004538 case Decl::OMPDeclareReduction:
4539 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4540 break;
4541
Mike Stump11289f42009-09-09 15:08:12 +00004542 default:
Mike Stump18bb9282009-05-16 07:57:57 +00004543 // Make sure we handled everything we should, every other kind is a
4544 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4545 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004546 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00004547 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004548 }
4549}
John McCall09ae0322010-07-06 23:57:41 +00004550
Alex Lorenzee024992014-08-04 18:41:51 +00004551void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4552 // Do we need to generate coverage mapping?
4553 if (!CodeGenOpts.CoverageMapping)
4554 return;
4555 switch (D->getKind()) {
4556 case Decl::CXXConversion:
4557 case Decl::CXXMethod:
4558 case Decl::Function:
4559 case Decl::ObjCMethod:
4560 case Decl::CXXConstructor:
4561 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00004562 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00004563 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00004564 SourceManager &SM = getContext().getSourceManager();
4565 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4566 return;
Alex Lorenzee024992014-08-04 18:41:51 +00004567 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4568 if (I == DeferredEmptyCoverageMappingDecls.end())
4569 DeferredEmptyCoverageMappingDecls[D] = true;
4570 break;
4571 }
4572 default:
4573 break;
4574 };
4575}
4576
4577void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4578 // Do we need to generate coverage mapping?
4579 if (!CodeGenOpts.CoverageMapping)
4580 return;
4581 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4582 if (Fn->isTemplateInstantiation())
4583 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4584 }
4585 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4586 if (I == DeferredEmptyCoverageMappingDecls.end())
4587 DeferredEmptyCoverageMappingDecls[D] = false;
4588 else
4589 I->second = false;
4590}
4591
4592void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Eli Friedman8516b7f2017-12-19 01:54:09 +00004593 // We call takeVector() here to avoid use-after-free.
4594 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4595 // we deserialize function bodies to emit coverage info for them, and that
4596 // deserializes more declarations. How should we handle that case?
4597 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
Eli Friedmandbcfade2017-12-13 00:14:17 +00004598 if (!Entry.second)
Alex Lorenzee024992014-08-04 18:41:51 +00004599 continue;
Eli Friedmandbcfade2017-12-13 00:14:17 +00004600 const Decl *D = Entry.first;
Alex Lorenzee024992014-08-04 18:41:51 +00004601 switch (D->getKind()) {
4602 case Decl::CXXConversion:
4603 case Decl::CXXMethod:
4604 case Decl::Function:
4605 case Decl::ObjCMethod: {
4606 CodeGenPGO PGO(*this);
4607 GlobalDecl GD(cast<FunctionDecl>(D));
4608 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4609 getFunctionLinkage(GD));
4610 break;
4611 }
4612 case Decl::CXXConstructor: {
4613 CodeGenPGO PGO(*this);
4614 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4615 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4616 getFunctionLinkage(GD));
4617 break;
4618 }
4619 case Decl::CXXDestructor: {
4620 CodeGenPGO PGO(*this);
4621 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4622 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4623 getFunctionLinkage(GD));
4624 break;
4625 }
4626 default:
4627 break;
4628 };
4629 }
4630}
4631
John McCall09ae0322010-07-06 23:57:41 +00004632/// Turns the given pointer into a constant.
4633static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4634 const void *Ptr) {
4635 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00004636 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00004637 return llvm::ConstantInt::get(i64, PtrInt);
4638}
4639
4640static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4641 llvm::NamedMDNode *&GlobalMetadata,
4642 GlobalDecl D,
4643 llvm::GlobalValue *Addr) {
4644 if (!GlobalMetadata)
4645 GlobalMetadata =
4646 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4647
4648 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004649 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4650 llvm::ConstantAsMetadata::get(GetPointerConstant(
4651 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00004652 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00004653}
4654
Richard Smithdf931ce2013-04-06 05:00:46 +00004655/// For each function which is declared within an extern "C" region and marked
4656/// as 'used', but has internal linkage, create an alias from the unmangled
4657/// name to the mangled name if possible. People expect to be able to refer
4658/// to such functions with an unmangled name from inline assembly within the
4659/// same translation unit.
4660void CodeGenModule::EmitStaticExternCAliases() {
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00004661 // Don't do anything if we're generating CUDA device code -- the NVPTX
4662 // assembly target doesn't support aliases.
4663 if (Context.getTargetInfo().getTriple().isNVPTX())
4664 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00004665 for (auto &I : StaticExternCValues) {
4666 IdentifierInfo *Name = I.first;
4667 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00004668 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00004669 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00004670 }
Richard Smithdf931ce2013-04-06 05:00:46 +00004671}
4672
Alp Tokerfb8d02b2014-06-05 22:10:59 +00004673bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4674 GlobalDecl &Result) const {
4675 auto Res = Manglings.find(MangledName);
4676 if (Res == Manglings.end())
4677 return false;
4678 Result = Res->getValue();
4679 return true;
4680}
4681
John McCall09ae0322010-07-06 23:57:41 +00004682/// Emits metadata nodes associating all the global values in the
4683/// current module with the Decls they came from. This is useful for
4684/// projects using IR gen as a subroutine.
4685///
4686/// Since there's currently no way to associate an MDNode directly
4687/// with an llvm::GlobalValue, we create a global named metadata
4688/// with the name 'clang.global.decl.ptrs'.
4689void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00004690 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004691
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004692 for (auto &I : MangledDeclNames) {
4693 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00004694 // Some mangled names don't necessarily have an associated GlobalValue
4695 // in this module, e.g. if we mangled it for DebugInfo.
4696 if (Addr)
4697 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00004698 }
4699}
4700
4701/// Emits metadata nodes for all the local variables in the current
4702/// function.
4703void CodeGenFunction::EmitDeclMetadata() {
4704 if (LocalDeclMap.empty()) return;
4705
4706 llvm::LLVMContext &Context = getLLVMContext();
4707
4708 // Find the unique metadata ID for this name.
4709 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4710
Craig Topper8a13c412014-05-21 05:09:00 +00004711 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004712
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004713 for (auto &I : LocalDeclMap) {
4714 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00004715 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004716 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004717 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004718 Alloca->setMetadata(
4719 DeclPtrKind, llvm::MDNode::get(
4720 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004721 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004722 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4723 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4724 }
4725 }
4726}
Daniel Dunbar900546d2010-07-16 00:00:15 +00004727
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004728void CodeGenModule::EmitVersionIdentMetadata() {
4729 llvm::NamedMDNode *IdentMetadata =
4730 TheModule.getOrInsertNamedMetadata("llvm.ident");
4731 std::string Version = getClangFullVersion();
4732 llvm::LLVMContext &Ctx = TheModule.getContext();
4733
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004734 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004735 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4736}
4737
Robert Lytton57765d52014-07-03 09:30:33 +00004738void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00004739 // Warning, new MangledDeclNames may be appended within this loop.
4740 // We rely on MapVector insertions adding new elements to the end
4741 // of the container.
4742 // FIXME: Move this loop into the one target that needs it, and only
4743 // loop over those declarations for which we couldn't emit the target
4744 // metadata when we emitted the declaration.
4745 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00004746 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00004747 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4748 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00004749 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4750 }
4751}
4752
Nick Lewycky85c011d2011-05-05 00:08:20 +00004753void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00004754 if (getCodeGenOpts().CoverageDataFile.empty() &&
4755 getCodeGenOpts().CoverageNotesFile.empty())
4756 return;
4757
4758 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4759 if (!CUNode)
4760 return;
4761
4762 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4763 llvm::LLVMContext &Ctx = TheModule.getContext();
4764 auto *CoverageDataFile =
4765 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4766 auto *CoverageNotesFile =
4767 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4768 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4769 llvm::MDNode *CU = CUNode->getOperand(i);
4770 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4771 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00004772 }
4773}
Nico Webercf4ff5862012-10-11 10:13:44 +00004774
Nico Weber17d3a2c2014-09-08 16:26:36 +00004775llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00004776 // Sema has checked that all uuid strings are of the form
4777 // "12345678-1234-1234-1234-1234567890ab".
4778 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00004779 for (unsigned i = 0; i < 36; ++i) {
4780 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4781 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00004782 }
Nico Webercf4ff5862012-10-11 10:13:44 +00004783
Nico Weberdfa274e2014-09-08 16:11:15 +00004784 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00004785 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00004786
David Majnemerbbecd092013-08-15 19:59:14 +00004787 llvm::Constant *Field3[8];
4788 for (unsigned Idx = 0; Idx < 8; ++Idx)
4789 Field3[Idx] = llvm::ConstantInt::get(
4790 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4791
4792 llvm::Constant *Fields[4] = {
4793 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4794 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4795 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4796 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4797 };
4798
4799 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00004800}
David Majnemere2cb8d12014-07-07 06:20:47 +00004801
4802llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4803 bool ForEH) {
4804 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4805 // FIXME: should we even be calling this method if RTTI is disabled
4806 // and it's not for EH?
4807 if (!ForEH && !getLangOpts().RTTI)
4808 return llvm::Constant::getNullValue(Int8PtrTy);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004809
David Majnemere2cb8d12014-07-07 06:20:47 +00004810 if (ForEH && Ty->isObjCObjectPointerType() &&
4811 LangOpts.ObjCRuntime.isGNUFamily())
4812 return ObjCRuntime->GetEHType(Ty);
4813
David Majnemer443250f2015-03-17 20:35:00 +00004814 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00004815}
4816
Alexey Bataev97720002014-11-11 04:05:39 +00004817void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00004818 // Do not emit threadprivates in simd-only mode.
4819 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
4820 return;
Alexey Bataev97720002014-11-11 04:05:39 +00004821 for (auto RefExpr : D->varlists()) {
4822 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4823 bool PerformInit =
4824 VD->getAnyInitializer() &&
4825 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4826 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00004827
4828 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00004829 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00004830 VD, Addr, RefExpr->getLocStart(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00004831 CXXGlobalInits.push_back(InitFunction);
4832 }
4833}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00004834
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00004835llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4836 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4837 if (InternalId)
4838 return InternalId;
4839
4840 if (isExternallyVisible(T->getLinkage())) {
4841 std::string OutName;
4842 llvm::raw_string_ostream Out(OutName);
4843 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4844
4845 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4846 } else {
4847 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4848 llvm::ArrayRef<llvm::Metadata *>());
4849 }
4850
4851 return InternalId;
4852}
4853
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00004854// Generalize pointer types to a void pointer with the qualifiers of the
4855// originally pointed-to type, e.g. 'const char *' and 'char * const *'
4856// generalize to 'const void *' while 'char *' and 'const char **' generalize to
4857// 'void *'.
4858static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
4859 if (!Ty->isPointerType())
4860 return Ty;
4861
4862 return Ctx.getPointerType(
4863 QualType(Ctx.VoidTy).withCVRQualifiers(
4864 Ty->getPointeeType().getCVRQualifiers()));
4865}
4866
4867// Apply type generalization to a FunctionType's return and argument types
4868static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
4869 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
4870 SmallVector<QualType, 8> GeneralizedParams;
4871 for (auto &Param : FnType->param_types())
4872 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
4873
4874 return Ctx.getFunctionType(
4875 GeneralizeType(Ctx, FnType->getReturnType()),
4876 GeneralizedParams, FnType->getExtProtoInfo());
4877 }
4878
4879 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
4880 return Ctx.getFunctionNoProtoType(
4881 GeneralizeType(Ctx, FnType->getReturnType()));
4882
4883 llvm_unreachable("Encountered unknown FunctionType");
4884}
4885
4886llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
4887 T = GeneralizeFunctionType(getContext(), T);
4888
4889 llvm::Metadata *&InternalId = GeneralizedMetadataIdMap[T.getCanonicalType()];
4890 if (InternalId)
4891 return InternalId;
4892
4893 if (isExternallyVisible(T->getLinkage())) {
4894 std::string OutName;
4895 llvm::raw_string_ostream Out(OutName);
4896 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4897 Out << ".generalized";
4898
4899 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4900 } else {
4901 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4902 llvm::ArrayRef<llvm::Metadata *>());
4903 }
4904
4905 return InternalId;
4906}
4907
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004908/// Returns whether this module needs the "all-vtables" type identifier.
4909bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004910 // Returns true if at least one of vtable-based CFI checkers is enabled and
4911 // is not in the trapping mode.
4912 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4913 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4914 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4915 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4916 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4917 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4918 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4919 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4920}
4921
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004922void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4923 CharUnits Offset,
4924 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004925 llvm::Metadata *MD =
4926 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004927 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004928
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004929 if (CodeGenOpts.SanitizeCfiCrossDso)
4930 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4931 VTable->addTypeMetadata(Offset.getQuantity(),
4932 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004933
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004934 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004935 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004936 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004937 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00004938}
Eric Christopher2b90a642015-11-11 23:05:08 +00004939
4940// Fills in the supplied string map with the set of target features for the
4941// passed in function.
4942void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4943 const FunctionDecl *FD) {
4944 StringRef TargetCPU = Target.getTargetOpts().CPU;
4945 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4946 // If we have a TargetAttr build up the feature map based on that.
4947 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4948
Erich Keanecf8807c2017-10-27 18:32:23 +00004949 ParsedAttr.Features.erase(
4950 llvm::remove_if(ParsedAttr.Features,
4951 [&](const std::string &Feat) {
4952 return !Target.isValidFeatureName(
4953 StringRef{Feat}.substr(1));
4954 }),
4955 ParsedAttr.Features.end());
4956
Eric Christopher2b90a642015-11-11 23:05:08 +00004957 // Make a copy of the features as passed on the command line into the
4958 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00004959 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00004960 Target.getTargetOpts().FeaturesAsWritten.begin(),
4961 Target.getTargetOpts().FeaturesAsWritten.end());
4962
Erich Keanecf8807c2017-10-27 18:32:23 +00004963 if (ParsedAttr.Architecture != "" &&
4964 Target.isValidCPUName(ParsedAttr.Architecture))
4965 TargetCPU = ParsedAttr.Architecture;
Eric Christopher2b90a642015-11-11 23:05:08 +00004966
4967 // Now populate the feature map, first with the TargetCPU which is either
4968 // the default or a new one from the target attribute string. Then we'll use
4969 // the passed in features (FeaturesAsWritten) along with the new ones from
4970 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00004971 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4972 ParsedAttr.Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00004973 } else {
4974 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4975 Target.getTargetOpts().Features);
4976 }
4977}
Peter Collingbournedc134532016-01-16 00:31:22 +00004978
4979llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4980 if (!SanStats)
4981 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4982
4983 return *SanStats;
4984}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00004985llvm::Value *
4986CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4987 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00004988 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00004989 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00004990 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4991 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4992 "__translate_sampler_initializer"),
4993 {C});
4994}