blob: c2fb4797ccdd18e22e388259d48cc314504f5334 [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"
Caroline Tice62279732018-09-21 18:34:59 +000047#include "llvm/ADT/StringSwitch.h"
John McCallbeec5a02010-03-06 00:35:14 +000048#include "llvm/ADT/Triple.h"
Matthias Brauna4519532017-05-20 01:29:55 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000050#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000051#include "llvm/IR/CallingConv.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/Intrinsics.h"
54#include "llvm/IR/LLVMContext.h"
55#include "llvm/IR/Module.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000056#include "llvm/ProfileData/InstrProfReader.h"
Caroline Tice62279732018-09-21 18:34:59 +000057#include "llvm/Support/CodeGen.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000058#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000059#include "llvm/Support/ErrorHandling.h"
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +000060#include "llvm/Support/MD5.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000061
Chris Lattnerbed31442007-05-28 01:07:47 +000062using namespace clang;
63using namespace CodeGen;
64
Vedant Kumar0acf3432017-09-22 18:23:04 +000065static llvm::cl::opt<bool> LimitedCoverage(
Zachary Turner8065f0b2017-12-01 00:53:10 +000066 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
Vedant Kumar0acf3432017-09-22 18:23:04 +000067 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
68 llvm::cl::init(false));
69
Julien Lerouge5a6b6982011-09-09 22:41:49 +000070static const char AnnotationSection[] = "llvm.metadata";
71
Alp Toker82862252013-12-28 21:58:40 +000072static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000073 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000074 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000075 case TargetCXXABI::GenericARM:
76 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000077 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +000078 case TargetCXXABI::WatchOS:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000079 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000080 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +000081 case TargetCXXABI::WebAssembly:
Alp Toker82862252013-12-28 21:58:40 +000082 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000083 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000084 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000085 }
86
87 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000088}
89
Adrian Prantle74f5252015-06-30 02:26:03 +000090CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
91 const PreprocessorOptions &PPO,
92 const CodeGenOptions &CGO, llvm::Module &M,
Alex Lorenzee024992014-08-04 18:41:51 +000093 DiagnosticsEngine &diags,
94 CoverageSourceInfo *CoverageInfo)
Adrian Prantle74f5252015-06-30 02:26:03 +000095 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
96 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Mehdi Aminica3cf9e2015-07-24 16:04:29 +000097 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Reid Kleckner9305fd12016-04-13 23:37:17 +000098 VMContext(M.getContext()), Types(*this), VTables(*this),
Peter Collingbourne3afb2662016-04-28 17:09:37 +000099 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +0000100
Chris Lattnerece04092012-02-07 00:39:47 +0000101 // Initialize the type cache.
102 llvm::LLVMContext &LLVMContext = M.getContext();
103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
106 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
107 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
Abderrazek Zaafranif58a1322017-12-21 19:20:01 +0000108 HalfTy = llvm::Type::getHalfTy(LLVMContext);
Chris Lattnerece04092012-02-07 00:39:47 +0000109 FloatTy = llvm::Type::getFloatTy(LLVMContext);
110 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
111 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
112 PointerAlignInBytes =
John McCall7f416cc2015-09-08 08:05:57 +0000113 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
Yaxun Liu26f75662016-08-19 05:17:25 +0000114 SizeSizeInBytes =
115 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +0000116 IntAlignInBytes =
117 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
Chris Lattnerece04092012-02-07 00:39:47 +0000118 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
Yaxun Liu26f75662016-08-19 05:17:25 +0000119 IntPtrTy = llvm::IntegerType::get(LLVMContext,
120 C.getTargetInfo().getMaxPointerWidth());
Chris Lattnerece04092012-02-07 00:39:47 +0000121 Int8PtrTy = Int8Ty->getPointerTo(0);
122 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000123 AllocaInt8PtrTy = Int8Ty->getPointerTo(
124 M.getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000125 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
Chris Lattnerece04092012-02-07 00:39:47 +0000126
John McCall882987f2013-02-28 19:01:20 +0000127 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
128
David Blaikiebbafb8a2012-03-11 07:00:24 +0000129 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000130 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000131 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000132 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000133 if (LangOpts.OpenMP)
134 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000135 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000136 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000137
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000138 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000139 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000140 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000141 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
Reid Kleckner9305fd12016-04-13 23:37:17 +0000142 getCXXABI().getMangleContext()));
Dan Gohman947c9af2010-10-14 23:06:10 +0000143
Nick Lewycky207bce32011-04-21 23:44:07 +0000144 // If debug info or coverage generation is enabled, create the CGDebugInfo
145 // object.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000146 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
147 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000148 DebugInfo.reset(new CGDebugInfo(*this));
John McCallad7c5c12011-02-08 08:22:06 +0000149
150 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000151
John McCallb04ecb72015-10-21 18:06:43 +0000152 if (C.getLangOpts().ObjC1)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000153 ObjCData.reset(new ObjCEntrypoints());
Justin Bogneref512b92014-01-06 22:27:43 +0000154
Rong Xu9c6f1532016-03-02 20:59:36 +0000155 if (CodeGenOpts.hasProfileClangUse()) {
156 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
157 CodeGenOpts.ProfileInstrumentUsePath);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000158 if (auto E = ReaderOrErr.takeError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000159 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Diego Novillo5aecacb2015-06-25 22:56:00 +0000160 "Could not read profile %0: %1");
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000161 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
162 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
163 << EI.message();
164 });
Nico Weber176efac2015-04-06 04:16:48 +0000165 } else
166 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000167 }
Alex Lorenzee024992014-08-04 18:41:51 +0000168
169 // If coverage mapping generation is enabled, create the
170 // CoverageMappingModuleGen object.
171 if (CodeGenOpts.CoverageMapping)
172 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000173}
174
Reid Kleckner9305fd12016-04-13 23:37:17 +0000175CodeGenModule::~CodeGenModule() {}
Ted Kremenek2c674f62008-08-05 18:50:11 +0000176
David Chisnall481e3a82010-01-23 02:40:42 +0000177void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000178 // This is just isGNUFamily(), but we want to force implementors of
179 // new ABIs to decide how best to do this.
180 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000181 case ObjCRuntime::GNUstep:
182 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000183 case ObjCRuntime::ObjFW:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000184 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000185 return;
186
187 case ObjCRuntime::FragileMacOSX:
188 case ObjCRuntime::MacOSX:
189 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000190 case ObjCRuntime::WatchOS:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000191 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000192 return;
193 }
194 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000195}
196
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000197void CodeGenModule::createOpenCLRuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000198 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000199}
200
Alexey Bataev9959db52014-05-06 10:08:46 +0000201void CodeGenModule::createOpenMPRuntime() {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000202 // Select a specialized code generation class based on the target, if any.
203 // If it does not exist use the default implementation.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000204 switch (getTriple().getArch()) {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000205 case llvm::Triple::nvptx:
206 case llvm::Triple::nvptx64:
207 assert(getLangOpts().OpenMPIsDevice &&
208 "OpenMP NVPTX is only prepared to deal with device code.");
Reid Kleckner9305fd12016-04-13 23:37:17 +0000209 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000210 break;
211 default:
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000212 if (LangOpts.OpenMPSimd)
213 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
214 else
215 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000216 break;
217 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000218}
219
Peter Collingbournefe883422011-10-06 18:29:37 +0000220void CodeGenModule::createCUDARuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000221 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbournefe883422011-10-06 18:29:37 +0000222}
223
Rafael Espindola1e4df922014-09-16 15:18:21 +0000224void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
225 Replacements[Name] = C;
226}
227
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000228void CodeGenModule::applyReplacements() {
Yaron Kerenb54db522015-06-11 12:33:25 +0000229 for (auto &I : Replacements) {
230 StringRef MangledName = I.first();
231 llvm::Constant *Replacement = I.second;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000232 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
233 if (!Entry)
234 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000235 auto *OldF = cast<llvm::Function>(Entry);
236 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000237 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000238 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000239 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000240 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000241 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000242 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
243 CE->getOpcode() == llvm::Instruction::GetElementPtr);
244 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
245 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000246 }
247
248 // Replace old with new, but keep the old order.
249 OldF->replaceAllUsesWith(Replacement);
250 if (NewF) {
251 NewF->removeFromParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000252 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
253 NewF);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000254 }
255 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000256 }
257}
258
Andrey Bokhankocab58582015-08-31 13:20:44 +0000259void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
260 GlobalValReplacements.push_back(std::make_pair(GV, C));
261}
262
263void CodeGenModule::applyGlobalValReplacements() {
264 for (auto &I : GlobalValReplacements) {
265 llvm::GlobalValue *GV = I.first;
266 llvm::Constant *C = I.second;
267
268 GV->replaceAllUsesWith(C);
269 GV->eraseFromParent();
270 }
271}
272
Rafael Espindola27c60b52014-06-03 02:42:01 +0000273// This is only used in aliases that we created and we know they have a
274// linear structure.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000275static const llvm::GlobalObject *getAliasedGlobal(
276 const llvm::GlobalIndirectSymbol &GIS) {
277 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
278 const llvm::Constant *C = &GIS;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000279 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000280 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000281 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
282 return GO;
283 // stripPointerCasts will not walk over weak aliases.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000284 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
285 if (!GIS2)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000286 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000287 if (!Visited.insert(GIS2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000288 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000289 C = GIS2->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000290 }
291}
292
Rafael Espindola208b5c02013-10-22 19:26:13 +0000293void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000294 // Check if the constructed aliases are well formed. It is really unfortunate
295 // that we have to do this in CodeGen, but we only construct mangled names
296 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000297 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000298 DiagnosticsEngine &Diags = getDiags();
Yaron Kerenb54db522015-06-11 12:33:25 +0000299 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000300 const auto *D = cast<ValueDecl>(GD.getDecl());
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000301 SourceLocation Location;
302 bool IsIFunc = D->hasAttr<IFuncAttr>();
303 if (const Attr *A = D->getDefiningAttr())
304 Location = A->getLocation();
305 else
306 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindola208b5c02013-10-22 19:26:13 +0000307 StringRef MangledName = getMangledName(GD);
308 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000309 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000310 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
311 if (!GV) {
312 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000313 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000314 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000315 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000316 Diags.Report(Location, diag::err_alias_to_undefined)
317 << IsIFunc << IsIFunc;
318 } else if (IsIFunc) {
319 // Check resolver function type.
320 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
321 GV->getType()->getPointerElementType());
322 assert(FTy);
323 if (!FTy->getReturnType()->isPointerTy())
324 Diags.Report(Location, diag::err_ifunc_resolver_return);
325 if (FTy->getNumParams())
326 Diags.Report(Location, diag::err_ifunc_resolver_params);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000327 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000328
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000329 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000330 llvm::GlobalValue *AliaseeGV;
331 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
332 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
333 else
334 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
335
Rafael Espindola502f65a2014-05-05 20:21:03 +0000336 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
337 StringRef AliasSection = SA->getName();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000338 if (AliasSection != AliaseeGV->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000339 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000340 << AliasSection << IsIFunc << IsIFunc;
Rafael Espindola502f65a2014-05-05 20:21:03 +0000341 }
Rafael Espindola27c60b52014-06-03 02:42:01 +0000342
343 // We have to handle alias to weak aliases in here. LLVM itself disallows
344 // this since the object semantics would not match the IL one. For
345 // compatibility with gcc we implement it by just pointing the alias
346 // to its aliasee's aliasee. We also warn, since the user is probably
347 // expecting the link to be weak.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000348 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
Sanjoy Dasf60a0d72016-04-08 01:31:02 +0000349 if (GA->isInterposable()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000350 Diags.Report(Location, diag::warn_alias_to_weak_alias)
351 << GV->getName() << GA->getName() << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000352 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000353 GA->getIndirectSymbol(), Alias->getType());
354 Alias->setIndirectSymbol(Aliasee);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000355 }
356 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000357 }
358 if (!Error)
359 return;
360
Yaron Kerenb54db522015-06-11 12:33:25 +0000361 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000362 StringRef MangledName = getMangledName(GD);
363 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000364 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000365 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
366 Alias->eraseFromParent();
367 }
368}
369
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000370void CodeGenModule::clear() {
371 DeferredDeclsToEmit.clear();
Alexey Bataev91797552015-03-18 04:13:55 +0000372 if (OpenMPRuntime)
373 OpenMPRuntime->clear();
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000374}
375
Justin Bogner40b8ba12014-06-26 01:45:07 +0000376void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
377 StringRef MainFile) {
378 if (!hasDiagnostics())
379 return;
380 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
381 if (MainFile.empty())
382 MainFile = "<stdin>";
383 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
Vedant Kumar96d6ca72017-04-27 17:30:58 +0000384 } else {
385 if (Mismatched > 0)
386 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
387
388 if (Missing > 0)
389 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
390 }
Justin Bogner40b8ba12014-06-26 01:45:07 +0000391}
392
Ted Kremenek2c674f62008-08-05 18:50:11 +0000393void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000394 EmitDeferred();
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000395 EmitVTablesOpportunistically();
Andrey Bokhankocab58582015-08-31 13:20:44 +0000396 applyGlobalValReplacements();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000397 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000398 checkAliases();
Erich Keane281d20b2018-01-08 21:34:17 +0000399 emitMultiVersionFunctions();
Eli Friedman5866fe32010-01-08 00:50:11 +0000400 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000401 EmitCXXGlobalDtorFunc();
Akira Hatanaka617e2612018-04-17 18:41:52 +0000402 registerGlobalDtorsWithAtExit();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000403 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000404 if (ObjCRuntime)
405 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000406 AddGlobalCtor(ObjCInitFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000407 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
408 CUDARuntime) {
Artem Belevichc66d2542018-06-27 18:32:51 +0000409 if (llvm::Function *CudaCtorFunction =
410 CUDARuntime->makeModuleCtorFunction())
Artem Belevich52cc4872015-05-07 19:34:16 +0000411 AddGlobalCtor(CudaCtorFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000412 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000413 if (OpenMPRuntime) {
Samuel Antaoee8fb302016-01-06 13:42:12 +0000414 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000415 OpenMPRuntime->emitRegistrationFunction()) {
416 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
417 OpenMPRegistrationFunction : nullptr;
418 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
419 }
Alexey Bataev03f270c2018-03-30 18:31:07 +0000420 OpenMPRuntime->clear();
421 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000422 if (PGOReader) {
Easwaran Raman81608122016-03-24 21:32:25 +0000423 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Easwaran Raman695890c2015-12-17 19:14:27 +0000424 if (PGOStats.hasDiagnostics())
425 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
426 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000427 EmitCtorList(GlobalCtors, "llvm.global_ctors");
428 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000429 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000430 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000431 EmitDeferredUnusedCoverageMappings();
432 if (CoverageMapping)
433 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000434 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000435 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000436 CodeGenFunction(*this).EmitCfiCheckStub();
437 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000438 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000439 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000440 if (SanStats)
441 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000442
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000443 if (CodeGenOpts.Autolink &&
444 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000445 EmitModuleLinkOptions();
446 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000447
Nirav Dave741dea02017-03-30 13:41:44 +0000448 // Record mregparm value now so it is visible through rest of codegen.
449 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
450 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
451 CodeGenOpts.NumRegisterParameters);
Jake Ehrlichc451cf22017-11-11 01:15:41 +0000452
Reid Kleckner124955a2015-08-05 18:51:13 +0000453 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000454 // We actually want the latest version when there are conflicts.
455 // We can change from Warning to Latest if such mode is supported.
456 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
457 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000458 }
459 if (CodeGenOpts.EmitCodeView) {
460 // Indicate that we want CodeView in the metadata.
461 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
462 }
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000463 if (CodeGenOpts.ControlFlowGuard) {
464 // We want function ID tables for Control Flow Guard.
Hans Wennborga912e3e2018-08-10 09:49:21 +0000465 getModule().addModuleFlag(llvm::Module::Warning, "cfguardtable", 1);
Adrian McCarthydb2736d2018-01-09 23:49:30 +0000466 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000467 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
468 // We don't support LTO with 2 with different StrictVTablePointers
469 // FIXME: we could support it by stripping all the information introduced
470 // by StrictVTablePointers.
471
472 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
473
474 llvm::Metadata *Ops[2] = {
475 llvm::MDString::get(VMContext, "StrictVTablePointers"),
476 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
477 llvm::Type::getInt32Ty(VMContext), 1))};
478
479 getModule().addModuleFlag(llvm::Module::Require,
480 "StrictVTablePointersRequirement",
481 llvm::MDNode::get(VMContext, Ops));
482 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000483 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000484 // We support a single version in the linked module. The LLVM
485 // parser will drop debug info with a different version number
486 // (and warn about it, too).
487 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000488 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000489
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000490 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000491 // the correct build attributes in the ARM backend. wchar_size is also used by
492 // TargetLibraryInfo.
Matthias Braunbffc1bb2017-09-26 02:37:23 +0000493 uint64_t WCharWidth =
494 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Matthias Brauna4519532017-05-20 01:29:55 +0000495 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
496
Justin Bogner9bb7f152014-06-23 20:03:28 +0000497 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000498 if ( Arch == llvm::Triple::arm
499 || Arch == llvm::Triple::armeb
500 || Arch == llvm::Triple::thumb
501 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000502 // The minimum width of an enum in bytes
503 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
504 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
505 }
506
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000507 if (CodeGenOpts.SanitizeCfiCrossDso) {
508 // Indicate that we want cross-DSO control flow integrity checks.
509 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
510 }
511
Oren Ben Simhon57cc1a52018-01-09 08:53:59 +0000512 if (CodeGenOpts.CFProtectionReturn &&
513 Target.checkCFProtectionReturnSupported(getDiags())) {
514 // Indicate that we want to instrument return control flow protection.
515 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
516 1);
517 }
518
519 if (CodeGenOpts.CFProtectionBranch &&
520 Target.checkCFProtectionBranchSupported(getDiags())) {
521 // Indicate that we want to instrument branch control flow protection.
522 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
523 1);
524 }
525
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000526 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000527 // Indicate whether __nvvm_reflect should be configured to flush denormal
528 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
529 // property.)
530 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
Yaxun Liue1bfbc52018-07-21 02:02:22 +0000531 CodeGenOpts.FlushDenorm ? 1 : 0);
Justin Lebard3a44f62016-04-05 18:26:20 +0000532 }
533
Alexey Bader364a1162017-06-20 14:30:18 +0000534 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
535 if (LangOpts.OpenCL) {
536 EmitOpenCLMetadata();
537 // Emit SPIR version.
538 if (getTriple().getArch() == llvm::Triple::spir ||
539 getTriple().getArch() == llvm::Triple::spir64) {
540 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
541 // opencl.spir.version named metadata.
542 llvm::Metadata *SPIRVerElts[] = {
543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
544 Int32Ty, LangOpts.OpenCLVersion / 100)),
545 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
546 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
547 llvm::NamedMDNode *SPIRVerMD =
548 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
549 llvm::LLVMContext &Ctx = TheModule.getContext();
550 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
551 }
552 }
553
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000554 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000555 assert(PLevel < 3 && "Invalid PIC Level");
556 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000557 if (Context.getLangOpts().PIE)
558 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000559 }
560
Caroline Tice62279732018-09-21 18:34:59 +0000561 if (getCodeGenOpts().CodeModel.size() > 0) {
562 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
563 .Case("tiny", llvm::CodeModel::Tiny)
564 .Case("small", llvm::CodeModel::Small)
565 .Case("kernel", llvm::CodeModel::Kernel)
566 .Case("medium", llvm::CodeModel::Medium)
567 .Case("large", llvm::CodeModel::Large)
568 .Default(~0u);
569 if (CM != ~0u) {
570 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
571 getModule().setCodeModel(codeModel);
572 }
573 }
574
Sriraman Tallam80af0052018-02-23 21:27:33 +0000575 if (CodeGenOpts.NoPLT)
576 getModule().setRtLibUseGOT();
577
John McCall0bdb1fd2010-09-16 06:16:50 +0000578 SimplifyPersonality();
579
John McCall09ae0322010-07-06 23:57:41 +0000580 if (getCodeGenOpts().EmitDeclMetadata)
581 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000582
583 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000584 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000585
586 if (DebugInfo)
587 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000588
Mikhail Maltsev4a4e7a32018-04-23 10:08:46 +0000589 if (getCodeGenOpts().EmitVersionIdentMetadata)
590 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000591
592 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000593}
594
Alexey Bader364a1162017-06-20 14:30:18 +0000595void CodeGenModule::EmitOpenCLMetadata() {
596 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
597 // opencl.ocl.version named metadata node.
598 llvm::Metadata *OCLVerElts[] = {
599 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
600 Int32Ty, LangOpts.OpenCLVersion / 100)),
601 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
602 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
603 llvm::NamedMDNode *OCLVerMD =
604 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
605 llvm::LLVMContext &Ctx = TheModule.getContext();
606 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
607}
608
Devang Patel945b8ae2011-03-23 16:29:39 +0000609void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
610 // Make sure that this type is translated.
611 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000612}
613
David Majnemer929025d2016-01-26 19:30:26 +0000614void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
615 // Make sure that this type is translated.
616 Types.RefreshTypeCacheForClass(RD);
617}
618
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000619llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
Dan Gohman947c9af2010-10-14 23:06:10 +0000620 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000621 return nullptr;
Ivan A. Kosarev289574e2017-10-02 09:54:47 +0000622 return TBAA->getTypeInfo(QTy);
Dan Gohman947c9af2010-10-14 23:06:10 +0000623}
624
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000625TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
Ivan A. Kosarev124a2182018-02-20 12:33:04 +0000626 if (!TBAA)
627 return TBAAAccessInfo();
628 return TBAA->getAccessInfo(AccessType);
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000629}
630
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000631TBAAAccessInfo
632CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000633 if (!TBAA)
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000634 return TBAAAccessInfo();
Ivan A. Kosarev4e50e702017-11-27 09:39:29 +0000635 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000636}
637
Dan Gohman22695fc2012-09-28 21:58:29 +0000638llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
639 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000640 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000641 return TBAA->getTBAAStructInfo(QTy);
642}
643
Ivan A. Kosarev383890b2017-10-06 08:17:48 +0000644llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
645 if (!TBAA)
646 return nullptr;
647 return TBAA->getBaseTypeInfo(QTy);
648}
649
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000650llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
Manman Renc451e572013-04-04 21:53:22 +0000651 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000652 return nullptr;
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000653 return TBAA->getAccessTagInfo(Info);
Manman Renc451e572013-04-04 21:53:22 +0000654}
655
Ivan A. Kosareved141ba2017-10-17 09:12:13 +0000656TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
657 TBAAAccessInfo TargetInfo) {
658 if (!TBAA)
659 return TBAAAccessInfo();
660 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
661}
662
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000663TBAAAccessInfo
664CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
665 TBAAAccessInfo InfoB) {
666 if (!TBAA)
667 return TBAAAccessInfo();
668 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
669}
670
Ivan A. Kosarev1860b522018-01-25 14:21:55 +0000671TBAAAccessInfo
672CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
673 TBAAAccessInfo SrcInfo) {
674 if (!TBAA)
675 return TBAAAccessInfo();
676 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
677}
678
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000679void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
Ivan A. Kosarev3d68ce92017-10-05 11:08:17 +0000680 TBAAAccessInfo TBAAInfo) {
681 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
682 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
Dan Gohman947c9af2010-10-14 23:06:10 +0000683}
684
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000685void CodeGenModule::DecorateInstructionWithInvariantGroup(
686 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000687 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
688 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000689}
690
Alp Toker29cb66b2014-01-26 06:17:37 +0000691void CodeGenModule::Error(SourceLocation loc, StringRef message) {
692 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
693 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000694}
695
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000696/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000697/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000698void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000699 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000700 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000701 std::string Msg = Type;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000702 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
703 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000704}
Chris Lattner41af8182007-12-02 06:27:33 +0000705
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000706/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000707/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000708void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000709 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000710 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000711 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000712 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000713}
714
John McCall23c29fe2011-06-24 21:55:10 +0000715llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
716 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
717}
718
Mike Stump11289f42009-09-09 15:08:12 +0000719void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000720 const NamedDecl *D) const {
Rafael Espindola123ce972018-01-24 18:58:32 +0000721 if (GV->hasDLLImportStorageClass())
722 return;
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000723 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000724 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000725 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000726 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000727 }
Rafael Espindola3f727a82018-03-14 18:14:46 +0000728 if (!D)
729 return;
John McCallc273f242010-10-30 11:50:40 +0000730 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000731 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindoladeb10be2018-02-07 19:04:41 +0000732 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
Rafael Espindola4a5da442013-02-27 02:56:45 +0000733 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000734}
735
Rafael Espindola699f5d62018-02-07 22:15:33 +0000736static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
Rafael Espindola3dd49812018-02-23 00:22:15 +0000737 llvm::GlobalValue *GV) {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000738 if (GV->hasLocalLinkage())
739 return true;
740
741 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
742 return true;
743
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000744 // DLLImport explicitly marks the GV as external.
745 if (GV->hasDLLImportStorageClass())
746 return false;
747
Rafael Espindola699f5d62018-02-07 22:15:33 +0000748 const llvm::Triple &TT = CGM.getTriple();
Martin Storsjo5ff7a8e2018-08-29 17:26:58 +0000749 if (TT.isWindowsGNUEnvironment()) {
750 // In MinGW, variables without DLLImport can still be automatically
751 // imported from a DLL by the linker; don't mark variables that
752 // potentially could come from another DLL as DSO local.
753 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
754 !GV->isThreadLocal())
755 return false;
756 }
Rafael Espindola922f2aa2018-02-23 19:30:48 +0000757 // Every other GV is local on COFF.
758 // Make an exception for windows OS in the triple: Some firmware builds use
759 // *-win32-macho triples. This (accidentally?) produced windows relocations
760 // without GOT tables in older clang versions; Keep this behaviour.
761 // FIXME: even thread local variables?
762 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
763 return true;
764
765 // Only handle COFF and ELF for now.
Rafael Espindola699f5d62018-02-07 22:15:33 +0000766 if (!TT.isOSBinFormatELF())
767 return false;
768
769 // If this is not an executable, don't assume anything is local.
770 const auto &CGOpts = CGM.getCodeGenOpts();
771 llvm::Reloc::Model RM = CGOpts.RelocationModel;
772 const auto &LOpts = CGM.getLangOpts();
773 if (RM != llvm::Reloc::Static && !LOpts.PIE)
774 return false;
775
776 // A definition cannot be preempted from an executable.
777 if (!GV->isDeclarationForLinker())
778 return true;
779
780 // Most PIC code sequences that assume that a symbol is local cannot produce a
781 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
782 // depended, it seems worth it to handle it here.
783 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
784 return false;
785
786 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
787 llvm::Triple::ArchType Arch = TT.getArch();
788 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
789 Arch == llvm::Triple::ppc64le)
790 return false;
791
792 // If we can use copy relocations we can assume it is local.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000793 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
794 if (!Var->isThreadLocal() &&
Rafael Espindola75e57362018-02-07 23:04:06 +0000795 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
796 return true;
Rafael Espindola699f5d62018-02-07 22:15:33 +0000797
798 // If we can use a plt entry as the symbol address we can assume it
799 // is local.
800 // FIXME: This should work for PIE, but the gold linker doesn't support it.
Rafael Espindola3dd49812018-02-23 00:22:15 +0000801 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
Rafael Espindola699f5d62018-02-07 22:15:33 +0000802 return true;
803
804 // Otherwise don't assue it is local.
805 return false;
806}
807
Rafael Espindola3dd49812018-02-23 00:22:15 +0000808void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
Rafael Espindola796d4a82018-03-02 01:29:51 +0000809 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
Rafael Espindola699f5d62018-02-07 22:15:33 +0000810}
811
Rafael Espindolab7350042018-03-01 00:35:47 +0000812void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
813 GlobalDecl GD) const {
814 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
Reid Klecknerae9b0702018-03-16 19:40:50 +0000815 // C++ destructors have a few C++ ABI specific special cases.
Rafael Espindolab7350042018-03-01 00:35:47 +0000816 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
Reid Klecknerae9b0702018-03-16 19:40:50 +0000817 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
818 return;
Rafael Espindolab7350042018-03-01 00:35:47 +0000819 }
820 setDLLImportDLLExport(GV, D);
821}
822
823void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
824 const NamedDecl *D) const {
Rafael Espindola3f727a82018-03-14 18:14:46 +0000825 if (D && D->isExternallyVisible()) {
Rafael Espindolab7350042018-03-01 00:35:47 +0000826 if (D->hasAttr<DLLImportAttr>())
827 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
828 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
829 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
830 }
831}
832
833void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
834 GlobalDecl GD) const {
835 setDLLImportDLLExport(GV, GD);
836 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
837}
838
Rafael Espindola699f5d62018-02-07 22:15:33 +0000839void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
840 const NamedDecl *D) const {
Rafael Espindolab7350042018-03-01 00:35:47 +0000841 setDLLImportDLLExport(GV, D);
842 setGlobalVisibilityAndLocal(GV, D);
843}
844
845void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
846 const NamedDecl *D) const {
Rafael Espindola699f5d62018-02-07 22:15:33 +0000847 setGlobalVisibility(GV, D);
Rafael Espindola3dd49812018-02-23 00:22:15 +0000848 setDSOLocal(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +0000849}
850
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000851static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
852 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
853 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
854 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
855 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
856 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
857}
858
859static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
860 CodeGenOptions::TLSModel M) {
861 switch (M) {
862 case CodeGenOptions::GeneralDynamicTLSModel:
863 return llvm::GlobalVariable::GeneralDynamicTLSModel;
864 case CodeGenOptions::LocalDynamicTLSModel:
865 return llvm::GlobalVariable::LocalDynamicTLSModel;
866 case CodeGenOptions::InitialExecTLSModel:
867 return llvm::GlobalVariable::InitialExecTLSModel;
868 case CodeGenOptions::LocalExecTLSModel:
869 return llvm::GlobalVariable::LocalExecTLSModel;
870 }
871 llvm_unreachable("Invalid TLS model!");
872}
873
David Majnemerbb525f7c2014-10-15 22:38:23 +0000874void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000875 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000876
David Majnemerbb525f7c2014-10-15 22:38:23 +0000877 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000878 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000879
880 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000881 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000882 TLM = GetLLVMTLSModel(Attr->getModel());
883 }
884
885 GV->setThreadLocalMode(TLM);
886}
887
Erich Keane3efe0022018-07-20 14:13:28 +0000888static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
889 StringRef Name) {
890 const TargetInfo &Target = CGM.getTarget();
891 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
892}
893
894static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
895 const CPUSpecificAttr *Attr,
896 raw_ostream &Out) {
897 // cpu_specific gets the current name, dispatch gets the resolver.
898 if (Attr)
899 Out << getCPUSpecificMangling(CGM, Attr->getCurCPUName()->getName());
900 else
901 Out << ".resolver";
902}
903
Erich Keane281d20b2018-01-08 21:34:17 +0000904static void AppendTargetMangling(const CodeGenModule &CGM,
905 const TargetAttr *Attr, raw_ostream &Out) {
906 if (Attr->isDefaultVersion())
907 return;
908
909 Out << '.';
Erich Keane3efe0022018-07-20 14:13:28 +0000910 const TargetInfo &Target = CGM.getTarget();
Erich Keane281d20b2018-01-08 21:34:17 +0000911 TargetAttr::ParsedTargetAttr Info =
912 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
Erich Keane3efe0022018-07-20 14:13:28 +0000913 // Multiversioning doesn't allow "no-${feature}", so we can
914 // only have "+" prefixes here.
915 assert(LHS.startswith("+") && RHS.startswith("+") &&
916 "Features should always have a prefix.");
917 return Target.multiVersionSortPriority(LHS.substr(1)) >
918 Target.multiVersionSortPriority(RHS.substr(1));
919 });
Erich Keane281d20b2018-01-08 21:34:17 +0000920
921 bool IsFirst = true;
922
923 if (!Info.Architecture.empty()) {
924 IsFirst = false;
925 Out << "arch_" << Info.Architecture;
926 }
927
928 for (StringRef Feat : Info.Features) {
929 if (!IsFirst)
930 Out << '_';
931 IsFirst = false;
932 Out << Feat.substr(1);
933 }
934}
935
936static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
937 const NamedDecl *ND,
Erich Keane3efe0022018-07-20 14:13:28 +0000938 bool OmitMultiVersionMangling = false) {
Erich Keane281d20b2018-01-08 21:34:17 +0000939 SmallString<256> Buffer;
940 llvm::raw_svector_ostream Out(Buffer);
941 MangleContext &MC = CGM.getCXXABI().getMangleContext();
942 if (MC.shouldMangleDeclName(ND)) {
943 llvm::raw_svector_ostream Out(Buffer);
944 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
945 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
946 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
947 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
948 else
949 MC.mangleName(ND, Out);
950 } else {
951 IdentifierInfo *II = ND->getIdentifier();
952 assert(II && "Attempt to mangle unnamed decl.");
953 const auto *FD = dyn_cast<FunctionDecl>(ND);
954
955 if (FD &&
956 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
957 llvm::raw_svector_ostream Out(Buffer);
958 Out << "__regcall3__" << II->getName();
959 } else {
960 Out << II->getName();
961 }
962 }
963
964 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Erich Keane3efe0022018-07-20 14:13:28 +0000965 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
966 if (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())
967 AppendCPUSpecificCPUDispatchMangling(
968 CGM, FD->getAttr<CPUSpecificAttr>(), Out);
969 else
970 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
971 }
972
Erich Keane281d20b2018-01-08 21:34:17 +0000973 return Out.str();
974}
975
976void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
977 const FunctionDecl *FD) {
978 if (!FD->isMultiVersion())
979 return;
980
981 // Get the name of what this would be without the 'target' attribute. This
982 // allows us to lookup the version that was emitted when this wasn't a
983 // multiversion function.
984 std::string NonTargetName =
Erich Keane3efe0022018-07-20 14:13:28 +0000985 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
Erich Keane281d20b2018-01-08 21:34:17 +0000986 GlobalDecl OtherGD;
987 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
988 assert(OtherGD.getCanonicalDecl()
989 .getDecl()
990 ->getAsFunction()
991 ->isMultiVersion() &&
992 "Other GD should now be a multiversioned function");
993 // OtherFD is the version of this function that was mangled BEFORE
994 // becoming a MultiVersion function. It potentially needs to be updated.
995 const FunctionDecl *OtherFD =
996 OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
997 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
998 // This is so that if the initial version was already the 'default'
999 // version, we don't try to update it.
1000 if (OtherName != NonTargetName) {
Erich Keanebc40c5c2018-01-09 01:09:12 +00001001 // Remove instead of erase, since others may have stored the StringRef
1002 // to this.
1003 const auto ExistingRecord = Manglings.find(NonTargetName);
1004 if (ExistingRecord != std::end(Manglings))
1005 Manglings.remove(&(*ExistingRecord));
Erich Keane281d20b2018-01-08 21:34:17 +00001006 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1007 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1008 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1009 Entry->setName(OtherName);
1010 }
1011 }
1012}
1013
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001014StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +00001015 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1016
1017 // Some ABIs don't have constructor variants. Make sure that base and
1018 // complete constructors get mangled the same.
1019 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1020 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1021 CXXCtorType OrigCtorType = GD.getCtorType();
1022 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1023 if (OrigCtorType == Ctor_Base)
1024 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1025 }
1026 }
1027
Erich Keane3efe0022018-07-20 14:13:28 +00001028 const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
1029 // Since CPUSpecific can require multiple emits per decl, store the manglings
1030 // separately.
1031 if (FD &&
1032 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())) {
1033 const auto *SD = FD->getAttr<CPUSpecificAttr>();
1034
1035 std::pair<GlobalDecl, unsigned> SpecCanonicalGD{
1036 CanonicalGD,
1037 SD ? SD->ActiveArgIndex : std::numeric_limits<unsigned>::max()};
1038
1039 auto FoundName = CPUSpecificMangledDeclNames.find(SpecCanonicalGD);
1040 if (FoundName != CPUSpecificMangledDeclNames.end())
1041 return FoundName->second;
1042
1043 auto Result = CPUSpecificManglings.insert(
1044 std::make_pair(getMangledNameImpl(*this, GD, FD), SpecCanonicalGD));
1045 return CPUSpecificMangledDeclNames[SpecCanonicalGD] = Result.first->first();
1046 }
1047
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001048 auto FoundName = MangledDeclNames.find(CanonicalGD);
1049 if (FoundName != MangledDeclNames.end())
1050 return FoundName->second;
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001051
Richard Smith6d0e97a2014-08-02 00:50:16 +00001052 // Keep the first result in the case of a mangling collision.
Erich Keane281d20b2018-01-08 21:34:17 +00001053 const auto *ND = cast<NamedDecl>(GD.getDecl());
1054 auto Result =
1055 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
NAKAMURA Takumi6e4d7742017-07-30 05:06:26 +00001056 return MangledDeclNames[CanonicalGD] = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +00001057}
1058
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001059StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1060 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001061 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1062 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +00001063
Alp Tokerfb8d02b2014-06-05 22:10:59 +00001064 SmallString<256> Buffer;
1065 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +00001066 if (!D)
Jake Ehrlichc451cf22017-11-11 01:15:41 +00001067 MangleCtx.mangleGlobalBlock(BD,
Fariborz Jahanian63628032012-06-26 16:06:38 +00001068 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001069 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001070 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001071 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001072 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +00001073 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +00001074 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +00001075
Richard Smith6d0e97a2014-08-02 00:50:16 +00001076 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1077 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +00001078}
1079
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001080llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +00001081 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +00001082}
1083
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001084/// AddGlobalCtor - Add a function to the list that will be called before
1085/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001086void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1087 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +00001088 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001089 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001090}
1091
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001092/// AddGlobalDtor - Add a function to the list that will be called
1093/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +00001094void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Akira Hatanaka617e2612018-04-17 18:41:52 +00001095 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1096 DtorsUsingAtExit[Priority].push_back(Dtor);
1097 return;
1098 }
1099
Daniel Dunbardec798b2009-01-13 02:25:00 +00001100 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +00001101 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001102}
1103
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001104void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001105 if (Fns.empty()) return;
1106
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001107 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +00001108 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001109 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001110
Reid Kleckner563f0e82014-05-23 21:13:45 +00001111 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1112 llvm::StructType *CtorStructTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +00001113 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001114
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001115 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +00001116 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001117 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +00001118 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +00001119 auto ctor = ctors.beginStruct(CtorStructTy);
1120 ctor.addInt(Int32Ty, I.Priority);
1121 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1122 if (I.AssociatedData)
1123 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1124 else
1125 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +00001126 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001127 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001128
John McCall18081af2016-11-19 20:12:25 +00001129 auto list =
1130 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1131 /*constant*/ false,
1132 llvm::GlobalValue::AppendingLinkage);
1133
1134 // The LTO linker doesn't seem to like it when we set an alignment
1135 // on appending variables. Take it off as a workaround.
1136 list->setAlignment(0);
1137
Vassil Vassilev188ad3a2016-10-27 09:12:20 +00001138 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +00001139}
1140
John McCalld4324142010-02-19 01:32:20 +00001141llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001142CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001143 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +00001144
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001145 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +00001146
Reid Klecknerae9b0702018-03-16 19:40:50 +00001147 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1148 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
Reid Klecknera283e482017-12-21 19:44:23 +00001149
Richard Smith5179eb72016-06-28 19:03:57 +00001150 if (isa<CXXConstructorDecl>(D) &&
1151 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1152 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1153 // Our approach to inheriting constructors is fundamentally different from
1154 // that used by the MS ABI, so keep our inheriting constructor thunks
1155 // internal rather than trying to pick an unambiguous mangling for them.
1156 return llvm::GlobalValue::InternalLinkage;
1157 }
1158
Hans Wennborg275efb92014-05-28 01:52:23 +00001159 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +00001160}
Nuno Lopesb6f79532008-06-08 15:45:52 +00001161
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001162llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001163 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1164 if (!MDS) return nullptr;
1165
Benjamin Kramer630cf8c2016-11-23 11:20:27 +00001166 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001167}
1168
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001169void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +00001170 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +00001171 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001172 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +00001173 llvm::AttributeList PAL;
1174 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1175 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001176 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +00001177}
1178
John McCall9b0a7ce2011-10-02 01:16:38 +00001179/// Determines whether the language options require us to model
1180/// unwind exceptions. We treat -fexceptions as mandating this
1181/// except under the fragile ObjC ABI with only ObjC exceptions
1182/// enabled. This means, for example, that C with -fexceptions
1183/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001184static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +00001185 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001186 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +00001187
1188 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001189 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +00001190
1191 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001192 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +00001193 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +00001194 }
1195
1196 return true;
1197}
1198
Peter Collingbournee44acad2018-06-26 02:15:47 +00001199static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1200 const CXXMethodDecl *MD) {
1201 // Check that the type metadata can ever actually be used by a call.
1202 if (!CGM.getCodeGenOpts().LTOUnit ||
1203 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1204 return false;
1205
1206 // Only functions whose address can be taken with a member function pointer
1207 // need this sort of type metadata.
1208 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1209 !isa<CXXDestructorDecl>(MD);
1210}
1211
1212std::vector<const CXXRecordDecl *>
1213CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1214 llvm::SetVector<const CXXRecordDecl *> MostBases;
1215
1216 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1217 CollectMostBases = [&](const CXXRecordDecl *RD) {
1218 if (RD->getNumBases() == 0)
1219 MostBases.insert(RD);
1220 for (const CXXBaseSpecifier &B : RD->bases())
1221 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1222 };
1223 CollectMostBases(RD);
1224 return MostBases.takeVector();
1225}
1226
Daniel Dunbar38932572009-04-14 08:05:55 +00001227void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1228 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001229 llvm::AttrBuilder B;
1230
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001231 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001232 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +00001233
David Blaikiebbafb8a2012-03-11 07:00:24 +00001234 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001235 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +00001236
Manoj Gupta4fbf84c2018-05-09 21:41:18 +00001237 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1238 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1239 B.addAttribute(llvm::Attribute::StackProtect);
1240 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1241 B.addAttribute(llvm::Attribute::StackProtectStrong);
1242 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1243 B.addAttribute(llvm::Attribute::StackProtectReq);
1244 }
Akira Hatanaka200500d2015-10-08 19:30:57 +00001245
1246 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001247 // If we don't have a declaration to control inlining, the function isn't
1248 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1249 // disabled, mark the function as noinline.
1250 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1251 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1252 B.addAttribute(llvm::Attribute::NoInline);
1253
Reid Kleckneree4930b2017-05-02 22:07:37 +00001254 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +00001255 return;
1256 }
1257
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001258 // Track whether we need to add the optnone LLVM attribute,
1259 // starting with the default for this optimization level.
1260 bool ShouldAddOptNone =
1261 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1262 // We can't add optnone in the following cases, it won't pass the verifier.
1263 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1264 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1265 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1266
1267 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +00001268 B.addAttribute(llvm::Attribute::OptimizeNone);
1269
1270 // OptimizeNone implies noinline; we should not be inlining such functions.
1271 B.addAttribute(llvm::Attribute::NoInline);
1272 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1273 "OptimizeNone and AlwaysInline on same function!");
1274
1275 // We still need to handle naked functions even though optnone subsumes
1276 // much of their semantics.
1277 if (D->hasAttr<NakedAttr>())
1278 B.addAttribute(llvm::Attribute::Naked);
1279
1280 // OptimizeNone wins over OptimizeForSize and MinSize.
1281 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1282 F->removeFnAttr(llvm::Attribute::MinSize);
1283 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +00001284 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001285 B.addAttribute(llvm::Attribute::Naked);
1286 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +00001287 } else if (D->hasAttr<NoDuplicateAttr>()) {
1288 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001289 } else if (D->hasAttr<NoInlineAttr>()) {
1290 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +00001291 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +00001292 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001293 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00001294 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001295 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1296 // If we're not inlining, then force everything that isn't always_inline to
1297 // carry an explicit noinline attribute.
1298 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1299 B.addAttribute(llvm::Attribute::NoInline);
1300 } else {
1301 // Otherwise, propagate the inline hint attribute and potentially use its
1302 // absence to mark things as noinline.
1303 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1304 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
1305 return Redecl->isInlineSpecified();
1306 })) {
1307 B.addAttribute(llvm::Attribute::InlineHint);
1308 } else if (CodeGenOpts.getInlining() ==
1309 CodeGenOptions::OnlyHintInlining &&
1310 !FD->isInlined() &&
1311 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1312 B.addAttribute(llvm::Attribute::NoInline);
1313 }
1314 }
Eli Friedmanc55efe42011-08-22 23:55:33 +00001315 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +00001316
Chandler Carruthfcd33142016-12-23 01:24:49 +00001317 // Add other optimization related attributes if we are optimizing this
1318 // function.
1319 if (!D->hasAttr<OptimizeNoneAttr>()) {
1320 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001321 if (!ShouldAddOptNone)
1322 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001323 B.addAttribute(llvm::Attribute::Cold);
1324 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +00001325
Chandler Carruthfcd33142016-12-23 01:24:49 +00001326 if (D->hasAttr<MinSizeAttr>())
1327 B.addAttribute(llvm::Attribute::MinSize);
1328 }
Richard Smithb555a762012-09-28 22:46:07 +00001329
Reid Kleckneree4930b2017-05-02 22:07:37 +00001330 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +00001331
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001332 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1333 if (alignment)
1334 F->setAlignment(alignment);
1335
Saleem Abdulrasool3fe5b7a2018-04-19 23:14:57 +00001336 if (!D->hasAttr<AlignedAttr>())
1337 if (LangOpts.FunctionAlignment)
1338 F->setAlignment(1 << LangOpts.FunctionAlignment);
1339
Dan Gohmanc2853072015-09-03 22:51:53 +00001340 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1341 // reserve a bit for differentiating between virtual and non-virtual member
1342 // functions. If the current target's C++ ABI requires this and this is a
1343 // member function, set its alignment accordingly.
1344 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1345 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1346 F->setAlignment(2);
1347 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001348
1349 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1350 if (CodeGenOpts.SanitizeCfiCrossDso)
1351 if (auto *FD = dyn_cast<FunctionDecl>(D))
Peter Collingbournee44acad2018-06-26 02:15:47 +00001352 CreateFunctionTypeMetadataForIcall(FD, F);
1353
1354 // Emit type metadata on member functions for member function pointer checks.
1355 // These are only ever necessary on definitions; we're guaranteed that the
1356 // definition will be present in the LTO unit as a result of LTO visibility.
1357 auto *MD = dyn_cast<CXXMethodDecl>(D);
1358 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1359 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1360 llvm::Metadata *Id =
1361 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1362 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1363 F->addTypeMetadata(0, Id);
1364 }
1365 }
Daniel Dunbar449a3392008-09-04 23:41:35 +00001366}
1367
Rafael Espindola75c649c2018-03-01 00:06:55 +00001368void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1369 const Decl *D = GD.getDecl();
Rafael Espindolab7350042018-03-01 00:35:47 +00001370 if (dyn_cast_or_null<NamedDecl>(D))
1371 setGVProperties(GV, GD);
John McCall457a04e2010-10-22 21:05:15 +00001372 else
1373 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001374
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001375 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001376 addUsedGlobal(GV);
Elizabeth Andrews6593df22018-08-22 19:05:19 +00001377
1378 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1379 const auto *VD = cast<VarDecl>(D);
1380 if (VD->getType().isConstQualified() && VD->getStorageClass() == SC_Static)
1381 addUsedGlobal(GV);
1382 }
Rafael Espindola502f65a2014-05-05 20:21:03 +00001383}
1384
Erich Keane93e58662018-02-12 17:01:41 +00001385bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1386 llvm::AttrBuilder &Attrs) {
1387 // Add target-cpu and target-features attributes to functions. If
1388 // we have a decl for the function and it has a target attribute then
1389 // parse that and add it to the feature set.
1390 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1391 std::vector<std::string> Features;
1392 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1393 FD = FD ? FD->getMostRecentDecl() : FD;
1394 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
Erich Keane3efe0022018-07-20 14:13:28 +00001395 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
Erich Keane93e58662018-02-12 17:01:41 +00001396 bool AddedAttr = false;
Erich Keane3efe0022018-07-20 14:13:28 +00001397 if (TD || SD) {
Erich Keane93e58662018-02-12 17:01:41 +00001398 llvm::StringMap<bool> FeatureMap;
1399 getFunctionFeatureMap(FeatureMap, FD);
1400
1401 // Produce the canonical string for this set of features.
1402 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1403 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1404
1405 // Now add the target-cpu and target-features to the function.
1406 // While we populated the feature map above, we still need to
1407 // get and parse the target attribute so we can get the cpu for
1408 // the function.
Erich Keane3efe0022018-07-20 14:13:28 +00001409 if (TD) {
1410 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1411 if (ParsedAttr.Architecture != "" &&
1412 getTarget().isValidCPUName(ParsedAttr.Architecture))
1413 TargetCPU = ParsedAttr.Architecture;
1414 }
Erich Keane93e58662018-02-12 17:01:41 +00001415 } else {
1416 // Otherwise just add the existing target cpu and target features to the
1417 // function.
1418 Features = getTarget().getTargetOpts().Features;
1419 }
1420
1421 if (TargetCPU != "") {
1422 Attrs.addAttribute("target-cpu", TargetCPU);
1423 AddedAttr = true;
1424 }
1425 if (!Features.empty()) {
Fangrui Song55fab262018-09-26 22:16:28 +00001426 llvm::sort(Features);
Erich Keane93e58662018-02-12 17:01:41 +00001427 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1428 AddedAttr = true;
1429 }
1430
1431 return AddedAttr;
1432}
1433
Rafael Espindola285271c2018-02-28 23:54:23 +00001434void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001435 llvm::GlobalObject *GO) {
Rafael Espindola285271c2018-02-28 23:54:23 +00001436 const Decl *D = GD.getDecl();
Rafael Espindola75c649c2018-03-01 00:06:55 +00001437 SetCommonAttributes(GD, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001438
Javed Absar2a67c9e2017-06-05 10:11:57 +00001439 if (D) {
1440 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1441 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1442 GV->addAttribute("bss-section", SA->getName());
1443 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1444 GV->addAttribute("data-section", SA->getName());
1445 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1446 GV->addAttribute("rodata-section", SA->getName());
1447 }
1448
1449 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1450 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
Erich Keane30994d22018-02-08 20:04:22 +00001451 if (!D->getAttr<SectionAttr>())
1452 F->addFnAttr("implicit-section-name", SA->getName());
Erich Keane93e58662018-02-12 17:01:41 +00001453
1454 llvm::AttrBuilder Attrs;
1455 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1456 // We know that GetCPUAndFeaturesAttributes will always have the
1457 // newest set, since it has the newest possible FunctionDecl, so the
1458 // new ones should replace the old.
1459 F->removeFnAttr("target-cpu");
1460 F->removeFnAttr("target-features");
1461 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1462 }
Javed Absar2a67c9e2017-06-05 10:11:57 +00001463 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001464
Erich Keane7963e8b2018-07-18 20:04:48 +00001465 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1466 GO->setSection(CSA->getName());
1467 else if (const auto *SA = D->getAttr<SectionAttr>())
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001468 GO->setSection(SA->getName());
Javed Absar2a67c9e2017-06-05 10:11:57 +00001469 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001470
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001471 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001472}
1473
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001474void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001475 llvm::Function *F,
1476 const CGFunctionInfo &FI) {
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001477 const Decl *D = GD.getDecl();
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001478 SetLLVMFunctionAttributes(D, FI, F);
1479 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001480
1481 F->setLinkage(llvm::Function::InternalLinkage);
1482
Rafael Espindola285271c2018-02-28 23:54:23 +00001483 setNonAliasAttributes(GD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001484}
1485
Rafael Espindolab7350042018-03-01 00:35:47 +00001486static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
David Majnemerf6acb762014-04-25 17:07:16 +00001487 // Set linkage and visibility in case we never see a definition.
1488 LinkageInfo LV = ND->getLinkageAndVisibility();
Rafael Espindolab7350042018-03-01 00:35:47 +00001489 // Don't set internal linkage on declarations.
1490 // "extern_weak" is overloaded in LLVM; we probably should have
1491 // separate linkage types for this.
1492 if (isExternallyVisible(LV.getLinkage()) &&
1493 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1494 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001495}
1496
Peter Collingbournee44acad2018-06-26 02:15:47 +00001497void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1498 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001499 // Only if we are checking indirect calls.
1500 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1501 return;
1502
Peter Collingbournee44acad2018-06-26 02:15:47 +00001503 // Non-static class methods are handled via vtable or member function pointer
1504 // checks elsewhere.
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001505 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1506 return;
1507
1508 // Additionally, if building with cross-DSO support...
1509 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001510 // Skip available_externally functions. They won't be codegen'ed in the
1511 // current module anyway.
1512 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1513 return;
1514 }
1515
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001516 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001517 F->addTypeMetadata(0, MD);
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00001518 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001519
1520 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001521 if (CodeGenOpts.SanitizeCfiCrossDso)
1522 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1523 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001524}
1525
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001526void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1527 bool IsIncompleteFunction,
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001528 bool IsThunk) {
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001529
Pete Cooper2f1637a2015-05-20 17:17:45 +00001530 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001531 // If this is an intrinsic function, set the function's attributes
1532 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001533 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001534 return;
1535 }
1536
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001537 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001538
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001539 if (!IsIncompleteFunction) {
John McCalla729c622012-02-17 03:33:10 +00001540 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001541 // Setup target-specific attributes.
Rafael Espindoladeb10be2018-02-07 19:04:41 +00001542 if (F->isDeclaration())
1543 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
Simon Atanasyan1a116db2017-07-20 20:34:18 +00001544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001546 // Add the Returned attribute for "this", except for iOS 5 and earlier
1547 // where substantial code, including the libstdc++ dylib, was compiled with
1548 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001549 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001550 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001551 assert(!F->arg_empty() &&
1552 F->arg_begin()->getType()
1553 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1554 "unexpected this return");
1555 F->addAttribute(1, llvm::Attribute::Returned);
1556 }
1557
Daniel Dunbar38932572009-04-14 08:05:55 +00001558 // Only a few attributes are set on declarations; these may later be
1559 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001560
Jake Ehrlichba874ad2017-11-29 00:54:20 +00001561 setLinkageForGV(F, FD);
Rafael Espindola699f5d62018-02-07 22:15:33 +00001562 setGVProperties(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001563
Erich Keane7963e8b2018-07-18 20:04:48 +00001564 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1565 F->setSection(CSA->getName());
1566 else if (const auto *SA = FD->getAttr<SectionAttr>())
1567 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001568
Richard Smith351241c2016-04-07 21:46:12 +00001569 if (FD->isReplaceableGlobalAllocationFunction()) {
1570 // A replaceable global allocation function does not act like a builtin by
1571 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001572 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001573 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001574
Richard Smith351241c2016-04-07 21:46:12 +00001575 // A sane operator new returns a non-aliasing pointer.
1576 // FIXME: Also add NonNull attribute to the return value
1577 // for the non-nothrow forms?
1578 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1579 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1580 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001581 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001582 llvm::Attribute::NoAlias);
1583 }
1584
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001585 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001586 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001587 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1588 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001589 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001590
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001591 // Don't emit entries for function declarations in the cross-DSO mode. This
1592 // is handled with better precision by the receiving DSO.
1593 if (!CodeGenOpts.SanitizeCfiCrossDso)
Peter Collingbournee44acad2018-06-26 02:15:47 +00001594 CreateFunctionTypeMetadataForIcall(FD, F);
Alexey Bataevb952e632017-12-15 16:28:31 +00001595
1596 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1597 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001598}
1599
Rafael Espindola060062a2014-03-06 22:15:10 +00001600void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001601 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001602 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001603 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001604}
1605
Rafael Espindola060062a2014-03-06 22:15:10 +00001606void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1607 assert(!GV->isDeclaration() &&
1608 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001609 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001610}
1611
1612static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001613 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001614 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001615 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001616 return;
1617
Rafael Espindola060062a2014-03-06 22:15:10 +00001618 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001619 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001620 UsedArray.resize(List.size());
1621 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001622 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001623 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1624 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001625 }
Mike Stump11289f42009-09-09 15:08:12 +00001626
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001627 if (UsedArray.empty())
1628 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001629 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001630
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001631 auto *GV = new llvm::GlobalVariable(
1632 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1633 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001634
1635 GV->setSection("llvm.metadata");
1636}
1637
Rafael Espindola060062a2014-03-06 22:15:10 +00001638void CodeGenModule::emitLLVMUsed() {
1639 emitUsed(*this, "llvm.used", LLVMUsed);
1640 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1641}
1642
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001643void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001644 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001645 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1646}
1647
Aaron Ballman5d041be2013-06-04 02:07:14 +00001648void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1649 llvm::SmallString<32> Opt;
1650 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001651 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001652 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1653}
1654
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00001655void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1656 auto &C = getLLVMContext();
1657 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1658 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1659}
1660
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001661void CodeGenModule::AddDependentLib(StringRef Lib) {
1662 llvm::SmallString<24> Opt;
1663 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001664 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001665 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1666}
1667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001668/// Add link options implied by the given module, including modules
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001669/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001670static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
Peter Collingbourne89061b22017-06-12 20:10:48 +00001671 SmallVectorImpl<llvm::MDNode *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001672 llvm::SmallPtrSet<Module *, 16> &Visited) {
1673 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001674 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001675 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001676 }
1677
1678 // Import this module's dependencies.
1679 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001680 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001681 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001682 }
1683
1684 // Add linker options to link against the libraries/frameworks
1685 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001686 llvm::LLVMContext &Context = CGM.getLLVMContext();
Bruno Cardoso Lopesa3b5f712018-04-16 19:42:32 +00001687
1688 // For modules that use export_as for linking, use that module
1689 // name instead.
1690 if (Mod->UseExportAsModuleLinkName)
1691 return;
1692
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001693 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001694 // Link against a framework. Frameworks are currently Darwin only, so we
1695 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001696 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001697 llvm::Metadata *Args[2] = {
1698 llvm::MDString::get(Context, "-framework"),
1699 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001700
1701 Metadata.push_back(llvm::MDNode::get(Context, Args));
1702 continue;
1703 }
1704
1705 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001706 llvm::SmallString<24> Opt;
1707 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1708 Mod->LinkLibraries[I-1].Library, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001709 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001710 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1711 }
1712}
1713
1714void CodeGenModule::EmitModuleLinkOptions() {
1715 // Collect the set of all of the modules we want to visit to emit link
1716 // options, which is essentially the imported modules and all of their
1717 // non-explicit child modules.
1718 llvm::SetVector<clang::Module *> LinkModules;
1719 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1720 SmallVector<clang::Module *, 16> Stack;
1721
1722 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001723 for (Module *M : ImportedModules) {
1724 // Do not add any link flags when an implementation TU of a module imports
1725 // a header of that same module.
1726 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1727 !getLangOpts().isCompilingModule())
1728 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001729 if (Visited.insert(M).second)
1730 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001731 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001732
1733 // Find all of the modules to import, making a little effort to prune
1734 // non-leaf modules.
1735 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001736 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001737
1738 bool AnyChildren = false;
1739
1740 // Visit the submodules of this module.
1741 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1742 SubEnd = Mod->submodule_end();
1743 Sub != SubEnd; ++Sub) {
1744 // Skip explicit children; they need to be explicitly imported to be
1745 // linked against.
1746 if ((*Sub)->IsExplicit)
1747 continue;
1748
David Blaikie82e95a32014-11-19 07:49:47 +00001749 if (Visited.insert(*Sub).second) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001750 Stack.push_back(*Sub);
1751 AnyChildren = true;
1752 }
1753 }
1754
1755 // We didn't find any children, so add this module to the list of
1756 // modules to link against.
1757 if (!AnyChildren) {
1758 LinkModules.insert(Mod);
1759 }
1760 }
1761
1762 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001763 // order. We don't do anything to try to order import link flags with respect
1764 // to linker options inserted by things like #pragma comment().
Peter Collingbourne89061b22017-06-12 20:10:48 +00001765 SmallVector<llvm::MDNode *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001766 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001767 for (Module *M : LinkModules)
1768 if (Visited.insert(M).second)
1769 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001770 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001771 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001772
Daniel Dunbar69e47462013-01-17 01:35:06 +00001773 // Add the linker options metadata flag.
Peter Collingbourne89061b22017-06-12 20:10:48 +00001774 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1775 for (auto *MD : LinkerOptionsMetadata)
1776 NMD->addOperand(MD);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001777}
1778
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001779void CodeGenModule::EmitDeferred() {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001780 // Emit deferred declare target declarations.
1781 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
1782 getOpenMPRuntime().emitDeferredTargetDecls();
1783
Chris Lattner45470942009-03-21 09:44:56 +00001784 // Emit code for any potentially referenced deferred decls. Since a
1785 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001786 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001787
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001788 if (!DeferredVTables.empty()) {
1789 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001790
Eric Christopherd160c502016-01-29 01:35:53 +00001791 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001792 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001793 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001794 assert(DeferredVTables.empty());
1795 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001796
Eric Christopherd160c502016-01-29 01:35:53 +00001797 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001798 if (DeferredDeclsToEmit.empty())
1799 return;
John McCall6bd2a892013-01-25 22:31:03 +00001800
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001801 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1802 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001803 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001804 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1805
Sanjoy Das70a60512017-05-01 06:12:13 +00001806 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001807 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1808 // to get GlobalValue with exactly the type we need, not something that
1809 // might had been created for another decl with the same mangled name but
1810 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001811 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001812 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001813
1814 // In case of different address spaces, we may still get a cast, even with
1815 // IsForDefinition equal to true. Query mangled names table to get
1816 // GlobalValue.
1817 if (!GV)
1818 GV = GetGlobalValue(getMangledName(D));
1819
1820 // Make sure GetGlobalValue returned non-null.
1821 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001822
John McCallc2af9392010-05-27 01:45:30 +00001823 // Check to see if we've already emitted this. This is necessary
1824 // for a couple of reasons: first, decls can end up in the
1825 // deferred-decls queue multiple times, and second, decls can end
1826 // up with definitions in unusual ways (e.g. by an extern inline
1827 // function acquiring a strong function redefinition). Just
1828 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001829 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001830 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001831
Chris Lattner45470942009-03-21 09:44:56 +00001832 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001833 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001834
1835 // If we found out that we need to emit more decls, do that recursively.
1836 // This has the advantage that the decls are emitted in a DFS and related
1837 // ones are close together, which is convenient for testing.
1838 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1839 EmitDeferred();
1840 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1841 }
Chris Lattner45470942009-03-21 09:44:56 +00001842 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001843}
Chris Lattner09153c02007-06-22 18:48:09 +00001844
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001845void CodeGenModule::EmitVTablesOpportunistically() {
1846 // Try to emit external vtables as available_externally if they have emitted
1847 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1848 // is not allowed to create new references to things that need to be emitted
1849 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1850
Piotr Padlewski05547742017-06-01 09:24:36 +00001851 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1852 && "Only emit opportunistic vtables with optimizations");
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001853
1854 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1855 assert(getVTables().isVTableExternal(RD) &&
1856 "This queue should only contain external vtables");
1857 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1858 VTables.GenerateClassData(RD);
1859 }
1860 OpportunisticVTables.clear();
1861}
1862
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001863void CodeGenModule::EmitGlobalAnnotations() {
1864 if (Annotations.empty())
1865 return;
1866
1867 // Create a new global variable for the ConstantStruct in the Module.
1868 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1869 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001870 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1871 llvm::GlobalValue::AppendingLinkage,
1872 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001873 gv->setSection(AnnotationSection);
1874}
1875
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001876llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001877 llvm::Constant *&AStr = AnnotationStrings[Str];
1878 if (AStr)
1879 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001880
1881 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001882 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001883 auto *gv =
1884 new llvm::GlobalVariable(getModule(), s->getType(), true,
1885 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001886 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001887 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001888 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001889 return gv;
1890}
1891
1892llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1893 SourceManager &SM = getContext().getSourceManager();
1894 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1895 if (PLoc.isValid())
1896 return EmitAnnotationString(PLoc.getFilename());
1897 return EmitAnnotationString(SM.getBufferName(Loc));
1898}
1899
1900llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1901 SourceManager &SM = getContext().getSourceManager();
1902 PresumedLoc PLoc = SM.getPresumedLoc(L);
1903 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1904 SM.getExpansionLineNumber(L);
1905 return llvm::ConstantInt::get(Int32Ty, LineNo);
1906}
1907
Mike Stump11289f42009-09-09 15:08:12 +00001908llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001909 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001910 SourceLocation L) {
1911 // Get the globals for file name, annotation, and the line number.
1912 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1913 *UnitGV = EmitAnnotationUnit(L),
1914 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001915
Daniel Dunbar346892a2009-04-14 22:41:13 +00001916 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001917 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001918 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1919 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1920 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1921 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001922 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001923 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001924}
1925
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001926void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1927 llvm::GlobalValue *GV) {
1928 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1929 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001930 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1931 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001932}
1933
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001934bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1935 llvm::Function *Fn,
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001936 SourceLocation Loc) const {
1937 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1938 // Blacklist by function name.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001939 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001940 return true;
1941 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001942 if (Loc.isValid())
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001943 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001944 // If location is unknown, this may be a compiler-generated function. Assume
1945 // it's located in the main file.
1946 auto &SM = Context.getSourceManager();
1947 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001948 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001949 }
1950 return false;
1951}
1952
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001953bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1954 SourceLocation Loc, QualType Ty,
1955 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001956 // For now globals can be blacklisted only in ASan and KASan.
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001957 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +00001958 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1959 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001960 if (!EnabledAsanMask)
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001961 return false;
1962 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001963 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001964 return true;
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001965 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001966 return true;
1967 // Check global type.
1968 if (!Ty.isNull()) {
1969 // Drill down the array types: if global variable of a fixed type is
1970 // blacklisted, we also don't instrument arrays of them.
1971 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1972 Ty = AT->getElementType();
1973 Ty = Ty.getCanonicalType().getUnqualifiedType();
1974 // We allow to blacklist only record types (classes, structs etc.)
1975 if (Ty->isRecordType()) {
1976 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +00001977 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001978 return true;
1979 }
1980 }
1981 return false;
1982}
1983
Dean Michael Berris835832d2017-03-30 00:29:36 +00001984bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1985 StringRef Category) const {
Dean Michael Berris835832d2017-03-30 00:29:36 +00001986 const auto &XRayFilter = getContext().getXRayFilter();
1987 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
Dean Michael Berris488f7c22018-04-13 02:31:58 +00001988 auto Attr = ImbueAttr::NONE;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001989 if (Loc.isValid())
1990 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1991 if (Attr == ImbueAttr::NONE)
1992 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1993 switch (Attr) {
1994 case ImbueAttr::NONE:
1995 return false;
1996 case ImbueAttr::ALWAYS:
1997 Fn->addFnAttr("function-instrument", "xray-always");
1998 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00001999 case ImbueAttr::ALWAYS_ARG1:
2000 Fn->addFnAttr("function-instrument", "xray-always");
2001 Fn->addFnAttr("xray-log-args", "1");
2002 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00002003 case ImbueAttr::NEVER:
2004 Fn->addFnAttr("function-instrument", "xray-never");
2005 break;
2006 }
2007 return true;
2008}
2009
Hans Wennborg43a0f992015-01-10 01:19:48 +00002010bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00002011 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002012 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00002013 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002014
Elizabeth Andrews6593df22018-08-22 19:05:19 +00002015 if (CodeGenOpts.KeepStaticConsts) {
2016 const auto *VD = dyn_cast<VarDecl>(Global);
2017 if (VD && VD->getType().isConstQualified() &&
2018 VD->getStorageClass() == SC_Static)
2019 return true;
2020 }
2021
Hans Wennborg43a0f992015-01-10 01:19:48 +00002022 return getContext().DeclMustBeEmitted(Global);
2023}
2024
2025bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2026 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
2027 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2028 // Implicit template instantiations may change linkage if they are later
2029 // explicitly instantiated, so they should not be emitted eagerly.
2030 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00002031 if (const auto *VD = dyn_cast<VarDecl>(Global))
2032 if (Context.getInlineVariableDefinitionKind(VD) ==
2033 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2034 // A definition of an inline constexpr static data member may change
2035 // linkage later if it's redeclared outside the class.
2036 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00002037 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2038 // codegen for global variables, because they may be marked as threadprivate.
2039 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
Alexey Bataev96edb2e2018-06-25 15:32:05 +00002040 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
Alexey Bataevd01b7492018-08-15 19:45:12 +00002041 !isTypeConstant(Global->getType(), false) &&
2042 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
Samuel Antaof8b50122015-07-13 22:54:53 +00002043 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00002044
2045 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002046}
2047
John McCall7f416cc2015-09-08 08:05:57 +00002048ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00002049 const CXXUuidofExpr* E) {
2050 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2051 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00002052 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00002053 std::string Name = "_GUID_" + Uuid.lower();
2054 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00002055
David Majnemer65687602016-03-27 04:46:14 +00002056 // The UUID descriptor should be pointer aligned.
2057 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00002058
Nico Webercf4ff5862012-10-11 10:13:44 +00002059 // Look for an existing global.
2060 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00002061 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002062
Nico Weber17d3a2c2014-09-08 16:26:36 +00002063 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00002064 assert(Init && "failed to initialize as constant");
2065
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002066 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00002067 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00002068 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002069 if (supportsCOMDAT())
2070 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolaca08d242018-03-20 15:42:58 +00002071 setDSOLocal(GV);
John McCall7f416cc2015-09-08 08:05:57 +00002072 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00002073}
2074
John McCall7f416cc2015-09-08 08:05:57 +00002075ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002076 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2077 assert(AA && "No alias?");
2078
John McCall7f416cc2015-09-08 08:05:57 +00002079 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00002080 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002081
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002082 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00002083 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002084 if (Entry) {
2085 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00002086 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2087 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002088 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002089
2090 llvm::Constant *Aliasee;
2091 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002092 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2093 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00002094 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002095 else
John McCall7ec50432010-03-19 23:29:14 +00002096 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00002097 llvm::PointerType::getUnqual(DeclTy),
2098 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002099
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002100 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00002101 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2102 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002103
John McCall7f416cc2015-09-08 08:05:57 +00002104 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002105}
2106
Chris Lattnere0be0df2009-05-12 21:21:08 +00002107void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002108 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002109
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002110 // Weak references don't produce any output by themselves.
2111 if (Global->hasAttr<WeakRefAttr>())
2112 return;
2113
Chris Lattner54041692009-03-22 21:47:11 +00002114 // If this is an alias definition (which otherwise looks like a declaration)
2115 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002116 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00002117 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002118
Dmitry Polukhin85eda122016-04-11 07:48:59 +00002119 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2120 if (Global->hasAttr<IFuncAttr>())
2121 return emitIFuncDefinition(GD);
2122
Erich Keane3efe0022018-07-20 14:13:28 +00002123 // If this is a cpu_dispatch multiversion function, emit the resolver.
2124 if (Global->hasAttr<CPUDispatchAttr>())
2125 return emitCPUDispatchDefinition(GD);
2126
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002127 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002128 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00002129 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002130 if (!Global->hasAttr<CUDADeviceAttr>() &&
2131 !Global->hasAttr<CUDAGlobalAttr>() &&
2132 !Global->hasAttr<CUDAConstantAttr>() &&
2133 !Global->hasAttr<CUDASharedAttr>())
2134 return;
2135 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00002136 // We need to emit host-side 'shadows' for all global
2137 // device-side variables because the CUDA runtime needs their
2138 // size and host-side address in order to provide access to
2139 // their device-side incarnations.
2140
2141 // So device-only functions are the only things we skip.
2142 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2143 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002144 return;
Artem Belevich42e19492016-03-02 18:28:50 +00002145
2146 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2147 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00002148 }
2149 }
2150
Alexey Bataevc5b1d322016-03-04 09:22:22 +00002151 if (LangOpts.OpenMP) {
2152 // If this is OpenMP device, check if it is legal to emit this global
2153 // normally.
2154 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2155 return;
2156 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2157 if (MustBeEmitted(Global))
2158 EmitOMPDeclareReduction(DRD);
2159 return;
2160 }
2161 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002162
Chris Lattner45470942009-03-21 09:44:56 +00002163 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002164 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002165 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002166 if (!FD->doesThisDeclarationHaveABody()) {
2167 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2168 return;
2169
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002170 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00002171
2172 // Compute the function info and LLVM type.
2173 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2174 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2175
2176 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2177 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00002178 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00002179 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00002180 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002181 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002182 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich42e19492016-03-02 18:28:50 +00002183 // We need to emit device-side global CUDA variables even if a
2184 // variable does not have a definition -- we still need to define
2185 // host-side shadow for it.
2186 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2187 !VD->hasDefinition() &&
2188 (VD->hasAttr<CUDAConstantAttr>() ||
2189 VD->hasAttr<CUDADeviceAttr>());
2190 if (!MustEmitForCuda &&
2191 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00002192 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00002193 if (LangOpts.OpenMP) {
2194 // Emit declaration of the must-be-emitted declare target variable.
2195 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2196 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2197 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
2198 (void)GetAddrOfGlobalVar(VD);
2199 } else {
2200 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
2201 "link claue expected.");
2202 (void)getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
2203 }
2204 return;
2205 }
2206 }
Richard Smithd9b90092016-07-02 01:32:16 +00002207 // If this declaration may have caused an inline variable definition to
2208 // change linkage, make sure that it's emitted.
2209 if (Context.getInlineVariableDefinitionKind(VD) ==
2210 ASTContext::InlineVariableDefinitionKind::Strong)
2211 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00002212 return;
Richard Smithd9b90092016-07-02 01:32:16 +00002213 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002214 }
2215
Hans Wennborg43a0f992015-01-10 01:19:48 +00002216 // Defer code generation to first use when possible, e.g. if this is an inline
2217 // function. If the global must always be emitted, do it eagerly if possible
2218 // to benefit from cache locality.
2219 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002220 // Emit the definition if it can't be deferred.
2221 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002222 return;
2223 }
John McCall70013b62010-07-15 23:40:35 +00002224
2225 // If we're deferring emission of a C++ variable with an
2226 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002227 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00002228 cast<VarDecl>(Global)->hasInit()) {
2229 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00002230 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00002231 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00002232
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002233 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00002234 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00002235 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00002236 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002237 } else if (MustBeEmitted(Global)) {
2238 // The value must be emitted, but cannot be emitted eagerly.
2239 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00002240 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00002241 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00002242 // Otherwise, remember that we saw a deferred decl with this name. The
2243 // first use of the mangled name will cause it to move into
2244 // DeferredDeclsToEmit.
2245 DeferredDecls[MangledName] = GD;
2246 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00002247}
2248
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002249// Check if T is a class type with a destructor that's not dllimport.
2250static bool HasNonDllImportDtor(QualType T) {
2251 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2252 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2253 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2254 return true;
2255
2256 return false;
2257}
2258
Rafael Espindolac5941352011-10-26 20:41:06 +00002259namespace {
2260 struct FunctionIsDirectlyRecursive :
2261 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2262 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002263 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00002264 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002265 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2266 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002267 }
2268 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2269
2270 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002271 const FunctionDecl *FD = E->getDirectCallee();
2272 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00002273 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002274 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2275 if (Attr && Name == Attr->getLabel()) {
2276 Result = true;
2277 return false;
2278 }
2279 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00002280 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolac5941352011-10-26 20:41:06 +00002281 return true;
Eric Christopher02d5d862015-08-06 01:01:12 +00002282 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00002283 if (BuiltinName.startswith("__builtin_") &&
2284 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00002285 Result = true;
2286 return false;
2287 }
2288 return true;
2289 }
2290 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002291
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002292 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002293 struct DLLImportFunctionVisitor
2294 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2295 bool SafeToInline = true;
2296
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002297 bool shouldVisitImplicitCode() const { return true; }
2298
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002299 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002300 if (VD->getTLSKind()) {
2301 // A thread-local variable cannot be imported.
2302 SafeToInline = false;
2303 return SafeToInline;
2304 }
2305
2306 // A variable definition might imply a destructor call.
2307 if (VD->isThisDeclarationADefinition())
2308 SafeToInline = !HasNonDllImportDtor(VD->getType());
2309
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002310 return SafeToInline;
2311 }
2312
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002313 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2314 if (const auto *D = E->getTemporary()->getDestructor())
2315 SafeToInline = D->hasAttr<DLLImportAttr>();
2316 return SafeToInline;
2317 }
2318
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002319 bool VisitDeclRefExpr(DeclRefExpr *E) {
2320 ValueDecl *VD = E->getDecl();
2321 if (isa<FunctionDecl>(VD))
2322 SafeToInline = VD->hasAttr<DLLImportAttr>();
2323 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2324 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2325 return SafeToInline;
2326 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002327
Hans Wennborg1b3aee72016-09-13 22:51:42 +00002328 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2329 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2330 return SafeToInline;
2331 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002332
Hans Wennborg251c2042017-01-23 23:57:50 +00002333 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2334 CXXMethodDecl *M = E->getMethodDecl();
2335 if (!M) {
2336 // Call through a pointer to member function. This is safe to inline.
2337 SafeToInline = true;
2338 } else {
2339 SafeToInline = M->hasAttr<DLLImportAttr>();
2340 }
2341 return SafeToInline;
2342 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002343
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002344 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2345 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2346 return SafeToInline;
2347 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00002348
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002349 bool VisitCXXNewExpr(CXXNewExpr *E) {
2350 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2351 return SafeToInline;
2352 }
2353 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002354}
Rafael Espindolac5941352011-10-26 20:41:06 +00002355
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002356// isTriviallyRecursive - Check if this function calls another
2357// decl that, because of the asm attribute or the other decl being a builtin,
2358// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00002359bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002360CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2361 StringRef Name;
2362 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00002363 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002364 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2365 if (!Attr)
2366 return false;
2367 Name = Attr->getLabel();
2368 } else {
2369 Name = FD->getName();
2370 }
Rafael Espindolac5941352011-10-26 20:41:06 +00002371
David Majnemer64b0bdf2015-06-30 04:41:18 +00002372 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002373 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00002374 return Walker.Result;
2375}
2376
Hans Wennborg93f75472016-09-13 21:08:20 +00002377bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002378 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00002379 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002380 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00002381 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00002382 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002383
2384 if (F->hasAttr<DLLImportAttr>()) {
2385 // Check whether it would be safe to inline this dllimport function.
2386 DLLImportFunctionVisitor Visitor;
2387 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2388 if (!Visitor.SafeToInline)
2389 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00002390
2391 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2392 // Implicit destructor invocations aren't captured in the AST, so the
2393 // check above can't see them. Check for them manually here.
2394 for (const Decl *Member : Dtor->getParent()->decls())
2395 if (isa<FieldDecl>(Member))
2396 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2397 return false;
2398 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2399 if (HasNonDllImportDtor(B.getType()))
2400 return false;
2401 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00002402 }
2403
Rafael Espindolac5941352011-10-26 20:41:06 +00002404 // PR9614. Avoid cases where the source code is lying to us. An available
2405 // externally function should have an equivalent function somewhere else,
2406 // but a function that calls itself is clearly not equivalent to the real
2407 // implementation.
2408 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00002409 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00002410}
2411
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00002412bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2413 return CodeGenOpts.OptimizationLevel > 0;
2414}
2415
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002416void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002417 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002418
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002419 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00002420 Context.getSourceManager(),
2421 "Generating code for declaration");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002422
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002423 if (isa<FunctionDecl>(D)) {
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002424 // At -O0, don't generate IR for functions with available_externally
Douglas Gregora700f682010-07-13 06:02:28 +00002425 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002426 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00002427 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00002428
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002429 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00002430 // Make sure to emit the definition(s) before we emit the thunks.
2431 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002432 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002433 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002434 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00002435 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman49a94b12011-05-06 17:27:27 +00002436 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002437 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00002438
Douglas Gregora700f682010-07-13 06:02:28 +00002439 if (Method->isVirtual())
2440 getVTables().EmitThunks(GD);
2441
Eli Friedman49a94b12011-05-06 17:27:27 +00002442 return;
Douglas Gregora700f682010-07-13 06:02:28 +00002443 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00002444
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002445 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00002446 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002447
2448 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002449 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Jake Ehrlichc451cf22017-11-11 01:15:41 +00002450
David Blaikie83d382b2011-09-23 05:06:16 +00002451 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00002452}
2453
Andrey Bokhankocab58582015-08-31 13:20:44 +00002454static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2455 llvm::Function *NewFn);
2456
Erich Keanef353ae12018-09-13 16:58:24 +00002457static unsigned
2458TargetMVPriority(const TargetInfo &TI,
2459 const CodeGenFunction::MultiVersionResolverOption &RO) {
2460 unsigned Priority = 0;
2461 for (StringRef Feat : RO.Conditions.Features)
2462 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2463
2464 if (!RO.Conditions.Architecture.empty())
2465 Priority = std::max(
2466 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2467 return Priority;
2468}
2469
Erich Keane281d20b2018-01-08 21:34:17 +00002470void CodeGenModule::emitMultiVersionFunctions() {
2471 for (GlobalDecl GD : MultiVersionFuncs) {
Erich Keanef353ae12018-09-13 16:58:24 +00002472 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane281d20b2018-01-08 21:34:17 +00002473 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2474 getContext().forEachMultiversionedFunctionVersion(
2475 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2476 GlobalDecl CurGD{
2477 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2478 StringRef MangledName = getMangledName(CurGD);
2479 llvm::Constant *Func = GetGlobalValue(MangledName);
2480 if (!Func) {
2481 if (CurFD->isDefined()) {
2482 EmitGlobalFunctionDefinition(CurGD, nullptr);
2483 Func = GetGlobalValue(MangledName);
2484 } else {
2485 const CGFunctionInfo &FI =
2486 getTypes().arrangeGlobalDeclaration(GD);
2487 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2488 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2489 /*DontDefer=*/false, ForDefinition);
2490 }
2491 assert(Func && "This should have just been created");
2492 }
Erich Keanef353ae12018-09-13 16:58:24 +00002493
2494 const auto *TA = CurFD->getAttr<TargetAttr>();
2495 llvm::SmallVector<StringRef, 8> Feats;
2496 TA->getAddedFeatures(Feats);
2497
2498 Options.emplace_back(cast<llvm::Function>(Func),
2499 TA->getArchitecture(), Feats);
Erich Keane281d20b2018-01-08 21:34:17 +00002500 });
2501
2502 llvm::Function *ResolverFunc = cast<llvm::Function>(
2503 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
Erich Keane0a6fde42018-01-16 19:49:52 +00002504 if (supportsCOMDAT())
2505 ResolverFunc->setComdat(
2506 getModule().getOrInsertComdat(ResolverFunc->getName()));
Erich Keanef353ae12018-09-13 16:58:24 +00002507
2508 const TargetInfo &TI = getTarget();
Erich Keane281d20b2018-01-08 21:34:17 +00002509 std::stable_sort(
2510 Options.begin(), Options.end(),
Erich Keanef353ae12018-09-13 16:58:24 +00002511 [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2512 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2513 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2514 });
Erich Keane281d20b2018-01-08 21:34:17 +00002515 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002516 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane281d20b2018-01-08 21:34:17 +00002517 }
2518}
2519
Erich Keane3efe0022018-07-20 14:13:28 +00002520void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2521 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2522 assert(FD && "Not a FunctionDecl?");
2523 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2524 assert(DD && "Not a cpu_dispatch Function?");
2525 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(FD->getType());
2526
2527 StringRef ResolverName = getMangledName(GD);
2528 llvm::Type *ResolverType = llvm::FunctionType::get(
2529 llvm::PointerType::get(DeclTy,
2530 Context.getTargetAddressSpace(FD->getType())),
2531 false);
2532 auto *ResolverFunc = cast<llvm::Function>(
2533 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2534 /*ForVTable=*/false));
2535
Erich Keanef353ae12018-09-13 16:58:24 +00002536 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
Erich Keane3efe0022018-07-20 14:13:28 +00002537 const TargetInfo &Target = getTarget();
2538 for (const IdentifierInfo *II : DD->cpus()) {
2539 // Get the name of the target function so we can look it up/create it.
2540 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2541 getCPUSpecificMangling(*this, II->getName());
2542 llvm::Constant *Func = GetOrCreateLLVMFunction(
2543 MangledName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/false,
2544 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2545 llvm::SmallVector<StringRef, 32> Features;
2546 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2547 llvm::transform(Features, Features.begin(),
2548 [](StringRef Str) { return Str.substr(1); });
2549 Features.erase(std::remove_if(
2550 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2551 return !Target.validateCpuSupports(Feat);
2552 }), Features.end());
Erich Keanef353ae12018-09-13 16:58:24 +00002553 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
Erich Keane3efe0022018-07-20 14:13:28 +00002554 }
2555
2556 llvm::sort(
2557 Options.begin(), Options.end(),
Erich Keanef353ae12018-09-13 16:58:24 +00002558 [](const CodeGenFunction::MultiVersionResolverOption &LHS,
2559 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2560 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
2561 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
2562 });
Erich Keane3efe0022018-07-20 14:13:28 +00002563 CodeGenFunction CGF(*this);
Erich Keanef353ae12018-09-13 16:58:24 +00002564 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
Erich Keane3efe0022018-07-20 14:13:28 +00002565}
2566
Erich Keane281d20b2018-01-08 21:34:17 +00002567/// If an ifunc for the specified mangled name is not in the module, create and
2568/// return an llvm IFunc Function with the specified type.
2569llvm::Constant *
2570CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
Erich Keane281d20b2018-01-08 21:34:17 +00002571 const FunctionDecl *FD) {
Erich Keane3efe0022018-07-20 14:13:28 +00002572 std::string MangledName =
2573 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2574 std::string IFuncName = MangledName + ".ifunc";
Erich Keane281d20b2018-01-08 21:34:17 +00002575 if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2576 return IFuncGV;
2577
2578 // Since this is the first time we've created this IFunc, make sure
2579 // that we put this multiversioned function into the list to be
Erich Keane3efe0022018-07-20 14:13:28 +00002580 // replaced later if necessary (target multiversioning only).
2581 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2582 MultiVersionFuncs.push_back(GD);
Erich Keane281d20b2018-01-08 21:34:17 +00002583
Erich Keane3efe0022018-07-20 14:13:28 +00002584 std::string ResolverName = MangledName + ".resolver";
Erich Keane281d20b2018-01-08 21:34:17 +00002585 llvm::Type *ResolverType = llvm::FunctionType::get(
2586 llvm::PointerType::get(DeclTy,
2587 Context.getTargetAddressSpace(FD->getType())),
2588 false);
2589 llvm::Constant *Resolver =
2590 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2591 /*ForVTable=*/false);
2592 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2593 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2594 GIF->setName(IFuncName);
2595 SetCommonAttributes(FD, GIF);
2596
2597 return GIF;
2598}
2599
Chris Lattnerd4808922009-03-22 21:03:39 +00002600/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2601/// module, create and return an llvm Function with the specified type. If there
2602/// is something in the module with the specified name, return it potentially
2603/// bitcasted to the right type.
2604///
2605/// If D is non-null, it specifies a decl that correspond to this. This is used
2606/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00002607llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2608 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2609 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2610 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002611 const Decl *D = GD.getDecl();
2612
Erich Keane281d20b2018-01-08 21:34:17 +00002613 // Any attempts to use a MultiVersion function should result in retrieving
2614 // the iFunc instead. Name Mangling will handle the rest of the changes.
2615 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002616 // For the device mark the function as one that should be emitted.
2617 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
Alexey Bataev6d944102018-05-02 15:45:28 +00002618 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002619 !DontDefer && !IsForDefinition) {
Alexey Bataevbd8ff9b2018-08-30 18:56:11 +00002620 if (const FunctionDecl *FDDef = FD->getDefinition()) {
2621 GlobalDecl GDDef;
2622 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2623 GDDef = GlobalDecl(CD, GD.getCtorType());
2624 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2625 GDDef = GlobalDecl(DD, GD.getDtorType());
2626 else
2627 GDDef = GlobalDecl(FDDef);
2628 EmitGlobal(GDDef);
2629 }
Alexey Bataevd7ff6d62018-05-07 14:50:05 +00002630 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002631
Erich Keane3efe0022018-07-20 14:13:28 +00002632 if (FD->isMultiVersion()) {
2633 const auto *TA = FD->getAttr<TargetAttr>();
2634 if (TA && TA->isDefaultVersion())
2635 UpdateMultiVersionNames(GD, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00002636 if (!IsForDefinition)
Erich Keane3efe0022018-07-20 14:13:28 +00002637 return GetOrCreateMultiVersionIFunc(GD, Ty, FD);
Erich Keane281d20b2018-01-08 21:34:17 +00002638 }
2639 }
2640
Chris Lattnera85d68e2009-03-21 09:25:43 +00002641 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002642 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002643 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002644 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002645 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002646 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002647 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002648 }
2649
Hans Wennborg0a20f542014-08-29 00:16:06 +00002650 // Handle dropped DLL attributes.
Rafael Espindolac9643d82018-03-29 16:45:18 +00002651 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
Hans Wennborg0a20f542014-08-29 00:16:06 +00002652 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
Rafael Espindolac9643d82018-03-29 16:45:18 +00002653 setDSOLocal(Entry);
2654 }
Hans Wennborg0a20f542014-08-29 00:16:06 +00002655
Andrey Bokhankocab58582015-08-31 13:20:44 +00002656 // If there are two attempts to define the same mangled name, issue an
2657 // error.
2658 if (IsForDefinition && !Entry->isDeclaration()) {
2659 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002660 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2661 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002662 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2663 (GD.getCanonicalDecl().getDecl() !=
2664 OtherGD.getCanonicalDecl().getDecl()) &&
2665 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00002666 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2667 << MangledName;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002668 getDiags().Report(OtherGD.getDecl()->getLocation(),
2669 diag::note_previous_definition);
2670 }
2671 }
2672
2673 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2674 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002675 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002676 }
Mike Stump11289f42009-09-09 15:08:12 +00002677
Chris Lattnera85d68e2009-03-21 09:25:43 +00002678 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002679 // (If function is requested for a definition, we always need to create a new
2680 // function, not just return a bitcast.)
2681 if (!IsForDefinition)
2682 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002683 }
Mike Stump11289f42009-09-09 15:08:12 +00002684
Eli Friedmancc522d92009-11-09 05:07:37 +00002685 // This function doesn't have a complete type (for example, the return
2686 // type is an incomplete struct). Use a fake type instead, and make
2687 // sure not to try to set attributes.
2688 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002689
Chris Lattner2192fe52011-07-18 04:24:23 +00002690 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002691 if (isa<llvm::FunctionType>(Ty)) {
2692 FTy = cast<llvm::FunctionType>(Ty);
2693 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002694 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002695 IsIncompleteFunction = true;
2696 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002697
2698 llvm::Function *F =
2699 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2700 Entry ? StringRef() : MangledName, &getModule());
2701
2702 // If we already created a function with the same mangled name (but different
2703 // type) before, take its name and add it to the list of functions to be
2704 // replaced with F at the end of CodeGen.
2705 //
2706 // This happens if there is a prototype for a function (e.g. "int f()") and
2707 // then a definition of a different type (e.g. "int f(int x)").
2708 if (Entry) {
2709 F->takeName(Entry);
2710
2711 // This might be an implementation of a function without a prototype, in
2712 // which case, try to do special replacement of calls which match the new
2713 // prototype. The really key thing here is that we also potentially drop
2714 // arguments from the call site so as to make a direct call, which makes the
2715 // inliner happier and suppresses a number of optimizer warnings (!) about
2716 // dropping arguments.
2717 if (!Entry->use_empty()) {
2718 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2719 Entry->removeDeadConstantUsers();
2720 }
2721
2722 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2723 F, Entry->getType()->getElementType()->getPointerTo());
2724 addGlobalValReplacement(Entry, BC);
2725 }
2726
John McCall7ec50432010-03-19 23:29:14 +00002727 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002728 if (D)
Rafael Espindoladeb10be2018-02-07 19:04:41 +00002729 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00002730 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2731 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002732 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002733 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002734
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002735 if (!DontDefer) {
2736 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2737 // each other bottoming out with the base dtor. Therefore we emit non-base
2738 // dtors on usage, even if there is no dtor definition in the TU.
2739 if (D && isa<CXXDestructorDecl>(D) &&
2740 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2741 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002742 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002743
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002744 // This is the first use or definition of a mangled name. If there is a
2745 // deferred decl with this name, remember that we need to emit it at the end
2746 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002747 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002748 if (DDI != DeferredDecls.end()) {
2749 // Move the potentially referenced deferred decl to the
2750 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2751 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002752 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002753 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002754
2755 // Otherwise, there are cases we have to worry about where we're
2756 // using a declaration for which we must emit a definition but where
2757 // we might not find a top-level definition:
2758 // - member functions defined inline in their classes
2759 // - friend functions defined inline in some class
2760 // - special member functions with implicit definitions
2761 // If we ever change our AST traversal to walk into class methods,
2762 // this will be unnecessary.
2763 //
2764 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002765 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002766 } else if (getLangOpts().CPlusPlus && D) {
2767 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002768 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2769 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002770 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002771 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002772 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002773 break;
2774 }
John McCall357d0f32010-12-15 04:00:32 +00002775 }
Richard Smith46bb5812014-08-01 01:56:39 +00002776 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002777 }
Chris Lattner45470942009-03-21 09:44:56 +00002778 }
Mike Stump11289f42009-09-09 15:08:12 +00002779
John McCalld06fb862010-04-28 00:00:30 +00002780 // Make sure the result is of the requested type.
2781 if (!IsIncompleteFunction) {
2782 assert(F->getType()->getElementType() == Ty);
2783 return F;
2784 }
2785
Chris Lattnera5f58b02011-07-09 17:41:47 +00002786 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002787 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002788}
2789
Chris Lattnerd4808922009-03-22 21:03:39 +00002790/// GetAddrOfFunction - Return the address of the given function. If Ty is
2791/// non-null, then this function will use the specified type if it has to
2792/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002793llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002794 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002795 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002796 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002797 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002798 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002799 if (!Ty) {
2800 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2801 auto CanonTy = Context.getCanonicalType(FD->getType());
2802 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2803 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002804
Reid Kleckner28103252018-03-16 22:20:57 +00002805 // Devirtualized destructor calls may come through here instead of via
2806 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2807 // of the complete destructor when necessary.
2808 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2809 if (getTarget().getCXXABI().isMicrosoft() &&
2810 GD.getDtorType() == Dtor_Complete &&
2811 DD->getParent()->getNumVBases() == 0)
2812 GD = GlobalDecl(DD, Dtor_Base);
2813 }
2814
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002815 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002816 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002817 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002818 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002819}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002820
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002821static const FunctionDecl *
2822GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2823 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2824 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2825
2826 IdentifierInfo &CII = C.Idents.get(Name);
2827 for (const auto &Result : DC->lookup(&CII))
2828 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2829 return FD;
2830
2831 if (!C.getLangOpts().CPlusPlus)
2832 return nullptr;
2833
2834 // Demangle the premangled name from getTerminateFn()
2835 IdentifierInfo &CXXII =
Reid Klecknerfb931542018-03-16 20:36:49 +00002836 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002837 ? C.Idents.get("terminate")
2838 : C.Idents.get(Name);
2839
2840 for (const auto &N : {"__cxxabiv1", "std"}) {
2841 IdentifierInfo &NS = C.Idents.get(N);
2842 for (const auto &Result : DC->lookup(&NS)) {
2843 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2844 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2845 for (const auto &Result : LSD->lookup(&NS))
2846 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2847 break;
2848
2849 if (ND)
2850 for (const auto &Result : ND->lookup(&CXXII))
2851 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2852 return FD;
2853 }
2854 }
2855
2856 return nullptr;
2857}
2858
Chris Lattnerd4808922009-03-22 21:03:39 +00002859/// CreateRuntimeFunction - Create a new runtime function with the specified
2860/// type and name.
2861llvm::Constant *
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002862CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002863 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002864 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002865 llvm::Constant *C =
2866 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002867 /*DontDefer=*/false, /*IsThunk=*/false,
2868 ExtraAttrs);
2869
2870 if (auto *F = dyn_cast<llvm::Function>(C)) {
2871 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00002872 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002873
2874 if (!Local && getTriple().isOSBinFormatCOFF() &&
Martell Maloneb22e6002017-11-04 02:15:49 +00002875 !getCodeGenOpts().LTOVisibilityPublicStd &&
2876 !getTriple().isWindowsGNUEnvironment()) {
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002877 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2878 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2879 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2880 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2881 }
2882 }
Rafael Espindola3c9be622018-03-20 20:27:30 +00002883 setDSOLocal(F);
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002884 }
2885 }
2886
John McCall882987f2013-02-28 19:01:20 +00002887 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00002888}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002889
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002890/// CreateBuiltinFunction - Create a new builtin function with the specified
2891/// type and name.
2892llvm::Constant *
Reid Klecknerde864822017-03-21 16:57:30 +00002893CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2894 llvm::AttributeList ExtraAttrs) {
Rafael Espindola1193c372018-03-22 18:03:13 +00002895 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002896}
2897
Richard Smithe070fd22012-02-17 06:48:11 +00002898/// isTypeConstant - Determine whether an object of this type can be emitted
2899/// as a constant.
2900///
2901/// If ExcludeCtor is true, the duration when the object's constructor runs
2902/// will not be considered. The caller will need to verify that the object is
2903/// not written to during its construction.
2904bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2905 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00002906 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00002907
David Blaikiebbafb8a2012-03-11 07:00:24 +00002908 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00002909 if (const CXXRecordDecl *Record
2910 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2911 return ExcludeCtor && !Record->hasMutableFields() &&
2912 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00002913 }
Richard Smithe070fd22012-02-17 06:48:11 +00002914
Eli Friedmanb095e152009-12-11 21:23:03 +00002915 return true;
2916}
2917
Chris Lattnerd4808922009-03-22 21:03:39 +00002918/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2919/// create and return an llvm GlobalVariable with the specified type. If there
2920/// is something in the module with the specified name, return it potentially
2921/// bitcasted to the right type.
2922///
2923/// If D is non-null, it specifies a decl that correspond to this. This is used
2924/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002925///
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002926/// If IsForDefinition is true, it is guaranteed that an actual global with
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002927/// type Ty will be returned, not conversion of a variable with the same
2928/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00002929llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002930CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00002931 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002932 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00002933 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00002934 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002935 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00002936 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002937 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002938 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002939 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002940 }
2941
Hans Wennborg0a20f542014-08-29 00:16:06 +00002942 // Handle dropped DLL attributes.
2943 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2944 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2945
Alexey Bataev03f270c2018-03-30 18:31:07 +00002946 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2947 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
2948
Chris Lattnerd4808922009-03-22 21:03:39 +00002949 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00002950 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00002951
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002952 // If there are two attempts to define the same mangled name, issue an
2953 // error.
2954 if (IsForDefinition && !Entry->isDeclaration()) {
2955 GlobalDecl OtherGD;
2956 const VarDecl *OtherD;
2957
2958 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2959 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00002960 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002961 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2962 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2963 OtherD->hasInit() &&
2964 DiagnosedConflictingDefinitions.insert(D).second) {
Richard Smithb5345102018-05-30 01:52:16 +00002965 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2966 << MangledName;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002967 getDiags().Report(OtherGD.getDecl()->getLocation(),
2968 diag::note_previous_definition);
2969 }
2970 }
2971
Chris Lattner3bfce182009-03-21 08:03:33 +00002972 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00002973 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2974 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2975
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002976 // (If global is requested for a definition, we always need to create a new
2977 // global, not just return a bitcast.)
2978 if (!IsForDefinition)
2979 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00002980 }
Mike Stump11289f42009-09-09 15:08:12 +00002981
Yaxun Liucbf647c2017-07-08 13:24:52 +00002982 auto AddrSpace = GetGlobalVarAddressSpace(D);
2983 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2984
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002985 auto *GV = new llvm::GlobalVariable(
2986 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002987 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Yaxun Liucbf647c2017-07-08 13:24:52 +00002988 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00002989
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002990 // If we already created a global with the same mangled name (but different
2991 // type) before, take its name and remove it from its parent.
2992 if (Entry) {
2993 GV->takeName(Entry);
2994
2995 if (!Entry->use_empty()) {
2996 llvm::Constant *NewPtrForOldDecl =
2997 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2998 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2999 }
3000
3001 Entry->eraseFromParent();
3002 }
3003
Chris Lattner45470942009-03-21 09:44:56 +00003004 // This is the first use or definition of a mangled name. If there is a
3005 // deferred decl with this name, remember that we need to emit it at the end
3006 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00003007 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00003008 if (DDI != DeferredDecls.end()) {
3009 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3010 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00003011 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00003012 DeferredDecls.erase(DDI);
3013 }
Mike Stump11289f42009-09-09 15:08:12 +00003014
Chris Lattner3bfce182009-03-21 08:03:33 +00003015 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00003016 if (D) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003017 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3018 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3019
Mike Stump18bb9282009-05-16 07:57:57 +00003020 // FIXME: This code is overly simple and should be merged with other global
3021 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00003022 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00003023
Ulrich Weigand46084382015-04-21 17:27:59 +00003024 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3025
Jake Ehrlichba874ad2017-11-29 00:54:20 +00003026 setLinkageForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00003027
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003028 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00003029 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003030 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00003031 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00003032 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00003033
Rafael Espindola3dd49812018-02-23 00:22:15 +00003034 setGVProperties(GV, D);
3035
Hans Wennborgfeedf852013-11-21 00:15:56 +00003036 // If required by the ABI, treat declarations of static data members with
3037 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003038 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00003039 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00003040 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00003041
Erich Keane99fdfb62017-09-26 23:42:34 +00003042 // Emit section information for extern variables.
3043 if (D->hasExternalStorage()) {
3044 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3045 GV->setSection(SA->getName());
3046 }
3047
Robert Lyttonf80d6882014-05-02 09:33:30 +00003048 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003049 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00003050 D->getLanguageLinkage() == CLanguageLinkage &&
3051 D->getType().isConstant(Context) &&
3052 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3053 GV->setSection(".cp.rodata");
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003054
3055 // Check if we a have a const declaration with an initializer, we may be
3056 // able to emit it as available_externally to expose it's value to the
3057 // optimizer.
3058 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3059 D->getType().isConstQualified() && !GV->hasInitializer() &&
3060 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3061 const auto *Record =
3062 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3063 bool HasMutableFields = Record && Record->hasMutableFields();
3064 if (!HasMutableFields) {
3065 const VarDecl *InitDecl;
3066 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3067 if (InitExpr) {
3068 ConstantEmitter emitter(*this);
3069 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3070 if (Init) {
3071 auto *InitType = Init->getType();
3072 if (GV->getType()->getElementType() != InitType) {
3073 // The type of the initializer does not match the definition.
3074 // This happens when an initializer has a different type from
3075 // the type of the global (because of padding at the end of a
3076 // structure for instance).
3077 GV->setName(StringRef());
3078 // Make a new global with the correct type, this is now guaranteed
3079 // to work.
3080 auto *NewGV = cast<llvm::GlobalVariable>(
3081 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3082
3083 // Erase the old global, since it is no longer used.
George Burgess IV00f70bd2018-03-01 05:43:23 +00003084 GV->eraseFromParent();
Mehdi Amini7cb1b302017-09-05 03:58:35 +00003085 GV = NewGV;
3086 } else {
3087 GV->setInitializer(Init);
3088 GV->setConstant(true);
3089 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3090 }
3091 emitter.finalize(GV);
3092 }
3093 }
3094 }
3095 }
Chris Lattnerd4808922009-03-22 21:03:39 +00003096 }
Mike Stump11289f42009-09-09 15:08:12 +00003097
Alexander Richardson6d989432017-10-15 18:48:14 +00003098 LangAS ExpectedAS =
Yaxun Liucbf647c2017-07-08 13:24:52 +00003099 D ? D->getType().getAddressSpace()
Alexander Richardson6d989432017-10-15 18:48:14 +00003100 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
Benjamin Kramer6fbfdec2017-07-08 14:14:57 +00003101 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3102 Ty->getPointerAddressSpace());
Yaxun Liucbf647c2017-07-08 13:24:52 +00003103 if (AddrSpace != ExpectedAS)
3104 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3105 ExpectedAS, Ty);
Matt Arsenault00e65b22013-11-15 02:19:52 +00003106
3107 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00003108}
3109
Andrey Bokhankocab58582015-08-31 13:20:44 +00003110llvm::Constant *
3111CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00003112 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003113 const Decl *D = GD.getDecl();
3114 if (isa<CXXConstructorDecl>(D))
3115 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00003116 getFromCtorType(GD.getCtorType()),
3117 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3118 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003119 else if (isa<CXXDestructorDecl>(D))
3120 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00003121 getFromDtorType(GD.getDtorType()),
3122 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3123 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003124 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003125 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003126 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00003127 auto Ty = getTypes().GetFunctionType(*FInfo);
3128 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3129 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003130 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00003131 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3132 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3133 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3134 IsForDefinition);
3135 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00003136 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003137 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00003138}
Chris Lattnerd4808922009-03-22 21:03:39 +00003139
David Greenbe0c5b62018-09-12 14:09:06 +00003140llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3141 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3142 unsigned Alignment) {
Anders Carlssonda80af32011-01-29 18:20:20 +00003143 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00003144 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00003145
Anders Carlssonda80af32011-01-29 18:20:20 +00003146 if (GV) {
3147 // Check if the variable has the right type.
3148 if (GV->getType()->getElementType() == Ty)
3149 return GV;
3150
3151 // Because C++ name mangling, the only way we can end up with an already
3152 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00003153 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00003154 OldGV = GV;
3155 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003156
Anders Carlssonda80af32011-01-29 18:20:20 +00003157 // Create a new variable.
3158 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00003159 Linkage, nullptr, Name);
3160
Anders Carlssonda80af32011-01-29 18:20:20 +00003161 if (OldGV) {
3162 // Replace occurrences of the old variable if needed.
3163 GV->takeName(OldGV);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003164
Anders Carlssonda80af32011-01-29 18:20:20 +00003165 if (!OldGV->use_empty()) {
3166 llvm::Constant *NewPtrForOldDecl =
3167 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3168 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3169 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00003170
Anders Carlssonda80af32011-01-29 18:20:20 +00003171 OldGV->eraseFromParent();
3172 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00003173
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003174 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3175 !GV->hasAvailableExternallyLinkage())
3176 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00003177
David Greenbe0c5b62018-09-12 14:09:06 +00003178 GV->setAlignment(Alignment);
3179
Anders Carlssonda80af32011-01-29 18:20:20 +00003180 return GV;
3181}
3182
Chris Lattnerd4808922009-03-22 21:03:39 +00003183/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3184/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00003185/// then it will be created with the specified type instead of whatever the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003186/// normal requested type would be. If IsForDefinition is true, it is guaranteed
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003187/// that an actual global with type Ty will be returned, not conversion of a
3188/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00003189llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003190 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00003191 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00003192 assert(D->hasGlobalStorage() && "Not a global variable");
3193 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00003194 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00003195 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00003196
Chris Lattner2192fe52011-07-18 04:24:23 +00003197 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003198 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00003199
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003200 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003201 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00003202}
3203
3204/// CreateRuntimeVariable - Create a new runtime global variable with the
3205/// specified type and name.
3206llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00003207CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003208 StringRef Name) {
Rafael Espindola6ab4ae42018-03-21 01:30:16 +00003209 auto *Ret =
3210 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3211 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3212 return Ret;
Chris Lattnerd4808922009-03-22 21:03:39 +00003213}
3214
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003215void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3216 assert(!D->getInit() && "Cannot emit definite definitions here!");
3217
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003218 StringRef MangledName = getMangledName(D);
3219 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3220
3221 // We already have a definition, not declaration, with the same mangled name.
3222 // Emitting of declaration is not required (and actually overwrites emitted
3223 // definition).
3224 if (GV && !GV->isDeclaration())
3225 return;
3226
3227 // If we have not seen a reference to this variable yet, place it into the
3228 // deferred declarations table to be emitted if needed later.
3229 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003230 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003231 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00003232 }
3233
3234 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00003235 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003236}
3237
Chris Lattner2192fe52011-07-18 04:24:23 +00003238CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00003239 return Context.toCharUnitsFromBits(
3240 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00003241}
3242
Alexander Richardson6d989432017-10-15 18:48:14 +00003243LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3244 LangAS AddrSpace = LangAS::Default;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003245 if (LangOpts.OpenCL) {
Alexander Richardson6d989432017-10-15 18:48:14 +00003246 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003247 assert(AddrSpace == LangAS::opencl_global ||
3248 AddrSpace == LangAS::opencl_constant ||
3249 AddrSpace == LangAS::opencl_local ||
3250 AddrSpace >= LangAS::FirstTargetAddressSpace);
3251 return AddrSpace;
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003252 }
3253
Yaxun Liucbf647c2017-07-08 13:24:52 +00003254 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3255 if (D && D->hasAttr<CUDAConstantAttr>())
3256 return LangAS::cuda_constant;
3257 else if (D && D->hasAttr<CUDASharedAttr>())
3258 return LangAS::cuda_shared;
Yaxun Liua4005e12018-07-28 03:05:25 +00003259 else if (D && D->hasAttr<CUDADeviceAttr>())
3260 return LangAS::cuda_device;
3261 else if (D && D->getType().isConstQualified())
3262 return LangAS::cuda_constant;
Yaxun Liucbf647c2017-07-08 13:24:52 +00003263 else
3264 return LangAS::cuda_device;
3265 }
3266
3267 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
Peter Collingbournef44bdf92012-05-20 21:08:35 +00003268}
3269
Yaxun Liudaceb1e2018-05-14 19:20:12 +00003270LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3271 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3272 if (LangOpts.OpenCL)
3273 return LangAS::opencl_constant;
3274 if (auto AS = getTarget().getConstantAddressSpace())
3275 return AS.getValue();
3276 return LangAS::Default;
3277}
3278
3279// In address space agnostic languages, string literals are in default address
3280// space in AST. However, certain targets (e.g. amdgcn) request them to be
3281// emitted in constant address space in LLVM IR. To be consistent with other
3282// parts of AST, string literal global variables in constant address space
3283// need to be casted to default address space before being put into address
3284// map and referenced by other part of CodeGen.
3285// In OpenCL, string literals are in constant address space in AST, therefore
3286// they should not be casted to default address space.
3287static llvm::Constant *
3288castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3289 llvm::GlobalVariable *GV) {
3290 llvm::Constant *Cast = GV;
3291 if (!CGM.getLangOpts().OpenCL) {
3292 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3293 if (AS != LangAS::Default)
3294 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3295 CGM, GV, AS.getValue(), LangAS::Default,
3296 GV->getValueType()->getPointerTo(
3297 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3298 }
3299 }
3300 return Cast;
3301}
3302
Richard Smithdf931ce2013-04-06 05:00:46 +00003303template<typename SomeDecl>
3304void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3305 llvm::GlobalValue *GV) {
3306 if (!getLangOpts().CPlusPlus)
3307 return;
3308
3309 // Must have 'used' attribute, or else inline assembly can't rely on
3310 // the name existing.
3311 if (!D->template hasAttr<UsedAttr>())
3312 return;
3313
3314 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00003315 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00003316 return;
3317
3318 // Must be in an extern "C" context. Entities declared directly within
3319 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003320 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00003321 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00003322 return;
3323
3324 // OK, this is an internal linkage entity inside an extern "C" linkage
3325 // specification. Make a note of that so we can give it the "expected"
3326 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00003327 std::pair<StaticExternCMap::iterator, bool> R =
3328 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00003329
3330 // If we have multiple internal linkage entities with the same name
3331 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00003332 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00003333 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00003334}
3335
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003336static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3337 if (!CGM.supportsCOMDAT())
3338 return false;
3339
3340 if (D.hasAttr<SelectAnyAttr>())
3341 return true;
3342
3343 GVALinkage Linkage;
3344 if (auto *VD = dyn_cast<VarDecl>(&D))
3345 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3346 else
3347 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3348
3349 switch (Linkage) {
3350 case GVA_Internal:
3351 case GVA_AvailableExternally:
3352 case GVA_StrongExternal:
3353 return false;
3354 case GVA_DiscardableODR:
3355 case GVA_StrongODR:
3356 return true;
3357 }
3358 llvm_unreachable("No such linkage");
3359}
3360
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003361void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3362 llvm::GlobalObject &GO) {
3363 if (!shouldBeInCOMDAT(*this, D))
3364 return;
3365 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3366}
3367
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003368/// Pass IsTentative as true if you want to create a tentative definition.
3369void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3370 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003371 // OpenCL global variables of sampler type are translated to function calls,
3372 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003373 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003374 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3375 return;
3376
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00003377 // If this is OpenMP device, check if it is legal to emit this global
3378 // normally.
3379 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3380 OpenMPRuntime->emitTargetGlobalVariable(D))
3381 return;
3382
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003383 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00003384 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3385 bool NeedsGlobalCtor = false;
3386 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00003387
Richard Smithdafff942012-01-14 04:30:29 +00003388 const VarDecl *InitDecl;
3389 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003390
John McCallde0fe072017-08-15 21:42:52 +00003391 Optional<ConstantEmitter> emitter;
3392
Artem Belevich97c01c32016-02-02 22:29:48 +00003393 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3394 // as part of their declaration." Sema has already checked for
3395 // error cases, so we just need to set Init to UndefValue.
3396 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3397 D->hasAttr<CUDASharedAttr>())
Jingyue Wu284ebe22015-08-22 05:49:28 +00003398 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00003399 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00003400 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00003401 // implicitly initialized with { 0 }.
3402 //
3403 // Note that tentative definitions are only emitted at the end of
3404 // a translation unit, so they should never have incomplete
3405 // type. In addition, EmitTentativeDefinition makes sure that we
3406 // never attempt to emit a tentative definition if a real one
3407 // exists. A use may still exists, however, so we still may need
3408 // to do a RAUW.
3409 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00003410 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003411 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00003412 initializedGlobalDecl = GlobalDecl(D);
John McCallde0fe072017-08-15 21:42:52 +00003413 emitter.emplace(*this);
3414 Init = emitter->tryEmitForInitializer(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00003415
Fariborz Jahanian63628032012-06-26 16:06:38 +00003416 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00003417 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00003418 if (D->getType()->isReferenceType())
3419 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00003420
David Blaikiebbafb8a2012-03-11 07:00:24 +00003421 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003422 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00003423 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00003424 } else {
3425 ErrorUnsupported(D, "static initializer");
3426 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3427 }
John McCall70013b62010-07-15 23:40:35 +00003428 } else {
3429 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00003430 // initializer position (just in case this entry was delayed) if we
3431 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003432 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00003433 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00003434 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003435 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003436
Chris Lattner2192fe52011-07-18 04:24:23 +00003437 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003438 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00003439 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00003440
Chris Lattner149927c2009-03-21 09:16:30 +00003441 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003442 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00003443 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00003444 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3445 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00003446 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00003447 Entry = CE->getOperand(0);
3448 }
Mike Stump11289f42009-09-09 15:08:12 +00003449
Chris Lattner149927c2009-03-21 09:16:30 +00003450 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003451 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003452
Chris Lattner149927c2009-03-21 09:16:30 +00003453 // We have a definition after a declaration with the wrong type.
3454 // We must make a new GlobalVariable* and update everything that used OldGV
3455 // (a declaration or tentative definition) with the new GlobalVariable*
3456 // (which will be a definition).
3457 //
3458 // This happens if there is a prototype for a global (e.g.
3459 // "extern int x[];") and then a definition of a different type (e.g.
3460 // "int x[10];"). This also happens when an initializer has a different type
3461 // from the type of the global (this happens with unions).
Yaxun Liucbf647c2017-07-08 13:24:52 +00003462 if (!GV || GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00003463 GV->getType()->getAddressSpace() !=
Yaxun Liucbf647c2017-07-08 13:24:52 +00003464 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
Mike Stump11289f42009-09-09 15:08:12 +00003465
John McCall7ec50432010-03-19 23:29:14 +00003466 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003467 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00003468
Chris Lattner149927c2009-03-21 09:16:30 +00003469 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00003470 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00003471 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00003472
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003473 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00003474 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00003475 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00003476 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00003477
3478 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00003479 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00003480 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00003481
Richard Smithdf931ce2013-04-06 05:00:46 +00003482 MaybeHandleStaticInExternC(D, GV);
3483
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003484 if (D->hasAttr<AnnotateAttr>())
3485 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00003486
Artem Belevich42e19492016-03-02 18:28:50 +00003487 // Set the llvm linkage type as appropriate.
3488 llvm::GlobalValue::LinkageTypes Linkage =
3489 getLLVMLinkageVarDefinition(D, GV->isConstant());
3490
Jingyue Wu284ebe22015-08-22 05:49:28 +00003491 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3492 // the device. [...]"
3493 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3494 // __device__, declares a variable that: [...]
3495 // Is accessible from all the threads within the grid and from the host
3496 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3497 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00003498 if (GV && LangOpts.CUDA) {
3499 if (LangOpts.CUDAIsDevice) {
3500 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3501 GV->setExternallyInitialized(true);
3502 } else {
3503 // Host-side shadows of external declarations of device-side
3504 // global variables become internal definitions. These have to
3505 // be internal in order to prevent name conflicts with global
3506 // host variables with the same name in a different TUs.
3507 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3508 Linkage = llvm::GlobalValue::InternalLinkage;
3509
3510 // Shadow variables and their properties must be registered
3511 // with CUDA runtime.
3512 unsigned Flags = 0;
3513 if (!D->hasDefinition())
3514 Flags |= CGCUDARuntime::ExternDeviceVar;
3515 if (D->hasAttr<CUDAConstantAttr>())
3516 Flags |= CGCUDARuntime::ConstantDeviceVar;
3517 getCUDARuntime().registerDeviceVar(*GV, Flags);
3518 } else if (D->hasAttr<CUDASharedAttr>())
3519 // __shared__ variables are odd. Shadows do get created, but
3520 // they are not registered with the CUDA runtime, so they
3521 // can't really be used to access their device-side
3522 // counterparts. It's not clear yet whether it's nvcc's bug or
3523 // a feature, but we've got to do the same for compatibility.
3524 Linkage = llvm::GlobalValue::InternalLinkage;
3525 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00003526 }
John McCallde0fe072017-08-15 21:42:52 +00003527
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003528 GV->setInitializer(Init);
John McCallde0fe072017-08-15 21:42:52 +00003529 if (emitter) emitter->finalize(GV);
Chris Lattnerf49573d2009-08-05 05:20:29 +00003530
3531 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00003532 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3533 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00003534
Hans Wennborg899ded92014-10-16 20:52:46 +00003535 // If it is in a read-only section, mark it 'constant'.
3536 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3537 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3538 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3539 GV->setConstant(true);
3540 }
3541
Ken Dyck160146e2010-01-27 17:10:57 +00003542 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00003543
David Majnemer35ab3282014-06-11 04:08:55 +00003544
Manman Ren68150262015-11-11 22:42:31 +00003545 // On Darwin, if the normal linkage of a C++ thread_local variable is
3546 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3547 // copies within a linkage unit; otherwise, the backing variable has
3548 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00003549 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00003550 // variable. This is to preserve the ability to change the implementation
3551 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00003552 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00003553 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00003554 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3555 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00003556 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00003557
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003558 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00003559 if (D->hasAttr<DLLImportAttr>())
3560 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3561 else if (D->hasAttr<DLLExportAttr>())
3562 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00003563 else
3564 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00003565
Yaxun Liu402804b2016-12-15 08:09:08 +00003566 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00003567 // common vars aren't constant even if declared const.
3568 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00003569 // Tentative definition of global variables may be initialized with
3570 // non-zero null pointers. In this case they should have weak linkage
3571 // since common linkage must have zero initializer and must not have
3572 // explicit section therefore cannot have non-zero initial value.
3573 if (!GV->getInitializer()->isNullValue())
3574 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3575 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00003576
Rafael Espindola502f65a2014-05-05 20:21:03 +00003577 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00003578
David Majnemerbb525f7c2014-10-15 22:38:23 +00003579 if (D->getTLSKind() && !GV->isThreadLocal()) {
3580 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00003581 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00003582 setTLSMode(GV, *D);
3583 }
3584
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003585 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003586
John McCallcdf7ef52010-11-06 09:44:32 +00003587 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00003588 if (NeedsGlobalCtor || NeedsGlobalDtor)
3589 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00003590
Alexey Samsonov4b8de112014-08-01 21:35:28 +00003591 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00003592
Sanjiv Gupta158143a2008-06-05 08:59:10 +00003593 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00003594 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003595 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00003596 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00003597}
Chris Lattner09153c02007-06-22 18:48:09 +00003598
David Majnemerc017d362014-08-05 00:01:13 +00003599static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00003600 CodeGenModule &CGM, const VarDecl *D,
3601 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00003602 // Don't give variables common linkage if -fno-common was specified unless it
3603 // was overridden by a NoCommon attribute.
3604 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3605 return true;
3606
3607 // C11 6.9.2/2:
3608 // A declaration of an identifier for an object that has file scope without
3609 // an initializer, and without a storage-class specifier or with the
3610 // storage-class specifier static, constitutes a tentative definition.
3611 if (D->getInit() || D->hasExternalStorage())
3612 return true;
3613
3614 // A variable cannot be both common and exist in a section.
3615 if (D->hasAttr<SectionAttr>())
3616 return true;
3617
Javed Absar2a67c9e2017-06-05 10:11:57 +00003618 // A variable cannot be both common and exist in a section.
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003619 // We don't try to determine which is the right section in the front-end.
Javed Absar2a67c9e2017-06-05 10:11:57 +00003620 // If no specialized section name is applicable, it will resort to default.
3621 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3622 D->hasAttr<PragmaClangDataSectionAttr>() ||
3623 D->hasAttr<PragmaClangRodataSectionAttr>())
3624 return true;
3625
David Majnemer9832a3d2014-04-10 16:53:16 +00003626 // Thread local vars aren't considered common linkage.
3627 if (D->getTLSKind())
3628 return true;
3629
3630 // Tentative definitions marked with WeakImportAttr are true definitions.
3631 if (D->hasAttr<WeakImportAttr>())
3632 return true;
3633
Nico Weber608e7682015-04-15 23:04:24 +00003634 // A variable cannot be both common and exist in a comdat.
3635 if (shouldBeInCOMDAT(CGM, *D))
3636 return true;
3637
Sanjay Patel2f9303a2016-06-30 21:02:40 +00003638 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00003639 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00003640 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00003641 if (D->hasAttr<AlignedAttr>())
3642 return true;
3643 QualType VarType = D->getType();
3644 if (Context.isAlignmentRequired(VarType))
3645 return true;
3646
3647 if (const auto *RT = VarType->getAs<RecordType>()) {
3648 const RecordDecl *RD = RT->getDecl();
3649 for (const FieldDecl *FD : RD->fields()) {
3650 if (FD->isBitField())
3651 continue;
3652 if (FD->hasAttr<AlignedAttr>())
3653 return true;
3654 if (Context.isAlignmentRequired(FD->getType()))
3655 return true;
3656 }
3657 }
3658 }
David Majnemerc017d362014-08-05 00:01:13 +00003659
David Majnemer9832a3d2014-04-10 16:53:16 +00003660 return false;
3661}
3662
Hans Wennborg1a3a0742014-05-14 19:54:53 +00003663llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00003664 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003665 if (Linkage == GVA_Internal)
3666 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003667
3668 if (D->hasAttr<WeakAttr>()) {
3669 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003670 return llvm::GlobalVariable::WeakODRLinkage;
3671 else
3672 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003673 }
3674
3675 // We are guaranteed to have a strong definition somewhere else,
3676 // so we can use available_externally linkage.
3677 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00003678 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00003679
David Majnemer27d69db2014-04-28 22:17:59 +00003680 // Note that Apple's kernel linker doesn't support symbol
3681 // coalescing, so we need to avoid linkonce and weak linkages there.
3682 // Normally, this means we just map to internal, but for explicit
3683 // instantiations we'll map to external.
3684
3685 // In C++, the compiler has to emit a definition in every translation unit
3686 // that references the function. We should use linkonce_odr because
3687 // a) if all references in this translation unit are optimized away, we
3688 // don't need to codegen it. b) if the function persists, it needs to be
3689 // merged with other definitions. c) C++ has the ODR, so we know the
3690 // definition is dependable.
3691 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00003692 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00003693 : llvm::Function::InternalLinkage;
3694
3695 // An explicit instantiation of a template has weak linkage, since
3696 // explicit instantiations can occur in multiple translation units
3697 // and must all be equivalent. However, we are not allowed to
3698 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00003699 //
3700 // We don't currently support CUDA device code spread out across multiple TUs,
3701 // so say that CUDA templates are either external (for kernels) or internal.
3702 // This lets llvm perform aggressive inter-procedural optimizations.
3703 if (Linkage == GVA_StrongODR) {
3704 if (Context.getLangOpts().AppleKext)
3705 return llvm::Function::ExternalLinkage;
3706 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3707 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3708 : llvm::Function::InternalLinkage;
3709 return llvm::Function::WeakODRLinkage;
3710 }
David Majnemer27d69db2014-04-28 22:17:59 +00003711
David Majnemer27d69db2014-04-28 22:17:59 +00003712 // C++ doesn't have tentative definitions and thus cannot have common
3713 // linkage.
3714 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00003715 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00003716 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00003717 return llvm::GlobalVariable::CommonLinkage;
3718
David Majnemer27d69db2014-04-28 22:17:59 +00003719 // selectany symbols are externally visible, so use weak instead of
3720 // linkonce. MSVC optimizes away references to const selectany globals, so
3721 // all definitions should be the same and ODR linkage should be used.
3722 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3723 if (D->hasAttr<SelectAnyAttr>())
3724 return llvm::GlobalVariable::WeakODRLinkage;
3725
3726 // Otherwise, we have strong external linkage.
3727 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00003728 return llvm::GlobalVariable::ExternalLinkage;
3729}
3730
David Majnemer27d69db2014-04-28 22:17:59 +00003731llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3732 const VarDecl *VD, bool IsConstant) {
3733 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00003734 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00003735}
3736
John McCall49954ca2012-12-12 22:21:47 +00003737/// Replace the uses of a function that was declared with a non-proto type.
3738/// We want to silently drop extra arguments from call sites
3739static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3740 llvm::Function *newFn) {
3741 // Fast path.
3742 if (old->use_empty()) return;
3743
3744 llvm::Type *newRetTy = newFn->getReturnType();
3745 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00003746 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00003747
3748 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3749 ui != ue; ) {
3750 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003751 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00003752
3753 // Recognize and replace uses of bitcasts. Most calls to
3754 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003755 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00003756 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3757 replaceUsesOfNonProtoConstant(bitcast, newFn);
3758 continue;
3759 }
3760
3761 // Recognize calls to the function.
3762 llvm::CallSite callSite(user);
3763 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00003764 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00003765
3766 // If the return types don't match exactly, then we can't
3767 // transform this call unless it's dead.
3768 if (callSite->getType() != newRetTy && !callSite->use_empty())
3769 continue;
3770
3771 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00003772 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
Reid Klecknerde864822017-03-21 16:57:30 +00003773 llvm::AttributeList oldAttrs = callSite.getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00003774
John McCall49954ca2012-12-12 22:21:47 +00003775 // If the function was passed too few arguments, don't transform.
3776 unsigned newNumArgs = newFn->arg_size();
3777 if (callSite.arg_size() < newNumArgs) continue;
3778
3779 // If extra arguments were passed, we silently drop them.
3780 // If any of the types mismatch, we don't transform.
3781 unsigned argNo = 0;
3782 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00003783 for (llvm::Argument &A : newFn->args()) {
3784 if (callSite.getArgument(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00003785 dontTransform = true;
3786 break;
3787 }
3788
3789 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00003790 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00003791 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00003792 }
3793 if (dontTransform)
3794 continue;
3795
John McCall49954ca2012-12-12 22:21:47 +00003796 // Okay, we can transform this. Create the new call instruction and copy
3797 // over the required information.
3798 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3799
David Majnemer0b17d442015-12-15 21:27:59 +00003800 // Copy over any operand bundles.
3801 callSite.getOperandBundlesAsDefs(newBundles);
3802
John McCall49954ca2012-12-12 22:21:47 +00003803 llvm::CallSite newCall;
3804 if (callSite.isCall()) {
David Majnemer0b17d442015-12-15 21:27:59 +00003805 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003806 callSite.getInstruction());
3807 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003808 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00003809 newCall = llvm::InvokeInst::Create(newFn,
3810 oldInvoke->getNormalDest(),
3811 oldInvoke->getUnwindDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003812 newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003813 callSite.getInstruction());
3814 }
3815 newArgs.clear(); // for the next iteration
3816
3817 if (!newCall->getType()->isVoidTy())
3818 newCall->takeName(callSite.getInstruction());
Reid Kleckner7f720332017-04-13 00:58:09 +00003819 newCall.setAttributes(llvm::AttributeList::get(
3820 newFn->getContext(), oldAttrs.getFnAttributes(),
3821 oldAttrs.getRetAttributes(), newArgAttrs));
John McCall49954ca2012-12-12 22:21:47 +00003822 newCall.setCallingConv(callSite.getCallingConv());
3823
3824 // Finally, remove the old call, replacing any uses with the new one.
3825 if (!callSite->use_empty())
3826 callSite->replaceAllUsesWith(newCall.getInstruction());
3827
3828 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003829 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003830 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003831
John McCall49954ca2012-12-12 22:21:47 +00003832 callSite->eraseFromParent();
3833 }
3834}
3835
Chris Lattner36797ab2009-05-05 06:16:31 +00003836/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3837/// implement a function with no prototype, e.g. "int foo() {}". If there are
3838/// existing call uses of the old function in the module, this adjusts them to
3839/// call the new function directly.
3840///
3841/// This is not just a cleanup: the always_inline pass requires direct calls to
3842/// functions to be able to inline them. If there is a bitcast in the way, it
3843/// won't inline them. Instcombine normally deletes these calls, but it isn't
3844/// run at -O0.
3845static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3846 llvm::Function *NewFn) {
3847 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003848 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003849
John McCall49954ca2012-12-12 22:21:47 +00003850 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003851}
3852
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003853void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00003854 auto DK = VD->isThisDeclarationADefinition();
3855 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3856 return;
3857
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003858 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3859 // If we have a definition, this might be a deferred decl. If the
3860 // instantiation is explicit, make sure we emit it at the end.
3861 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3862 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003863
3864 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00003865}
Daniel Dunbar9c426522008-07-29 23:18:29 +00003866
Rafael Espindolacd7743b2013-12-09 16:01:03 +00003867void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3868 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003869 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00003870
John McCall46288ef2011-03-09 08:12:35 +00003871 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00003872 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3873 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00003874
Chris Lattnereb7466d2009-05-12 20:58:15 +00003875 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003876 if (!GV || (GV->getType()->getElementType() != Ty))
3877 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3878 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00003879 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00003880
Andrey Bokhankocab58582015-08-31 13:20:44 +00003881 // Already emitted.
3882 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00003883 return;
Mike Stump11289f42009-09-09 15:08:12 +00003884
John McCall8e7cb6d2010-11-02 21:04:24 +00003885 // We need to set linkage and visibility on the function before
3886 // generating code for it because various parts of IR generation
3887 // want to propagate this information down (e.g. to local static
3888 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003889 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00003890 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003891
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003892 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Rafael Espindolab7350042018-03-01 00:35:47 +00003893 setGVProperties(Fn, GD);
John McCall8e7cb6d2010-11-02 21:04:24 +00003894
Richard Smithdf931ce2013-04-06 05:00:46 +00003895 MaybeHandleStaticInExternC(D, Fn);
3896
Yaxun Liu4306f202018-04-20 17:01:03 +00003897
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003898 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003899
John McCalla738c252011-03-09 04:27:21 +00003900 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00003901
Rafael Espindolae4e78132018-03-01 00:00:02 +00003902 setNonAliasAttributes(GD, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00003903 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00003904
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003905 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003906 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003907 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003908 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003909 if (D->hasAttr<AnnotateAttr>())
3910 AddGlobalAnnotations(D, Fn);
Erich Keane3efe0022018-07-20 14:13:28 +00003911
3912 if (D->isCPUSpecificMultiVersion()) {
3913 auto *Spec = D->getAttr<CPUSpecificAttr>();
3914 // If there is another specific version we need to emit, do so here.
3915 if (Spec->ActiveArgIndex + 1 < Spec->cpus_size()) {
3916 ++Spec->ActiveArgIndex;
3917 EmitGlobalFunctionDefinition(GD, nullptr);
3918 }
3919 }
Daniel Dunbar9c426522008-07-29 23:18:29 +00003920}
3921
John McCall7ec50432010-03-19 23:29:14 +00003922void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003923 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003924 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00003925 assert(AA && "Not an alias?");
3926
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003927 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00003928
Hal Finkel0e2b9752015-09-04 21:49:21 +00003929 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003930 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00003931 return;
3932 }
3933
John McCall7ec50432010-03-19 23:29:14 +00003934 // If there is a definition in the module, then it wins over the alias.
3935 // This is dubious, but allow it to be safe. Just ignore the alias.
3936 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3937 if (Entry && !Entry->isDeclaration())
3938 return;
3939
Rafael Espindola208b5c02013-10-22 19:26:13 +00003940 Aliases.push_back(GD);
3941
Chris Lattner2192fe52011-07-18 04:24:23 +00003942 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00003943
3944 // Create a reference to the named value. This ensures that it is emitted
3945 // if a deferred decl.
3946 llvm::Constant *Aliasee;
3947 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00003948 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00003949 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00003950 else
John McCall7ec50432010-03-19 23:29:14 +00003951 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00003952 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00003953 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00003954
3955 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00003956 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00003957 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00003958
Chris Lattner54041692009-03-22 21:47:11 +00003959 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00003960 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003961 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00003962 return;
3963 }
3964
John McCall7ec50432010-03-19 23:29:14 +00003965 assert(Entry->isDeclaration());
3966
Chris Lattner54041692009-03-22 21:47:11 +00003967 // If there is a declaration in the module, then we had an extern followed
3968 // by the alias, as in:
3969 // extern int test6();
3970 // ...
3971 // int test6() __attribute__((alias("test7")));
3972 //
3973 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00003974 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003975
Owen Andersonade90fd2009-07-29 18:54:39 +00003976 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00003977 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00003978 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00003979 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00003980 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00003981 }
Mike Stump11289f42009-09-09 15:08:12 +00003982
Daniel Dunbar38932572009-04-14 08:05:55 +00003983 // Set attributes which are particular to an alias; this is a
3984 // specialization of the attributes which may be set on a global
3985 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00003986 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3987 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00003988 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3989 }
3990
David Majnemerbb525f7c2014-10-15 22:38:23 +00003991 if (const auto *VD = dyn_cast<VarDecl>(D))
3992 if (VD->getTLSKind())
3993 setTLSMode(GA, *VD);
3994
Rafael Espindolab7350042018-03-01 00:35:47 +00003995 SetCommonAttributes(GD, GA);
Chris Lattner54041692009-03-22 21:47:11 +00003996}
3997
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003998void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3999 const auto *D = cast<ValueDecl>(GD.getDecl());
4000 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4001 assert(IFA && "Not an ifunc?");
4002
4003 StringRef MangledName = getMangledName(GD);
4004
4005 if (IFA->getResolver() == MangledName) {
4006 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4007 return;
4008 }
4009
4010 // Report an error if some definition overrides ifunc.
4011 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4012 if (Entry && !Entry->isDeclaration()) {
4013 GlobalDecl OtherGD;
4014 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4015 DiagnosedConflictingDefinitions.insert(GD).second) {
Richard Smithb5345102018-05-30 01:52:16 +00004016 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4017 << MangledName;
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004018 Diags.Report(OtherGD.getDecl()->getLocation(),
4019 diag::note_previous_definition);
4020 }
4021 return;
4022 }
4023
4024 Aliases.push_back(GD);
4025
4026 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4027 llvm::Constant *Resolver =
4028 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4029 /*ForVTable=*/false);
4030 llvm::GlobalIFunc *GIF =
4031 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4032 "", Resolver, &getModule());
4033 if (Entry) {
4034 if (GIF->getResolver() == Entry) {
4035 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4036 return;
4037 }
4038 assert(Entry->isDeclaration());
4039
4040 // If there is a declaration in the module, then we had an extern followed
4041 // by the ifunc, as in:
4042 // extern int test();
4043 // ...
4044 // int test() __attribute__((ifunc("resolver")));
4045 //
4046 // Remove it and replace uses of it with the ifunc.
4047 GIF->takeName(Entry);
4048
4049 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4050 Entry->getType()));
4051 Entry->eraseFromParent();
4052 } else
4053 GIF->setName(MangledName);
4054
Rafael Espindola75c649c2018-03-01 00:06:55 +00004055 SetCommonAttributes(GD, GIF);
Dmitry Polukhin85eda122016-04-11 07:48:59 +00004056}
4057
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004058llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00004059 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00004060 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00004061 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00004062}
Chris Lattner1eec6602007-08-31 04:31:45 +00004063
David Blaikie2e804282015-04-05 22:47:07 +00004064static llvm::StringMapEntry<llvm::GlobalVariable *> &
4065GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4066 const StringLiteral *Literal, bool TargetIsLSB,
4067 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004068 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004069 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00004070
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004071 // Check for simple case.
4072 if (!Literal->containsNonAsciiOrNull()) {
4073 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00004074 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00004075 }
4076
Bill Wendling82b87f12012-03-30 00:26:17 +00004077 // Otherwise, convert the UTF8 literals into a string of shorts.
4078 IsUTF16 = true;
4079
Justin Lebar90910552016-09-30 00:38:45 +00004080 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4081 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4082 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00004083
Justin Lebar90910552016-09-30 00:38:45 +00004084 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4085 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00004086
Daniel Dunbar91ade142009-07-23 23:41:22 +00004087 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00004088 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00004089
Bill Wendling82b87f12012-03-30 00:26:17 +00004090 // Add an explicit null.
4091 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00004092 return *Map.insert(std::make_pair(
4093 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4094 (StringLength + 1) * 2),
4095 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00004096}
4097
John McCall7f416cc2015-09-08 08:05:57 +00004098ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00004099CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4100 unsigned StringLength = 0;
4101 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00004102 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4103 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4104 getDataLayout().isLittleEndian(), isUTF16,
4105 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004106
David Blaikie13156b62014-11-19 03:06:06 +00004107 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00004108 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00004109
Chris Lattnerece04092012-02-07 00:39:47 +00004110 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00004111 llvm::Constant *Zeros[] = { Zero, Zero };
Kristina Brooks34e24d52018-09-25 22:27:40 +00004112
Chris Lattneraa64ca22009-07-16 16:48:25 +00004113 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00004114 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00004115 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00004116 Ty = llvm::ArrayType::get(Ty, 0);
Kristina Brooks34e24d52018-09-25 22:27:40 +00004117 llvm::Constant *C =
4118 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
4119
4120 if (getTriple().isOSBinFormatELF() || getTriple().isOSBinFormatCOFF()) {
4121 llvm::GlobalValue *GV = nullptr;
4122
4123 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4124 IdentifierInfo &II = getContext().Idents.get(GV->getName());
4125 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
4126 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004127
Kristina Brooks34e24d52018-09-25 22:27:40 +00004128 const VarDecl *VD = nullptr;
4129 for (const auto &Result : DC->lookup(&II))
4130 if ((VD = dyn_cast<VarDecl>(Result)))
4131 break;
4132
4133 if (getTriple().isOSBinFormatELF()) {
4134 if (!VD)
4135 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4136 }
4137 else {
4138 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
4139 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4140 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4141 } else {
4142 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4143 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4144 }
4145 }
4146
4147 setDSOLocal(GV);
Saleem Abdulrasool49766342016-06-01 04:22:24 +00004148 }
4149 }
Kristina Brooks34e24d52018-09-25 22:27:40 +00004150
Daniel Dunbard644ad62008-08-23 18:37:06 +00004151 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00004152 CFConstantStringClassRef =
Kristina Brooks34e24d52018-09-25 22:27:40 +00004153 llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004154 }
Mike Stump11289f42009-09-09 15:08:12 +00004155
Anders Carlssonc2480a52008-11-15 18:54:24 +00004156 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00004157
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004158 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00004159
John McCall23c9dc62016-11-28 22:18:27 +00004160 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00004161 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00004162
Anders Carlssonb04ea612007-08-21 00:21:21 +00004163 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004164 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00004165
Anders Carlssonb04ea612007-08-21 00:21:21 +00004166 // Flags.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004167 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
Anders Carlsson157c3212009-08-16 05:55:31 +00004168
Anders Carlssonb04ea612007-08-21 00:21:21 +00004169 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00004170 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00004171 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00004172 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00004173 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4174 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00004175 C = llvm::ConstantDataArray::get(VMContext, Arr);
4176 } else {
David Blaikie13156b62014-11-19 03:06:06 +00004177 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00004178 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00004179
Bill Wendling86131f22012-01-10 08:46:39 +00004180 // Note: -fwritable-strings doesn't make the backing store strings of
4181 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004182 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00004183 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4184 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004185 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00004186 // Don't enforce the target's minimum global alignment, since the only use
4187 // of the string is via this class initializer.
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004188 CharUnits Align = isUTF16
4189 ? getContext().getTypeAlignInChars(getContext().ShortTy)
4190 : getContext().getTypeAlignInChars(getContext().CharTy);
4191 GV->setAlignment(Align.getQuantity());
4192
4193 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4194 // Without it LLVM can merge the string with a non unnamed_addr one during
4195 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00004196 if (getTriple().isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004197 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4198 : "__TEXT,__cstring,cstring_literals");
Kristina Brooks34e24d52018-09-25 22:27:40 +00004199 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4200 // the static linker to adjust permissions to read-only later on.
4201 else if (getTriple().isOSBinFormatELF())
4202 GV->setSection(".rodata");
4203
Bill Wendling82b87f12012-03-30 00:26:17 +00004204 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004205 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00004206 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00004207
Bill Wendling82b87f12012-03-30 00:26:17 +00004208 if (isUTF16)
4209 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004210 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4211 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00004212
Anders Carlssonb04ea612007-08-21 00:21:21 +00004213 // String length.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004214 auto Ty = getTypes().ConvertType(getContext().LongTy);
4215 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00004216
John McCall7f416cc2015-09-08 08:05:57 +00004217 CharUnits Alignment = getPointerAlign();
4218
Anders Carlssonb04ea612007-08-21 00:21:21 +00004219 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00004220 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4221 /*isConstant=*/false,
4222 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00004223 switch (getTriple().getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004224 case llvm::Triple::UnknownObjectFormat:
4225 llvm_unreachable("unknown file format");
4226 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004227 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00004228 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00004229 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00004230 break;
4231 case llvm::Triple::MachO:
4232 GV->setSection("__DATA,__cfstring");
4233 break;
4234 }
David Blaikie13156b62014-11-19 03:06:06 +00004235 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00004236
John McCall7f416cc2015-09-08 08:05:57 +00004237 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00004238}
Chris Lattnerfb300092007-11-28 05:34:05 +00004239
Bob Haarmanc6c9b8f2017-09-11 22:11:57 +00004240bool CodeGenModule::getExpressionLocationsEnabled() const {
4241 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4242}
4243
Douglas Gregor636e2002011-08-09 17:23:49 +00004244QualType CodeGenModule::getObjCFastEnumerationStateType() {
4245 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00004246 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00004247 D->startDefinition();
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004248
Douglas Gregor636e2002011-08-09 17:23:49 +00004249 QualType FieldTypes[] = {
4250 Context.UnsignedLongTy,
4251 Context.getPointerType(Context.getObjCIdType()),
4252 Context.getPointerType(Context.UnsignedLongTy),
4253 Context.getConstantArrayType(Context.UnsignedLongTy,
4254 llvm::APInt(32, 5), ArrayType::Normal, 0)
4255 };
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004256
Douglas Gregor636e2002011-08-09 17:23:49 +00004257 for (size_t i = 0; i < 4; ++i) {
4258 FieldDecl *Field = FieldDecl::Create(Context,
4259 D,
4260 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004261 SourceLocation(), nullptr,
4262 FieldTypes[i], /*TInfo=*/nullptr,
4263 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00004264 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00004265 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00004266 Field->setAccess(AS_public);
4267 D->addDecl(Field);
4268 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004269
Douglas Gregor636e2002011-08-09 17:23:49 +00004270 D->completeDefinition();
4271 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4272 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004273
Douglas Gregor636e2002011-08-09 17:23:49 +00004274 return ObjCFastEnumerationStateType;
4275}
4276
Eli Friedmanfcec6302011-11-01 02:23:42 +00004277llvm::Constant *
4278CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4279 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004280
Eli Friedmanfcec6302011-11-01 02:23:42 +00004281 // Don't emit it as the address of the string, emit the string data itself
4282 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00004283 if (E->getCharByteWidth() == 1) {
4284 SmallString<64> Str(E->getString());
4285
4286 // Resize the string to the right size, which is indicated by its type.
4287 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4288 Str.resize(CAT->getSize().getZExtValue());
4289 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4290 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004291
4292 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00004293 llvm::Type *ElemTy = AType->getElementType();
4294 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00004295
4296 // Wide strings have either 2-byte or 4-byte elements.
4297 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4298 SmallVector<uint16_t, 32> Elements;
4299 Elements.reserve(NumElements);
4300
4301 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4302 Elements.push_back(E->getCodeUnit(i));
4303 Elements.resize(NumElements);
4304 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00004305 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004306
Chris Lattner02cb1712012-02-06 22:52:04 +00004307 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4308 SmallVector<uint32_t, 32> Elements;
4309 Elements.reserve(NumElements);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004310
Chris Lattner02cb1712012-02-06 22:52:04 +00004311 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4312 Elements.push_back(E->getCodeUnit(i));
4313 Elements.resize(NumElements);
4314 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00004315}
4316
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004317static llvm::GlobalVariable *
4318GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4319 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00004320 CharUnits Alignment) {
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004321 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4322 CGM.getStringLiteralAddressSpace());
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004323
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004324 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004325 // Create a global variable for this string
4326 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004327 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4328 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00004329 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00004330 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004331 if (GV->isWeakForLinker()) {
4332 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4333 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4334 }
Rafael Espindola0d40f122018-03-20 20:42:55 +00004335 CGM.setDSOLocal(GV);
Rafael Espindolad9b26d52015-01-16 20:32:35 +00004336
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004337 return GV;
4338}
4339
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004340/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4341/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00004342ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00004343CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4344 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00004345 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00004346
Richard Smith00db2f12014-07-29 21:20:12 +00004347 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4348 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00004349 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004350 Entry = &ConstantStringMap[C];
4351 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004352 if (Alignment.getQuantity() > GV->getAlignment())
4353 GV->setAlignment(Alignment.getQuantity());
4354 return ConstantAddress(GV, Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00004355 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00004356 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00004357
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004358 SmallString<256> MangledNameBuffer;
4359 StringRef GlobalVariableName;
4360 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00004361
Reid Kleckner7a368962018-09-06 18:25:39 +00004362 // Mangle the string literal if that's how the ABI merges duplicate strings.
4363 // Don't do it if they are writable, since we don't want writes in one TU to
4364 // affect strings in another.
4365 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4366 !LangOpts.WritableStrings) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004367 llvm::raw_svector_ostream Out(MangledNameBuffer);
4368 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004369 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4370 GlobalVariableName = MangledNameBuffer;
4371 } else {
4372 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00004373 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00004374 }
4375
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004376 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4377 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004378 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00004379
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00004380 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4381 QualType());
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004382
4383 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4384 Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004385}
4386
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004387/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4388/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00004389ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004390CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4391 std::string Str;
4392 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00004393
4394 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00004395}
4396
Alexey Samsonovadc90372014-06-04 20:25:57 +00004397/// GetAddrOfConstantCString - Returns a pointer to a character array containing
4398/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004399/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00004400ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4401 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00004402 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00004403 CharUnits Alignment =
4404 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004405
Richard Smith00db2f12014-07-29 21:20:12 +00004406 llvm::Constant *C =
4407 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4408
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004409 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00004410 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004411 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00004412 Entry = &ConstantStringMap[C];
4413 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00004414 if (Alignment.getQuantity() > GV->getAlignment())
4415 GV->setAlignment(Alignment.getQuantity());
4416 return ConstantAddress(GV, Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004417 }
4418 }
4419
Daniel Dunbar08b216a2009-03-31 23:42:16 +00004420 // Get the default prefix if a name wasn't specified.
4421 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00004422 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00004423 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00004424 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4425 GlobalName, Alignment);
4426 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00004427 *Entry = GV;
Yaxun Liudaceb1e2018-05-14 19:20:12 +00004428
4429 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4430 Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00004431}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00004432
John McCall7f416cc2015-09-08 08:05:57 +00004433ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00004434 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00004435 assert((E->getStorageDuration() == SD_Static ||
4436 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004437 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00004438
4439 // If we're not materializing a subobject of the temporary, keep the
4440 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00004441 QualType MaterializedType = Init->getType();
4442 if (Init == E->GetTemporaryExpr())
4443 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004444
John McCall7f416cc2015-09-08 08:05:57 +00004445 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4446
David Majnemer2dcef9e2015-08-13 23:50:15 +00004447 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00004448 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004449
4450 // FIXME: If an externally-visible declaration extends multiple temporaries,
4451 // we need to give each temporary the same name in every translation unit (and
4452 // we also need to make the temporaries externally-visible).
4453 SmallString<256> Name;
4454 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00004455 getCXXABI().getMangleContext().mangleReferenceTemporary(
4456 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00004457
Craig Topper8a13c412014-05-21 05:09:00 +00004458 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004459 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00004460 // We might have a cached constant initializer for this temporary. Note
4461 // that this might have a different value from the value computed by
4462 // evaluating the initializer if the surrounding constant expression
4463 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00004464 Value = getContext().getMaterializedTemporaryValue(E, false);
4465 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00004466 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00004467 }
4468
Richard Smitha509f2f2013-06-14 03:07:01 +00004469 // Try evaluating it now, it might have a constant initializer.
4470 Expr::EvalResult EvalResult;
4471 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4472 !EvalResult.hasSideEffects())
4473 Value = &EvalResult.Val;
4474
Alexander Richardson6d989432017-10-15 18:48:14 +00004475 LangAS AddrSpace =
John McCallde0fe072017-08-15 21:42:52 +00004476 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4477
4478 Optional<ConstantEmitter> emitter;
Craig Topper8a13c412014-05-21 05:09:00 +00004479 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00004480 bool Constant = false;
4481 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00004482 if (Value) {
4483 // The temporary has a constant initializer, use it.
John McCallde0fe072017-08-15 21:42:52 +00004484 emitter.emplace(*this);
4485 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4486 MaterializedType);
Richard Smitha509f2f2013-06-14 03:07:01 +00004487 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4488 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00004489 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00004490 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00004491 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00004492 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00004493 }
4494
4495 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00004496 llvm::GlobalValue::LinkageTypes Linkage =
4497 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004498 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4499 const VarDecl *InitVD;
4500 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4501 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4502 // Temporaries defined inside a class get linkonce_odr linkage because the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004503 // class can be defined in multiple translation units.
David Majnemerc9a9c7a2015-02-19 19:25:17 +00004504 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4505 } else {
4506 // There is no need for this temporary to have external linkage if the
4507 // VarDecl has external linkage.
4508 Linkage = llvm::GlobalVariable::InternalLinkage;
4509 }
4510 }
Yaxun Liucbf647c2017-07-08 13:24:52 +00004511 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004512 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00004513 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
Yaxun Liucbf647c2017-07-08 13:24:52 +00004514 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
John McCallde0fe072017-08-15 21:42:52 +00004515 if (emitter) emitter->finalize(GV);
Rafael Espindola699f5d62018-02-07 22:15:33 +00004516 setGVProperties(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00004517 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00004518 if (supportsCOMDAT() && GV->isWeakForLinker())
4519 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00004520 if (VD->getTLSKind())
4521 setTLSMode(GV, *VD);
Yaxun Liucbf647c2017-07-08 13:24:52 +00004522 llvm::Constant *CV = GV;
4523 if (AddrSpace != LangAS::Default)
4524 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4525 *this, GV, AddrSpace, LangAS::Default,
4526 Type->getPointerTo(
4527 getContext().getTargetAddressSpace(LangAS::Default)));
4528 MaterializedGlobalTemporaryMap[E] = CV;
4529 return ConstantAddress(CV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00004530}
4531
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004532/// EmitObjCPropertyImplementations - Emit information for synthesized
4533/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00004534void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004535 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00004536 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004537 // Dynamic is just for type-checking.
4538 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4539 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4540
4541 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00004542 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004543 // we want, that just indicates if the decl came from a
4544 // property. What we want to know is if the method is defined in
4545 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004546 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004547 CodeGenFunction(*this).GenerateObjCGetter(
4548 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004549 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004550 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00004551 CodeGenFunction(*this).GenerateObjCSetter(
4552 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004553 }
4554 }
4555}
4556
John McCall6a4fa522011-03-22 07:05:39 +00004557static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004558 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4559 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00004560 ivar; ivar = ivar->getNextIvar())
4561 if (ivar->getType().isDestructedType())
4562 return true;
4563
4564 return false;
4565}
4566
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004567static bool AllTrivialInitializers(CodeGenModule &CGM,
4568 ObjCImplementationDecl *D) {
4569 CodeGenFunction CGF(CGM);
4570 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4571 E = D->init_end(); B != E; ++B) {
4572 CXXCtorInitializer *CtorInitExp = *B;
4573 Expr *Init = CtorInitExp->getInit();
4574 if (!CGF.isTrivialInitializer(Init))
4575 return false;
4576 }
4577 return true;
4578}
4579
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004580/// EmitObjCIvarInitializations - Emit information for ivar initialization
4581/// for an implementation.
4582void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00004583 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4584 if (needsDestructMethod(D)) {
4585 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4586 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4587 ObjCMethodDecl *DTORMethod =
4588 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00004589 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004590 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004591 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004592 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00004593 D->addInstanceMethod(DTORMethod);
4594 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00004595 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00004596 }
4597
4598 // If the implementation doesn't have any ivar initializers, we don't need
4599 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00004600 if (D->getNumIvarInitializers() == 0 ||
4601 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004602 return;
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004603
John McCall6a4fa522011-03-22 07:05:39 +00004604 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4605 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004606 // The constructor returns 'self'.
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004607 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004608 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004609 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004610 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00004611 getContext().getObjCIdType(),
4612 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004613 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00004614 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00004615 /*isImplicitlyDeclared=*/true,
4616 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004617 ObjCMethodDecl::Required);
4618 D->addInstanceMethod(CTORMethod);
4619 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00004620 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004621}
4622
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004623// EmitLinkageSpec - Emit all declarations in a linkage spec.
4624void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00004625 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4626 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004627 ErrorUnsupported(LSD, "linkage spec");
4628 return;
4629 }
4630
Richard Smith8df390f2016-09-08 23:14:54 +00004631 EmitDeclContext(LSD);
4632}
4633
4634void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4635 for (auto *I : DC->decls()) {
4636 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4637 // are themselves considered "top-level", so EmitTopLevelDecl on an
4638 // ObjCImplDecl does not recursively visit them. We need to do that in
4639 // case they're nested inside another construct (LinkageSpecDecl /
4640 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00004641 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00004642 for (auto *M : OID->methods())
4643 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004644 }
Richard Smith8df390f2016-09-08 23:14:54 +00004645
Aaron Ballman629afae2014-03-07 19:56:05 +00004646 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00004647 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004648}
4649
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004650/// EmitTopLevelDecl - Emit code for a single top level declaration.
4651void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00004652 // Ignore dependent declarations.
Richard Smith32b615c2018-02-01 00:28:36 +00004653 if (D->isTemplated())
Douglas Gregor70d83e22009-06-29 17:30:29 +00004654 return;
Mike Stump11289f42009-09-09 15:08:12 +00004655
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004656 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00004657 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00004658 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004659 case Decl::Function:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004660 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00004661 // Always provide some coverage mapping
4662 // even for the functions that aren't emitted.
4663 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004664 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004665
Richard Smithada08882017-04-19 21:15:45 +00004666 case Decl::CXXDeductionGuide:
4667 // Function-like, but does not result in code emission.
4668 break;
4669
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004670 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00004671 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004672 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00004673 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00004674 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4675 for (auto *B : DD->bindings())
4676 if (auto *HD = B->getHoldingVar())
4677 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004678 break;
4679
John McCall32f44bd2011-04-12 01:01:22 +00004680 // Indirect fields from global anonymous structs and unions can be
4681 // ignored; only the actual variable requires IR gen support.
4682 case Decl::IndirectField:
4683 break;
4684
Anders Carlssonf7475242009-04-15 15:55:24 +00004685 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004686 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00004687 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004688 break;
Richard Smithe1246122017-11-03 01:26:01 +00004689 case Decl::ClassTemplateSpecialization: {
4690 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4691 if (DebugInfo &&
4692 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4693 Spec->hasDefinition())
4694 DebugInfo->completeTemplateDefinition(*Spec);
4695 } LLVM_FALLTHROUGH;
Richard Smith62f19e72016-06-25 00:15:56 +00004696 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00004697 if (DebugInfo) {
4698 if (auto *ES = D->getASTContext().getExternalSource())
4699 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4700 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4701 }
Richard Smith62f19e72016-06-25 00:15:56 +00004702 // Emit any static data members, they may be definitions.
4703 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4704 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4705 EmitTopLevelDecl(I);
4706 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00004707 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00004708 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004709 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00004710 case Decl::VarTemplate:
4711 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00004712 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00004713 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00004714 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00004715 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00004716 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00004717 case Decl::Using: // using X; [C++]
4718 if (CGDebugInfo *DI = getModuleDebugInfo())
4719 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4720 return;
David Blaikief121b932013-05-20 22:50:41 +00004721 case Decl::NamespaceAlias:
4722 if (CGDebugInfo *DI = getModuleDebugInfo())
4723 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4724 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00004725 case Decl::UsingDirective: // using namespace X; [C++]
4726 if (CGDebugInfo *DI = getModuleDebugInfo())
4727 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4728 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00004729 case Decl::CXXConstructor:
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00004730 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00004731 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004732 case Decl::CXXDestructor:
Reid Klecknere7de47e2013-07-22 13:51:44 +00004733 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00004734 break;
Anders Carlsson87835432009-06-11 21:22:55 +00004735
4736 case Decl::StaticAssert:
4737 // Nothing to do.
4738 break;
4739
Anders Carlssonf7475242009-04-15 15:55:24 +00004740 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00004741
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004742 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00004743 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00004744 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00004745 break;
4746
Douglas Gregorf6102672012-01-01 21:23:57 +00004747 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004748 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00004749 if (Proto->isThisDeclarationADefinition())
4750 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004751 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00004752 }
Jake Ehrlichc451cf22017-11-11 01:15:41 +00004753
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004754 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004755 // Categories have properties but don't support synthesize so we
4756 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00004757 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004758 break;
4759
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004760 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004761 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00004762 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00004763 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00004764 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00004765 // Emit global variable debug information.
4766 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00004767 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00004768 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4769 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004770 break;
Mike Stump11289f42009-09-09 15:08:12 +00004771 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004772 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004773 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004774 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004775 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004776 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4777 break;
4778 }
Mike Stump11289f42009-09-09 15:08:12 +00004779 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00004780 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004781 break;
4782
Nico Weber66220292016-03-02 17:28:48 +00004783 case Decl::PragmaComment: {
4784 const auto *PCD = cast<PragmaCommentDecl>(D);
4785 switch (PCD->getCommentKind()) {
4786 case PCK_Unknown:
4787 llvm_unreachable("unexpected pragma comment kind");
4788 case PCK_Linker:
4789 AppendLinkerOptions(PCD->getArg());
4790 break;
4791 case PCK_Lib:
Saleem Abdulrasoolfd4db532018-02-07 01:46:46 +00004792 if (getTarget().getTriple().isOSBinFormatELF() &&
4793 !getTarget().getTriple().isPS4())
4794 AddELFLibDirective(PCD->getArg());
4795 else
4796 AddDependentLib(PCD->getArg());
Nico Weber66220292016-03-02 17:28:48 +00004797 break;
4798 case PCK_Compiler:
4799 case PCK_ExeStr:
4800 case PCK_User:
4801 break; // We ignore all of these.
4802 }
4803 break;
4804 }
4805
Nico Webercbbaeb12016-03-02 19:28:54 +00004806 case Decl::PragmaDetectMismatch: {
4807 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4808 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4809 break;
4810 }
4811
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00004812 case Decl::LinkageSpec:
4813 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004814 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004815
4816 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00004817 // File-scope asm is ignored during device-side CUDA compilation.
4818 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4819 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004820 // File-scope asm is ignored during device-side OpenMP compilation.
4821 if (LangOpts.OpenMPIsDevice)
4822 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004823 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00004824 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004825 break;
4826 }
Mike Stump11289f42009-09-09 15:08:12 +00004827
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004828 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004829 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004830
Richard Smithdc1f0422016-07-20 19:10:16 +00004831 // If we've already imported this module, we're done.
4832 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00004833 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004834
Richard Smithdc1f0422016-07-20 19:10:16 +00004835 // Emit debug information for direct imports.
4836 if (!Import->getImportedOwningModule()) {
4837 if (CGDebugInfo *DI = getModuleDebugInfo())
4838 DI->EmitImportDecl(*Import);
4839 }
4840
Manman Ren3b5dbf22016-10-14 18:55:44 +00004841 // Find all of the submodules and emit the module initializers.
4842 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4843 SmallVector<clang::Module *, 16> Stack;
4844 Visited.insert(Import->getImportedModule());
4845 Stack.push_back(Import->getImportedModule());
4846
4847 while (!Stack.empty()) {
4848 clang::Module *Mod = Stack.pop_back_val();
4849 if (!EmittedModuleInitializers.insert(Mod).second)
4850 continue;
4851
4852 for (auto *D : Context.getModuleInitializers(Mod))
4853 EmitTopLevelDecl(D);
4854
4855 // Visit the submodules of this module.
4856 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4857 SubEnd = Mod->submodule_end();
4858 Sub != SubEnd; ++Sub) {
4859 // Skip explicit children; they need to be explicitly imported to emit
4860 // the initializers.
4861 if ((*Sub)->IsExplicit)
4862 continue;
4863
4864 if (Visited.insert(*Sub).second)
4865 Stack.push_back(*Sub);
4866 }
4867 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004868 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004869 }
4870
Richard Smith8df390f2016-09-08 23:14:54 +00004871 case Decl::Export:
4872 EmitDeclContext(cast<ExportDecl>(D));
4873 break;
4874
Alexey Bataev97720002014-11-11 04:05:39 +00004875 case Decl::OMPThreadPrivate:
4876 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4877 break;
4878
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004879 case Decl::OMPDeclareReduction:
4880 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4881 break;
Kelvin Li1408f912018-09-26 04:28:39 +00004882
4883 case Decl::OMPRequires:
4884 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
4885 break;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004886
Mike Stump11289f42009-09-09 15:08:12 +00004887 default:
Mike Stump18bb9282009-05-16 07:57:57 +00004888 // Make sure we handled everything we should, every other kind is a
4889 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4890 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004891 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00004892 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004893 }
4894}
John McCall09ae0322010-07-06 23:57:41 +00004895
Alex Lorenzee024992014-08-04 18:41:51 +00004896void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4897 // Do we need to generate coverage mapping?
4898 if (!CodeGenOpts.CoverageMapping)
4899 return;
4900 switch (D->getKind()) {
4901 case Decl::CXXConversion:
4902 case Decl::CXXMethod:
4903 case Decl::Function:
4904 case Decl::ObjCMethod:
4905 case Decl::CXXConstructor:
4906 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00004907 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00004908 return;
Vedant Kumar0acf3432017-09-22 18:23:04 +00004909 SourceManager &SM = getContext().getSourceManager();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004910 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
Vedant Kumar0acf3432017-09-22 18:23:04 +00004911 return;
Alex Lorenzee024992014-08-04 18:41:51 +00004912 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4913 if (I == DeferredEmptyCoverageMappingDecls.end())
4914 DeferredEmptyCoverageMappingDecls[D] = true;
4915 break;
4916 }
4917 default:
4918 break;
4919 };
4920}
4921
4922void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4923 // Do we need to generate coverage mapping?
4924 if (!CodeGenOpts.CoverageMapping)
4925 return;
4926 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4927 if (Fn->isTemplateInstantiation())
4928 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4929 }
4930 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4931 if (I == DeferredEmptyCoverageMappingDecls.end())
4932 DeferredEmptyCoverageMappingDecls[D] = false;
4933 else
4934 I->second = false;
4935}
4936
4937void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Eli Friedman8516b7f2017-12-19 01:54:09 +00004938 // We call takeVector() here to avoid use-after-free.
4939 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4940 // we deserialize function bodies to emit coverage info for them, and that
4941 // deserializes more declarations. How should we handle that case?
4942 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
Eli Friedmandbcfade2017-12-13 00:14:17 +00004943 if (!Entry.second)
Alex Lorenzee024992014-08-04 18:41:51 +00004944 continue;
Eli Friedmandbcfade2017-12-13 00:14:17 +00004945 const Decl *D = Entry.first;
Alex Lorenzee024992014-08-04 18:41:51 +00004946 switch (D->getKind()) {
4947 case Decl::CXXConversion:
4948 case Decl::CXXMethod:
4949 case Decl::Function:
4950 case Decl::ObjCMethod: {
4951 CodeGenPGO PGO(*this);
4952 GlobalDecl GD(cast<FunctionDecl>(D));
4953 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4954 getFunctionLinkage(GD));
4955 break;
4956 }
4957 case Decl::CXXConstructor: {
4958 CodeGenPGO PGO(*this);
4959 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4960 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4961 getFunctionLinkage(GD));
4962 break;
4963 }
4964 case Decl::CXXDestructor: {
4965 CodeGenPGO PGO(*this);
4966 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4967 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4968 getFunctionLinkage(GD));
4969 break;
4970 }
4971 default:
4972 break;
4973 };
4974 }
4975}
4976
John McCall09ae0322010-07-06 23:57:41 +00004977/// Turns the given pointer into a constant.
4978static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4979 const void *Ptr) {
4980 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00004981 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00004982 return llvm::ConstantInt::get(i64, PtrInt);
4983}
4984
4985static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4986 llvm::NamedMDNode *&GlobalMetadata,
4987 GlobalDecl D,
4988 llvm::GlobalValue *Addr) {
4989 if (!GlobalMetadata)
4990 GlobalMetadata =
4991 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4992
4993 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004994 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4995 llvm::ConstantAsMetadata::get(GetPointerConstant(
4996 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00004997 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00004998}
4999
Richard Smithdf931ce2013-04-06 05:00:46 +00005000/// For each function which is declared within an extern "C" region and marked
5001/// as 'used', but has internal linkage, create an alias from the unmangled
5002/// name to the mangled name if possible. People expect to be able to refer
5003/// to such functions with an unmangled name from inline assembly within the
5004/// same translation unit.
5005void CodeGenModule::EmitStaticExternCAliases() {
Yaxun Liub0eee292018-03-29 14:50:00 +00005006 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00005007 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00005008 for (auto &I : StaticExternCValues) {
5009 IdentifierInfo *Name = I.first;
5010 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00005011 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00005012 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00005013 }
Richard Smithdf931ce2013-04-06 05:00:46 +00005014}
5015
Alp Tokerfb8d02b2014-06-05 22:10:59 +00005016bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5017 GlobalDecl &Result) const {
5018 auto Res = Manglings.find(MangledName);
5019 if (Res == Manglings.end())
5020 return false;
5021 Result = Res->getValue();
5022 return true;
5023}
5024
John McCall09ae0322010-07-06 23:57:41 +00005025/// Emits metadata nodes associating all the global values in the
5026/// current module with the Decls they came from. This is useful for
5027/// projects using IR gen as a subroutine.
5028///
5029/// Since there's currently no way to associate an MDNode directly
5030/// with an llvm::GlobalValue, we create a global named metadata
5031/// with the name 'clang.global.decl.ptrs'.
5032void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00005033 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005034
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005035 for (auto &I : MangledDeclNames) {
5036 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00005037 // Some mangled names don't necessarily have an associated GlobalValue
5038 // in this module, e.g. if we mangled it for DebugInfo.
5039 if (Addr)
5040 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00005041 }
5042}
5043
5044/// Emits metadata nodes for all the local variables in the current
5045/// function.
5046void CodeGenFunction::EmitDeclMetadata() {
5047 if (LocalDeclMap.empty()) return;
5048
5049 llvm::LLVMContext &Context = getLLVMContext();
5050
5051 // Find the unique metadata ID for this name.
5052 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5053
Craig Topper8a13c412014-05-21 05:09:00 +00005054 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00005055
Robert Lytton5b88f78f2014-07-03 09:30:29 +00005056 for (auto &I : LocalDeclMap) {
5057 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00005058 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005059 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005060 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005061 Alloca->setMetadata(
5062 DeclPtrKind, llvm::MDNode::get(
5063 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005064 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00005065 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5066 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5067 }
5068 }
5069}
Daniel Dunbar900546d2010-07-16 00:00:15 +00005070
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005071void CodeGenModule::EmitVersionIdentMetadata() {
5072 llvm::NamedMDNode *IdentMetadata =
5073 TheModule.getOrInsertNamedMetadata("llvm.ident");
5074 std::string Version = getClangFullVersion();
5075 llvm::LLVMContext &Ctx = TheModule.getContext();
5076
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005077 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00005078 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5079}
5080
Robert Lytton57765d52014-07-03 09:30:33 +00005081void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00005082 // Warning, new MangledDeclNames may be appended within this loop.
5083 // We rely on MapVector insertions adding new elements to the end
5084 // of the container.
5085 // FIXME: Move this loop into the one target that needs it, and only
5086 // loop over those declarations for which we couldn't emit the target
5087 // metadata when we emitted the declaration.
5088 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00005089 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00005090 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5091 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00005092 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5093 }
5094}
5095
Nick Lewycky85c011d2011-05-05 00:08:20 +00005096void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00005097 if (getCodeGenOpts().CoverageDataFile.empty() &&
5098 getCodeGenOpts().CoverageNotesFile.empty())
5099 return;
5100
5101 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5102 if (!CUNode)
5103 return;
5104
5105 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5106 llvm::LLVMContext &Ctx = TheModule.getContext();
5107 auto *CoverageDataFile =
5108 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5109 auto *CoverageNotesFile =
5110 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5111 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5112 llvm::MDNode *CU = CUNode->getOperand(i);
5113 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5114 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00005115 }
5116}
Nico Webercf4ff5862012-10-11 10:13:44 +00005117
Nico Weber17d3a2c2014-09-08 16:26:36 +00005118llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00005119 // Sema has checked that all uuid strings are of the form
5120 // "12345678-1234-1234-1234-1234567890ab".
5121 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00005122 for (unsigned i = 0; i < 36; ++i) {
5123 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5124 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00005125 }
Nico Webercf4ff5862012-10-11 10:13:44 +00005126
Nico Weberdfa274e2014-09-08 16:11:15 +00005127 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00005128 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00005129
David Majnemerbbecd092013-08-15 19:59:14 +00005130 llvm::Constant *Field3[8];
5131 for (unsigned Idx = 0; Idx < 8; ++Idx)
5132 Field3[Idx] = llvm::ConstantInt::get(
5133 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5134
5135 llvm::Constant *Fields[4] = {
5136 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5137 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5138 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5139 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5140 };
5141
5142 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00005143}
David Majnemere2cb8d12014-07-07 06:20:47 +00005144
5145llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5146 bool ForEH) {
5147 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5148 // FIXME: should we even be calling this method if RTTI is disabled
5149 // and it's not for EH?
Yaxun Liu6328f9a2018-06-05 15:11:02 +00005150 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
David Majnemere2cb8d12014-07-07 06:20:47 +00005151 return llvm::Constant::getNullValue(Int8PtrTy);
Jake Ehrlichc451cf22017-11-11 01:15:41 +00005152
David Majnemere2cb8d12014-07-07 06:20:47 +00005153 if (ForEH && Ty->isObjCObjectPointerType() &&
5154 LangOpts.ObjCRuntime.isGNUFamily())
5155 return ObjCRuntime->GetEHType(Ty);
5156
David Majnemer443250f2015-03-17 20:35:00 +00005157 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00005158}
5159
Alexey Bataev97720002014-11-11 04:05:39 +00005160void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00005161 // Do not emit threadprivates in simd-only mode.
5162 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5163 return;
Alexey Bataev97720002014-11-11 04:05:39 +00005164 for (auto RefExpr : D->varlists()) {
5165 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5166 bool PerformInit =
5167 VD->getAnyInitializer() &&
5168 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5169 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00005170
5171 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00005172 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005173 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00005174 CXXGlobalInits.push_back(InitFunction);
5175 }
5176}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005177
Peter Collingbournee44acad2018-06-26 02:15:47 +00005178llvm::Metadata *
5179CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5180 StringRef Suffix) {
5181 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005182 if (InternalId)
5183 return InternalId;
5184
5185 if (isExternallyVisible(T->getLinkage())) {
5186 std::string OutName;
5187 llvm::raw_string_ostream Out(OutName);
5188 getCXXABI().getMangleContext().mangleTypeName(T, Out);
Peter Collingbournee44acad2018-06-26 02:15:47 +00005189 Out << Suffix;
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00005190
5191 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5192 } else {
5193 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5194 llvm::ArrayRef<llvm::Metadata *>());
5195 }
5196
5197 return InternalId;
5198}
5199
Peter Collingbournee44acad2018-06-26 02:15:47 +00005200llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5201 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5202}
5203
5204llvm::Metadata *
5205CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5206 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5207}
5208
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005209// Generalize pointer types to a void pointer with the qualifiers of the
5210// originally pointed-to type, e.g. 'const char *' and 'char * const *'
5211// generalize to 'const void *' while 'char *' and 'const char **' generalize to
5212// 'void *'.
5213static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5214 if (!Ty->isPointerType())
5215 return Ty;
5216
5217 return Ctx.getPointerType(
5218 QualType(Ctx.VoidTy).withCVRQualifiers(
5219 Ty->getPointeeType().getCVRQualifiers()));
5220}
5221
5222// Apply type generalization to a FunctionType's return and argument types
5223static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5224 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5225 SmallVector<QualType, 8> GeneralizedParams;
5226 for (auto &Param : FnType->param_types())
5227 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5228
5229 return Ctx.getFunctionType(
5230 GeneralizeType(Ctx, FnType->getReturnType()),
5231 GeneralizedParams, FnType->getExtProtoInfo());
5232 }
5233
5234 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5235 return Ctx.getFunctionNoProtoType(
5236 GeneralizeType(Ctx, FnType->getReturnType()));
5237
5238 llvm_unreachable("Encountered unknown FunctionType");
5239}
5240
5241llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
Peter Collingbournee44acad2018-06-26 02:15:47 +00005242 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5243 GeneralizedMetadataIdMap, ".generalized");
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00005244}
5245
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005246/// Returns whether this module needs the "all-vtables" type identifier.
5247bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005248 // Returns true if at least one of vtable-based CFI checkers is enabled and
5249 // is not in the trapping mode.
5250 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5251 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5252 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5253 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5254 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5255 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5256 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5257 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5258}
5259
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005260void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5261 CharUnits Offset,
5262 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005263 llvm::Metadata *MD =
5264 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005265 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00005266
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005267 if (CodeGenOpts.SanitizeCfiCrossDso)
5268 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5269 VTable->addTypeMetadata(Offset.getQuantity(),
5270 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005271
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005272 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005273 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00005274 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00005275 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00005276}
Eric Christopher2b90a642015-11-11 23:05:08 +00005277
Gabor Buella1a83d062018-06-07 08:48:36 +00005278TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5279 assert(TD != nullptr);
5280 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5281
5282 ParsedAttr.Features.erase(
5283 llvm::remove_if(ParsedAttr.Features,
5284 [&](const std::string &Feat) {
5285 return !Target.isValidFeatureName(
5286 StringRef{Feat}.substr(1));
5287 }),
5288 ParsedAttr.Features.end());
5289 return ParsedAttr;
5290}
5291
5292
Eric Christopher2b90a642015-11-11 23:05:08 +00005293// Fills in the supplied string map with the set of target features for the
5294// passed in function.
5295void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5296 const FunctionDecl *FD) {
5297 StringRef TargetCPU = Target.getTargetOpts().CPU;
5298 if (const auto *TD = FD->getAttr<TargetAttr>()) {
Gabor Buella1a83d062018-06-07 08:48:36 +00005299 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
Erich Keanecf8807c2017-10-27 18:32:23 +00005300
Eric Christopher2b90a642015-11-11 23:05:08 +00005301 // Make a copy of the features as passed on the command line into the
5302 // beginning of the additional features from the function to override.
Erich Keaneb0d44232017-07-18 20:41:02 +00005303 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
Eric Christopher2b90a642015-11-11 23:05:08 +00005304 Target.getTargetOpts().FeaturesAsWritten.begin(),
5305 Target.getTargetOpts().FeaturesAsWritten.end());
5306
Erich Keanecf8807c2017-10-27 18:32:23 +00005307 if (ParsedAttr.Architecture != "" &&
5308 Target.isValidCPUName(ParsedAttr.Architecture))
5309 TargetCPU = ParsedAttr.Architecture;
Eric Christopher2b90a642015-11-11 23:05:08 +00005310
5311 // Now populate the feature map, first with the TargetCPU which is either
5312 // the default or a new one from the target attribute string. Then we'll use
5313 // the passed in features (FeaturesAsWritten) along with the new ones from
5314 // the attribute.
Erich Keaneb0d44232017-07-18 20:41:02 +00005315 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5316 ParsedAttr.Features);
Erich Keane3efe0022018-07-20 14:13:28 +00005317 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5318 llvm::SmallVector<StringRef, 32> FeaturesTmp;
5319 Target.getCPUSpecificCPUDispatchFeatures(SD->getCurCPUName()->getName(),
5320 FeaturesTmp);
5321 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5322 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
Eric Christopher2b90a642015-11-11 23:05:08 +00005323 } else {
5324 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5325 Target.getTargetOpts().Features);
5326 }
5327}
Peter Collingbournedc134532016-01-16 00:31:22 +00005328
5329llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5330 if (!SanStats)
5331 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5332
5333 return *SanStats;
5334}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005335llvm::Value *
5336CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5337 CodeGenFunction &CGF) {
John McCallde0fe072017-08-15 21:42:52 +00005338 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
Sven van Haastregtefb4d4c2017-08-15 09:38:18 +00005339 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00005340 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5341 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5342 "__translate_sampler_initializer"),
5343 {C});
5344}