blob: b7a3777fe458fffcb8d204d7aaacf47c60abdcde [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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000026#include "CodeGenTBAA.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000027#include "CoverageMappingGen.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000028#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000029#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000030#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000031#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000033#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000034#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000035#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000036#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000037#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000038#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000039#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000040#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000041#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000042#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000043#include "clang/Basic/Version.h"
John McCall5ad74072017-03-02 20:04:19 +000044#include "clang/CodeGen/ConstantInitBuilder.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000045#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000046#include "clang/Sema/SemaDiagnostic.h"
John McCallbeec5a02010-03-06 00:35:14 +000047#include "llvm/ADT/Triple.h"
Matthias Brauna4519532017-05-20 01:29:55 +000048#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000049#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000050#include "llvm/IR/CallingConv.h"
51#include "llvm/IR/DataLayout.h"
52#include "llvm/IR/Intrinsics.h"
53#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/Module.h"
Justin Bogner837a6f62014-04-18 21:52:00 +000055#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000056#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000057#include "llvm/Support/ErrorHandling.h"
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +000058#include "llvm/Support/MD5.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000059
Chris Lattnerbed31442007-05-28 01:07:47 +000060using namespace clang;
61using namespace CodeGen;
62
Julien Lerouge5a6b6982011-09-09 22:41:49 +000063static const char AnnotationSection[] = "llvm.metadata";
64
Alp Toker82862252013-12-28 21:58:40 +000065static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000066 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000067 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000068 case TargetCXXABI::GenericARM:
69 case TargetCXXABI::iOS:
Tim Northovera2ee4332014-03-29 15:09:45 +000070 case TargetCXXABI::iOS64:
Tim Northover756447a2015-10-30 16:30:36 +000071 case TargetCXXABI::WatchOS:
Zoran Jovanovic26a12162015-02-18 15:21:35 +000072 case TargetCXXABI::GenericMIPS:
John McCall57625922013-01-25 23:36:14 +000073 case TargetCXXABI::GenericItanium:
Dan Gohmanc2853072015-09-03 22:51:53 +000074 case TargetCXXABI::WebAssembly:
Alp Toker82862252013-12-28 21:58:40 +000075 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000076 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000077 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000078 }
79
80 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000081}
82
Adrian Prantle74f5252015-06-30 02:26:03 +000083CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
84 const PreprocessorOptions &PPO,
85 const CodeGenOptions &CGO, llvm::Module &M,
Alex Lorenzee024992014-08-04 18:41:51 +000086 DiagnosticsEngine &diags,
87 CoverageSourceInfo *CoverageInfo)
Adrian Prantle74f5252015-06-30 02:26:03 +000088 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
89 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
Mehdi Aminica3cf9e2015-07-24 16:04:29 +000090 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
Reid Kleckner9305fd12016-04-13 23:37:17 +000091 VMContext(M.getContext()), Types(*this), VTables(*this),
Peter Collingbourne3afb2662016-04-28 17:09:37 +000092 SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietzf54319c2013-01-18 11:30:38 +000093
Chris Lattnerece04092012-02-07 00:39:47 +000094 // Initialize the type cache.
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 VoidTy = llvm::Type::getVoidTy(LLVMContext);
97 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101 FloatTy = llvm::Type::getFloatTy(LLVMContext);
102 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104 PointerAlignInBytes =
John McCall7f416cc2015-09-08 08:05:57 +0000105 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
Yaxun Liu26f75662016-08-19 05:17:25 +0000106 SizeSizeInBytes =
107 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +0000108 IntAlignInBytes =
109 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
Chris Lattnerece04092012-02-07 00:39:47 +0000110 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
Yaxun Liu26f75662016-08-19 05:17:25 +0000111 IntPtrTy = llvm::IntegerType::get(LLVMContext,
112 C.getTargetInfo().getMaxPointerWidth());
Chris Lattnerece04092012-02-07 00:39:47 +0000113 Int8PtrTy = Int8Ty->getPointerTo(0);
114 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
Yaxun Liu7f7f3232017-04-17 20:03:11 +0000115 AllocaInt8PtrTy = Int8Ty->getPointerTo(
116 M.getDataLayout().getAllocaAddrSpace());
Yaxun Liu6d96f1632017-05-18 18:51:09 +0000117 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
Chris Lattnerece04092012-02-07 00:39:47 +0000118
John McCall882987f2013-02-28 19:01:20 +0000119 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
Anton Korobeynikovd90dd792014-12-02 16:04:58 +0000120 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
John McCall882987f2013-02-28 19:01:20 +0000121
David Blaikiebbafb8a2012-03-11 07:00:24 +0000122 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000123 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000124 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000125 createOpenCLRuntime();
Alexey Bataev9959db52014-05-06 10:08:46 +0000126 if (LangOpts.OpenMP)
127 createOpenMPRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000128 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000129 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000130
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000131 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000132 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000133 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
Reid Kleckner9305fd12016-04-13 23:37:17 +0000134 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
135 getCXXABI().getMangleContext()));
Dan Gohman947c9af2010-10-14 23:06:10 +0000136
Nick Lewycky207bce32011-04-21 23:44:07 +0000137 // If debug info or coverage generation is enabled, create the CGDebugInfo
138 // object.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000139 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
140 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000141 DebugInfo.reset(new CGDebugInfo(*this));
John McCallad7c5c12011-02-08 08:22:06 +0000142
143 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000144
John McCallb04ecb72015-10-21 18:06:43 +0000145 if (C.getLangOpts().ObjC1)
Reid Kleckner9305fd12016-04-13 23:37:17 +0000146 ObjCData.reset(new ObjCEntrypoints());
Justin Bogneref512b92014-01-06 22:27:43 +0000147
Rong Xu9c6f1532016-03-02 20:59:36 +0000148 if (CodeGenOpts.hasProfileClangUse()) {
149 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
150 CodeGenOpts.ProfileInstrumentUsePath);
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000151 if (auto E = ReaderOrErr.takeError()) {
Justin Bogner837a6f62014-04-18 21:52:00 +0000152 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
Diego Novillo5aecacb2015-06-25 22:56:00 +0000153 "Could not read profile %0: %1");
Vedant Kumarfa2d5952016-05-19 03:54:54 +0000154 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
155 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
156 << EI.message();
157 });
Nico Weber176efac2015-04-06 04:16:48 +0000158 } else
159 PGOReader = std::move(ReaderOrErr.get());
Justin Bogner837a6f62014-04-18 21:52:00 +0000160 }
Alex Lorenzee024992014-08-04 18:41:51 +0000161
162 // If coverage mapping generation is enabled, create the
163 // CoverageMappingModuleGen object.
164 if (CodeGenOpts.CoverageMapping)
165 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattnera087ff92008-03-01 08:45:05 +0000166}
167
Reid Kleckner9305fd12016-04-13 23:37:17 +0000168CodeGenModule::~CodeGenModule() {}
Ted Kremenek2c674f62008-08-05 18:50:11 +0000169
David Chisnall481e3a82010-01-23 02:40:42 +0000170void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000171 // This is just isGNUFamily(), but we want to force implementors of
172 // new ABIs to decide how best to do this.
173 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000174 case ObjCRuntime::GNUstep:
175 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000176 case ObjCRuntime::ObjFW:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000177 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000178 return;
179
180 case ObjCRuntime::FragileMacOSX:
181 case ObjCRuntime::MacOSX:
182 case ObjCRuntime::iOS:
Tim Northover756447a2015-10-30 16:30:36 +0000183 case ObjCRuntime::WatchOS:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000184 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
John McCall5fb5df92012-06-20 06:18:46 +0000185 return;
186 }
187 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000188}
189
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000190void CodeGenModule::createOpenCLRuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000191 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000192}
193
Alexey Bataev9959db52014-05-06 10:08:46 +0000194void CodeGenModule::createOpenMPRuntime() {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000195 // Select a specialized code generation class based on the target, if any.
196 // If it does not exist use the default implementation.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000197 switch (getTriple().getArch()) {
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000198 case llvm::Triple::nvptx:
199 case llvm::Triple::nvptx64:
200 assert(getLangOpts().OpenMPIsDevice &&
201 "OpenMP NVPTX is only prepared to deal with device code.");
Reid Kleckner9305fd12016-04-13 23:37:17 +0000202 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000203 break;
204 default:
Reid Kleckner9305fd12016-04-13 23:37:17 +0000205 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
Samuel Antao45bfe4c2016-02-08 15:59:20 +0000206 break;
207 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000208}
209
Peter Collingbournefe883422011-10-06 18:29:37 +0000210void CodeGenModule::createCUDARuntime() {
Reid Kleckner9305fd12016-04-13 23:37:17 +0000211 CUDARuntime.reset(CreateNVCUDARuntime(*this));
Peter Collingbournefe883422011-10-06 18:29:37 +0000212}
213
Rafael Espindola1e4df922014-09-16 15:18:21 +0000214void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
215 Replacements[Name] = C;
216}
217
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000218void CodeGenModule::applyReplacements() {
Yaron Kerenb54db522015-06-11 12:33:25 +0000219 for (auto &I : Replacements) {
220 StringRef MangledName = I.first();
221 llvm::Constant *Replacement = I.second;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000222 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
223 if (!Entry)
224 continue;
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000225 auto *OldF = cast<llvm::Function>(Entry);
226 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000227 if (!NewF) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000228 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
Rafael Espindola0fcad882014-05-16 22:20:18 +0000229 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Reid Klecknerb78257d2014-02-03 18:54:51 +0000230 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000231 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Reid Klecknerb78257d2014-02-03 18:54:51 +0000232 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
233 CE->getOpcode() == llvm::Instruction::GetElementPtr);
234 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
235 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000236 }
237
238 // Replace old with new, but keep the old order.
239 OldF->replaceAllUsesWith(Replacement);
240 if (NewF) {
241 NewF->removeFromParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000242 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
243 NewF);
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000244 }
245 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000246 }
247}
248
Andrey Bokhankocab58582015-08-31 13:20:44 +0000249void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
250 GlobalValReplacements.push_back(std::make_pair(GV, C));
251}
252
253void CodeGenModule::applyGlobalValReplacements() {
254 for (auto &I : GlobalValReplacements) {
255 llvm::GlobalValue *GV = I.first;
256 llvm::Constant *C = I.second;
257
258 GV->replaceAllUsesWith(C);
259 GV->eraseFromParent();
260 }
261}
262
Rafael Espindola27c60b52014-06-03 02:42:01 +0000263// This is only used in aliases that we created and we know they have a
264// linear structure.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000265static const llvm::GlobalObject *getAliasedGlobal(
266 const llvm::GlobalIndirectSymbol &GIS) {
267 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
268 const llvm::Constant *C = &GIS;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000269 for (;;) {
Rafael Espindolae11f40a2014-06-04 19:03:20 +0000270 C = C->stripPointerCasts();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000271 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
272 return GO;
273 // stripPointerCasts will not walk over weak aliases.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000274 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
275 if (!GIS2)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000276 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000277 if (!Visited.insert(GIS2).second)
Rafael Espindola27c60b52014-06-03 02:42:01 +0000278 return nullptr;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000279 C = GIS2->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000280 }
281}
282
Rafael Espindola208b5c02013-10-22 19:26:13 +0000283void CodeGenModule::checkAliases() {
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000284 // Check if the constructed aliases are well formed. It is really unfortunate
285 // that we have to do this in CodeGen, but we only construct mangled names
286 // and aliases during codegen.
Rafael Espindola208b5c02013-10-22 19:26:13 +0000287 bool Error = false;
Rafael Espindolac67b8152014-05-05 19:33:09 +0000288 DiagnosticsEngine &Diags = getDiags();
Yaron Kerenb54db522015-06-11 12:33:25 +0000289 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000290 const auto *D = cast<ValueDecl>(GD.getDecl());
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000291 SourceLocation Location;
292 bool IsIFunc = D->hasAttr<IFuncAttr>();
293 if (const Attr *A = D->getDefiningAttr())
294 Location = A->getLocation();
295 else
296 llvm_unreachable("Not an alias or ifunc?");
Rafael Espindola208b5c02013-10-22 19:26:13 +0000297 StringRef MangledName = getMangledName(GD);
298 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000299 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000300 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
301 if (!GV) {
302 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000303 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000304 } else if (GV->isDeclaration()) {
Rafael Espindola93c7a652014-03-13 15:47:50 +0000305 Error = true;
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000306 Diags.Report(Location, diag::err_alias_to_undefined)
307 << IsIFunc << IsIFunc;
308 } else if (IsIFunc) {
309 // Check resolver function type.
310 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
311 GV->getType()->getPointerElementType());
312 assert(FTy);
313 if (!FTy->getReturnType()->isPointerTy())
314 Diags.Report(Location, diag::err_ifunc_resolver_return);
315 if (FTy->getNumParams())
316 Diags.Report(Location, diag::err_ifunc_resolver_params);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000317 }
Rafael Espindolaa39fc6d2014-03-27 15:27:20 +0000318
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000319 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000320 llvm::GlobalValue *AliaseeGV;
321 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
322 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
323 else
324 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
325
Rafael Espindola502f65a2014-05-05 20:21:03 +0000326 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
327 StringRef AliasSection = SA->getName();
Rafael Espindola27c60b52014-06-03 02:42:01 +0000328 if (AliasSection != AliaseeGV->getSection())
Rafael Espindola502f65a2014-05-05 20:21:03 +0000329 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000330 << AliasSection << IsIFunc << IsIFunc;
Rafael Espindola502f65a2014-05-05 20:21:03 +0000331 }
Rafael Espindola27c60b52014-06-03 02:42:01 +0000332
333 // We have to handle alias to weak aliases in here. LLVM itself disallows
334 // this since the object semantics would not match the IL one. For
335 // compatibility with gcc we implement it by just pointing the alias
336 // to its aliasee's aliasee. We also warn, since the user is probably
337 // expecting the link to be weak.
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000338 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
Sanjoy Dasf60a0d72016-04-08 01:31:02 +0000339 if (GA->isInterposable()) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000340 Diags.Report(Location, diag::warn_alias_to_weak_alias)
341 << GV->getName() << GA->getName() << IsIFunc;
Rafael Espindola27c60b52014-06-03 02:42:01 +0000342 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000343 GA->getIndirectSymbol(), Alias->getType());
344 Alias->setIndirectSymbol(Aliasee);
Rafael Espindola27c60b52014-06-03 02:42:01 +0000345 }
346 }
Rafael Espindola208b5c02013-10-22 19:26:13 +0000347 }
348 if (!Error)
349 return;
350
Yaron Kerenb54db522015-06-11 12:33:25 +0000351 for (const GlobalDecl &GD : Aliases) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000352 StringRef MangledName = getMangledName(GD);
353 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Dmitry Polukhin85eda122016-04-11 07:48:59 +0000354 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000355 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
356 Alias->eraseFromParent();
357 }
358}
359
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000360void CodeGenModule::clear() {
361 DeferredDeclsToEmit.clear();
Alexey Bataev91797552015-03-18 04:13:55 +0000362 if (OpenMPRuntime)
363 OpenMPRuntime->clear();
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000364}
365
Justin Bogner40b8ba12014-06-26 01:45:07 +0000366void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
367 StringRef MainFile) {
368 if (!hasDiagnostics())
369 return;
370 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
371 if (MainFile.empty())
372 MainFile = "<stdin>";
373 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
Vedant Kumar96d6ca72017-04-27 17:30:58 +0000374 } else {
375 if (Mismatched > 0)
376 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
377
378 if (Missing > 0)
379 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
380 }
Justin Bogner40b8ba12014-06-26 01:45:07 +0000381}
382
Ted Kremenek2c674f62008-08-05 18:50:11 +0000383void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000384 EmitDeferred();
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +0000385 EmitVTablesOpportunistically();
Andrey Bokhankocab58582015-08-31 13:20:44 +0000386 applyGlobalValReplacements();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000387 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000388 checkAliases();
Eli Friedman5866fe32010-01-08 00:50:11 +0000389 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000390 EmitCXXGlobalDtorFunc();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000391 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000392 if (ObjCRuntime)
393 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000394 AddGlobalCtor(ObjCInitFunction);
Artem Belevich52cc4872015-05-07 19:34:16 +0000395 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
396 CUDARuntime) {
397 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
398 AddGlobalCtor(CudaCtorFunction);
399 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
400 AddGlobalDtor(CudaDtorFunction);
401 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000402 if (OpenMPRuntime)
403 if (llvm::Function *OpenMPRegistrationFunction =
George Rokos29d0f002017-05-27 03:03:13 +0000404 OpenMPRuntime->emitRegistrationFunction()) {
405 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
406 OpenMPRegistrationFunction : nullptr;
407 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
408 }
Easwaran Raman695890c2015-12-17 19:14:27 +0000409 if (PGOReader) {
Easwaran Raman81608122016-03-24 21:32:25 +0000410 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
Easwaran Raman695890c2015-12-17 19:14:27 +0000411 if (PGOStats.hasDiagnostics())
412 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
413 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000414 EmitCtorList(GlobalCtors, "llvm.global_ctors");
415 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000416 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000417 EmitStaticExternCAliases();
Alex Lorenzee024992014-08-04 18:41:51 +0000418 EmitDeferredUnusedCoverageMappings();
419 if (CoverageMapping)
420 CoverageMapping->emit();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000421 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000422 CodeGenFunction(*this).EmitCfiCheckFail();
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +0000423 CodeGenFunction(*this).EmitCfiCheckStub();
424 }
Alex Lorenza8fbef42017-03-23 11:14:27 +0000425 emitAtAvailableLinkGuard();
Rafael Espindola060062a2014-03-06 22:15:10 +0000426 emitLLVMUsed();
Peter Collingbournedc134532016-01-16 00:31:22 +0000427 if (SanStats)
428 SanStats->finish();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000429
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000430 if (CodeGenOpts.Autolink &&
431 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000432 EmitModuleLinkOptions();
433 }
Nirav Dave8497ef42017-03-18 00:43:39 +0000434
Nirav Dave741dea02017-03-30 13:41:44 +0000435 // Record mregparm value now so it is visible through rest of codegen.
436 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
437 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
438 CodeGenOpts.NumRegisterParameters);
439
Reid Kleckner124955a2015-08-05 18:51:13 +0000440 if (CodeGenOpts.DwarfVersion) {
Manman Ren9691f7f2013-06-19 01:46:49 +0000441 // We actually want the latest version when there are conflicts.
442 // We can change from Warning to Latest if such mode is supported.
443 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
444 CodeGenOpts.DwarfVersion);
Reid Kleckner124955a2015-08-05 18:51:13 +0000445 }
446 if (CodeGenOpts.EmitCodeView) {
447 // Indicate that we want CodeView in the metadata.
448 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
449 }
Piotr Padlewski9d0ecf22015-09-15 21:46:50 +0000450 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
451 // We don't support LTO with 2 with different StrictVTablePointers
452 // FIXME: we could support it by stripping all the information introduced
453 // by StrictVTablePointers.
454
455 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
456
457 llvm::Metadata *Ops[2] = {
458 llvm::MDString::get(VMContext, "StrictVTablePointers"),
459 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
460 llvm::Type::getInt32Ty(VMContext), 1))};
461
462 getModule().addModuleFlag(llvm::Module::Require,
463 "StrictVTablePointersRequirement",
464 llvm::MDNode::get(VMContext, Ops));
465 }
Manman Ren4b7f23d2013-11-22 19:42:45 +0000466 if (DebugInfo)
Adrian Prantl2dbdd202014-05-19 23:40:06 +0000467 // We support a single version in the linked module. The LLVM
468 // parser will drop debug info with a different version number
469 // (and warn about it, too).
470 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000471 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000472
Matthias Brauna4519532017-05-20 01:29:55 +0000473 // Width of wchar_t in bytes
474 uint64_t WCharWidth =
475 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
Davide Italiano5e458ad2017-05-31 18:51:36 +0000476 assert((LangOpts.ShortWChar ||
477 llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) ==
478 Target.getWCharWidth() / 8) &&
479 "LLVM wchar_t size out of sync");
Matthias Brauna4519532017-05-20 01:29:55 +0000480
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000481 // We need to record the widths of enums and wchar_t, so that we can generate
Matthias Brauna4519532017-05-20 01:29:55 +0000482 // the correct build attributes in the ARM backend. wchar_size is also used by
483 // TargetLibraryInfo.
484 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
485
Justin Bogner9bb7f152014-06-23 20:03:28 +0000486 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000487 if ( Arch == llvm::Triple::arm
488 || Arch == llvm::Triple::armeb
489 || Arch == llvm::Triple::thumb
490 || Arch == llvm::Triple::thumbeb) {
Oliver Stannarde3a4fb62014-06-20 12:43:07 +0000491 // The minimum width of an enum in bytes
492 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
493 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
494 }
495
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000496 if (CodeGenOpts.SanitizeCfiCrossDso) {
497 // Indicate that we want cross-DSO control flow integrity checks.
498 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
499 }
500
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +0000501 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
Justin Lebard3a44f62016-04-05 18:26:20 +0000502 // Indicate whether __nvvm_reflect should be configured to flush denormal
503 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
504 // property.)
505 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
506 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
507 }
508
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000509 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
Sriraman Tallam70e70e62016-04-28 22:34:00 +0000510 assert(PLevel < 3 && "Invalid PIC Level");
511 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
Rafael Espindolac9d336e2016-06-23 15:07:32 +0000512 if (Context.getLangOpts().PIE)
513 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
Justin Hibbits90ca05e2014-11-18 06:17:20 +0000514 }
515
John McCall0bdb1fd2010-09-16 06:16:50 +0000516 SimplifyPersonality();
517
John McCall09ae0322010-07-06 23:57:41 +0000518 if (getCodeGenOpts().EmitDeclMetadata)
519 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000520
521 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000522 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000523
524 if (DebugInfo)
525 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000526
527 EmitVersionIdentMetadata();
Robert Lytton57765d52014-07-03 09:30:33 +0000528
529 EmitTargetMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000530}
531
Devang Patel945b8ae2011-03-23 16:29:39 +0000532void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
533 // Make sure that this type is translated.
534 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000535}
536
David Majnemer929025d2016-01-26 19:30:26 +0000537void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
538 // Make sure that this type is translated.
539 Types.RefreshTypeCacheForClass(RD);
540}
541
Dan Gohman947c9af2010-10-14 23:06:10 +0000542llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
543 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000544 return nullptr;
Dan Gohman947c9af2010-10-14 23:06:10 +0000545 return TBAA->getTBAAInfo(QTy);
546}
547
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000548llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
549 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000550 return nullptr;
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000551 return TBAA->getTBAAInfoForVTablePtr();
552}
553
Dan Gohman22695fc2012-09-28 21:58:29 +0000554llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
555 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000556 return nullptr;
Dan Gohman22695fc2012-09-28 21:58:29 +0000557 return TBAA->getTBAAStructInfo(QTy);
558}
559
Manman Renc451e572013-04-04 21:53:22 +0000560llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
561 llvm::MDNode *AccessN,
562 uint64_t O) {
563 if (!TBAA)
Craig Topper8a13c412014-05-21 05:09:00 +0000564 return nullptr;
Manman Renc451e572013-04-04 21:53:22 +0000565 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
566}
567
Manman Ren4f755de2013-10-08 00:08:49 +0000568/// Decorate the instruction with a TBAA tag. For both scalar TBAA
569/// and struct-path aware TBAA, the tag has the same format:
570/// base type, access type and offset.
Manman Rene1ad74e2013-04-11 23:02:56 +0000571/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000572void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
573 llvm::MDNode *TBAAInfo,
574 bool ConvertTypeToTag) {
Manman Ren4f755de2013-10-08 00:08:49 +0000575 if (ConvertTypeToTag && TBAA)
Manman Rene1ad74e2013-04-11 23:02:56 +0000576 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
577 TBAA->getTBAAScalarTagInfo(TBAAInfo));
578 else
579 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman947c9af2010-10-14 23:06:10 +0000580}
581
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000582void CodeGenModule::DecorateInstructionWithInvariantGroup(
583 llvm::Instruction *I, const CXXRecordDecl *RD) {
Piotr Padlewski34046bd2017-04-24 12:58:43 +0000584 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
585 llvm::MDNode::get(getLLVMContext(), {}));
Piotr Padlewski4b1ac722015-09-15 21:46:55 +0000586}
587
Alp Toker29cb66b2014-01-26 06:17:37 +0000588void CodeGenModule::Error(SourceLocation loc, StringRef message) {
589 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
590 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000591}
592
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000593/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000594/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000595void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000596 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000597 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000598 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000599 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
600 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000601}
Chris Lattner41af8182007-12-02 06:27:33 +0000602
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000603/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000604/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000605void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000606 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000607 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000608 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000609 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000610}
611
John McCall23c29fe2011-06-24 21:55:10 +0000612llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
613 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
614}
615
Mike Stump11289f42009-09-09 15:08:12 +0000616void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000617 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000618 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000619 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000620 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000621 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000622 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000623
John McCallc273f242010-10-30 11:50:40 +0000624 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000625 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000626 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
627 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000628}
629
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000630static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
631 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
632 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
633 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
634 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
635 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
636}
637
638static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
639 CodeGenOptions::TLSModel M) {
640 switch (M) {
641 case CodeGenOptions::GeneralDynamicTLSModel:
642 return llvm::GlobalVariable::GeneralDynamicTLSModel;
643 case CodeGenOptions::LocalDynamicTLSModel:
644 return llvm::GlobalVariable::LocalDynamicTLSModel;
645 case CodeGenOptions::InitialExecTLSModel:
646 return llvm::GlobalVariable::InitialExecTLSModel;
647 case CodeGenOptions::LocalExecTLSModel:
648 return llvm::GlobalVariable::LocalExecTLSModel;
649 }
650 llvm_unreachable("Invalid TLS model!");
651}
652
David Majnemerbb525f7c2014-10-15 22:38:23 +0000653void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000654 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000655
David Majnemerbb525f7c2014-10-15 22:38:23 +0000656 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000657 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000658
659 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000660 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000661 TLM = GetLLVMTLSModel(Attr->getModel());
662 }
663
664 GV->setThreadLocalMode(TLM);
665}
666
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000667StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
David Majnemerd2385c02016-01-08 20:48:26 +0000668 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
669
670 // Some ABIs don't have constructor variants. Make sure that base and
671 // complete constructors get mangled the same.
672 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
673 if (!getTarget().getCXXABI().hasConstructorVariants()) {
674 CXXCtorType OrigCtorType = GD.getCtorType();
675 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
676 if (OrigCtorType == Ctor_Base)
677 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
678 }
679 }
680
681 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000682 if (!FoundStr.empty())
683 return FoundStr;
684
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000685 const auto *ND = cast<NamedDecl>(GD.getDecl());
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000686 SmallString<256> Buffer;
687 StringRef Str;
688 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
689 llvm::raw_svector_ostream Out(Buffer);
690 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
691 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
692 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
693 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
694 else
695 getCXXABI().getMangleContext().mangleName(ND, Out);
696 Str = Out.str();
697 } else {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000698 IdentifierInfo *II = ND->getIdentifier();
699 assert(II && "Attempt to mangle unnamed decl.");
Erich Keane757d3172016-11-02 18:29:35 +0000700 const auto *FD = dyn_cast<FunctionDecl>(ND);
701
702 if (FD &&
703 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
704 llvm::raw_svector_ostream Out(Buffer);
705 Out << "__regcall3__" << II->getName();
706 Str = Out.str();
707 } else {
708 Str = II->getName();
709 }
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000710 }
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000711
Richard Smith6d0e97a2014-08-02 00:50:16 +0000712 // Keep the first result in the case of a mangling collision.
713 auto Result = Manglings.insert(std::make_pair(Str, GD));
714 return FoundStr = Result.first->first();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000715}
716
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000717StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
718 const BlockDecl *BD) {
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000719 MangleContext &MangleCtx = getCXXABI().getMangleContext();
720 const Decl *D = GD.getDecl();
Alp Toker0e64e0d2014-06-03 02:13:57 +0000721
Alp Tokerfb8d02b2014-06-05 22:10:59 +0000722 SmallString<256> Buffer;
723 llvm::raw_svector_ostream Out(Buffer);
Craig Topper8a13c412014-05-21 05:09:00 +0000724 if (!D)
Fariborz Jahanian63628032012-06-26 16:06:38 +0000725 MangleCtx.mangleGlobalBlock(BD,
726 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000727 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000728 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000729 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000730 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000731 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000732 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Alp Toker0e64e0d2014-06-03 02:13:57 +0000733
Richard Smith6d0e97a2014-08-02 00:50:16 +0000734 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
735 return Result.first->first();
Anders Carlsson635186a2010-06-09 02:36:32 +0000736}
737
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000738llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000739 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000740}
741
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000742/// AddGlobalCtor - Add a function to the list that will be called before
743/// main() runs.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000744void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
745 llvm::Constant *AssociatedData) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000746 // FIXME: Type coercion of void()* types.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000747 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000748}
749
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000750/// AddGlobalDtor - Add a function to the list that will be called
751/// when the module is unloaded.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000752void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000753 // FIXME: Type coercion of void()* types.
Craig Topper4b566922014-06-09 02:04:02 +0000754 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000755}
756
Vassil Vassilev188ad3a2016-10-27 09:12:20 +0000757void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
John McCall6c9f1fdb2016-11-19 08:17:24 +0000758 if (Fns.empty()) return;
759
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000760 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000761 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000762 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000763
Reid Kleckner563f0e82014-05-23 21:13:45 +0000764 // Get the type of a ctor entry, { i32, void ()*, i8* }.
765 llvm::StructType *CtorStructTy = llvm::StructType::get(
Serge Guelton1d993272017-05-09 19:31:30 +0000766 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000767
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000768 // Construct the constructor and destructor arrays.
John McCall23c9dc62016-11-28 22:18:27 +0000769 ConstantInitBuilder builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000770 auto ctors = builder.beginArray(CtorStructTy);
Yaron Kerenb54db522015-06-11 12:33:25 +0000771 for (const auto &I : Fns) {
John McCall6c9f1fdb2016-11-19 08:17:24 +0000772 auto ctor = ctors.beginStruct(CtorStructTy);
773 ctor.addInt(Int32Ty, I.Priority);
774 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
775 if (I.AssociatedData)
776 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
777 else
778 ctor.addNullPointer(VoidPtrTy);
John McCallf1788632016-11-28 22:18:30 +0000779 ctor.finishAndAddTo(ctors);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000780 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000781
John McCall18081af2016-11-19 20:12:25 +0000782 auto list =
783 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
784 /*constant*/ false,
785 llvm::GlobalValue::AppendingLinkage);
786
787 // The LTO linker doesn't seem to like it when we set an alignment
788 // on appending variables. Take it off as a workaround.
789 list->setAlignment(0);
790
Vassil Vassilev188ad3a2016-10-27 09:12:20 +0000791 Fns.clear();
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000792}
793
John McCalld4324142010-02-19 01:32:20 +0000794llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000795CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000796 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +0000797
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000798 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000799
Hans Wennborg275efb92014-05-28 01:52:23 +0000800 if (isa<CXXDestructorDecl>(D) &&
Reid Klecknera12cd282013-12-11 19:21:27 +0000801 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
Hans Wennborg275efb92014-05-28 01:52:23 +0000802 GD.getDtorType())) {
803 // Destructor variants in the Microsoft C++ ABI are always internal or
804 // linkonce_odr thunks emitted on an as-needed basis.
805 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
806 : llvm::GlobalValue::LinkOnceODRLinkage;
807 }
Reid Klecknera12cd282013-12-11 19:21:27 +0000808
Richard Smith5179eb72016-06-28 19:03:57 +0000809 if (isa<CXXConstructorDecl>(D) &&
810 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
811 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
812 // Our approach to inheriting constructors is fundamentally different from
813 // that used by the MS ABI, so keep our inheriting constructor thunks
814 // internal rather than trying to pick an unambiguous mangling for them.
815 return llvm::GlobalValue::InternalLinkage;
816 }
817
Hans Wennborg275efb92014-05-28 01:52:23 +0000818 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld4324142010-02-19 01:32:20 +0000819}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000820
Hans Wennborgbb4f9622015-05-28 17:44:56 +0000821void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
822 const auto *FD = cast<FunctionDecl>(GD.getDecl());
823
824 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
825 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
826 // Don't dllexport/import destructor thunks.
827 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
828 return;
829 }
830 }
831
832 if (FD->hasAttr<DLLImportAttr>())
833 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
834 else if (FD->hasAttr<DLLExportAttr>())
835 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
836 else
837 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
838}
839
Peter Collingbourne8dd14da2016-06-24 21:21:46 +0000840llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000841 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
842 if (!MDS) return nullptr;
843
Benjamin Kramer630cf8c2016-11-23 11:20:27 +0000844 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +0000845}
846
Rafael Espindolae033c8c2014-05-08 15:26:12 +0000847void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
848 llvm::Function *F) {
849 setNonAliasAttributes(D, F);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000850}
851
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000852void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000853 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000854 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000855 unsigned CallingConv;
Reid Klecknercdd26792017-04-18 23:50:03 +0000856 llvm::AttributeList PAL;
857 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
858 F->setAttributes(PAL);
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000859 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000860}
861
John McCall9b0a7ce2011-10-02 01:16:38 +0000862/// Determines whether the language options require us to model
863/// unwind exceptions. We treat -fexceptions as mandating this
864/// except under the fragile ObjC ABI with only ObjC exceptions
865/// enabled. This means, for example, that C with -fexceptions
866/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000867static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000868 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000869 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000870
871 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000872 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000873
874 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000875 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +0000876 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +0000877 }
878
879 return true;
880}
881
Daniel Dunbar38932572009-04-14 08:05:55 +0000882void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
883 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000884 llvm::AttrBuilder B;
885
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000886 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000887 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000888
David Blaikiebbafb8a2012-03-11 07:00:24 +0000889 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000890 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000891
Akira Hatanaka200500d2015-10-08 19:30:57 +0000892 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
893 B.addAttribute(llvm::Attribute::StackProtect);
894 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
895 B.addAttribute(llvm::Attribute::StackProtectStrong);
896 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
897 B.addAttribute(llvm::Attribute::StackProtectReq);
898
899 if (!D) {
Chandler Carruthfcd33142016-12-23 01:24:49 +0000900 // If we don't have a declaration to control inlining, the function isn't
901 // explicitly marked as alwaysinline for semantic reasons, and inlining is
902 // disabled, mark the function as noinline.
903 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
904 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
905 B.addAttribute(llvm::Attribute::NoInline);
906
Reid Kleckneree4930b2017-05-02 22:07:37 +0000907 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Akira Hatanaka200500d2015-10-08 19:30:57 +0000908 return;
909 }
910
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000911 // Track whether we need to add the optnone LLVM attribute,
912 // starting with the default for this optimization level.
913 bool ShouldAddOptNone =
914 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
915 // We can't add optnone in the following cases, it won't pass the verifier.
916 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
917 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
918 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
919
920 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
Chandler Carruthfcd33142016-12-23 01:24:49 +0000921 B.addAttribute(llvm::Attribute::OptimizeNone);
922
923 // OptimizeNone implies noinline; we should not be inlining such functions.
924 B.addAttribute(llvm::Attribute::NoInline);
925 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
926 "OptimizeNone and AlwaysInline on same function!");
927
928 // We still need to handle naked functions even though optnone subsumes
929 // much of their semantics.
930 if (D->hasAttr<NakedAttr>())
931 B.addAttribute(llvm::Attribute::Naked);
932
933 // OptimizeNone wins over OptimizeForSize and MinSize.
934 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
935 F->removeFnAttr(llvm::Attribute::MinSize);
936 } else if (D->hasAttr<NakedAttr>()) {
Eli Friedmanc55efe42011-08-22 23:55:33 +0000937 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000938 B.addAttribute(llvm::Attribute::Naked);
939 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +0000940 } else if (D->hasAttr<NoDuplicateAttr>()) {
941 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000942 } else if (D->hasAttr<NoInlineAttr>()) {
943 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +0000944 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Chandler Carruthfcd33142016-12-23 01:24:49 +0000945 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000946 // (noinline wins over always_inline, and we can't specify both in IR)
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +0000947 B.addAttribute(llvm::Attribute::AlwaysInline);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000948 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
949 // If we're not inlining, then force everything that isn't always_inline to
950 // carry an explicit noinline attribute.
951 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
952 B.addAttribute(llvm::Attribute::NoInline);
953 } else {
954 // Otherwise, propagate the inline hint attribute and potentially use its
955 // absence to mark things as noinline.
956 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
957 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
958 return Redecl->isInlineSpecified();
959 })) {
960 B.addAttribute(llvm::Attribute::InlineHint);
961 } else if (CodeGenOpts.getInlining() ==
962 CodeGenOptions::OnlyHintInlining &&
963 !FD->isInlined() &&
964 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
965 B.addAttribute(llvm::Attribute::NoInline);
966 }
967 }
Eli Friedmanc55efe42011-08-22 23:55:33 +0000968 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000969
Chandler Carruthfcd33142016-12-23 01:24:49 +0000970 // Add other optimization related attributes if we are optimizing this
971 // function.
972 if (!D->hasAttr<OptimizeNoneAttr>()) {
973 if (D->hasAttr<ColdAttr>()) {
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000974 if (!ShouldAddOptNone)
975 B.addAttribute(llvm::Attribute::OptimizeForSize);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000976 B.addAttribute(llvm::Attribute::Cold);
977 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000978
Chandler Carruthfcd33142016-12-23 01:24:49 +0000979 if (D->hasAttr<MinSizeAttr>())
980 B.addAttribute(llvm::Attribute::MinSize);
981 }
Richard Smithb555a762012-09-28 22:46:07 +0000982
Reid Kleckneree4930b2017-05-02 22:07:37 +0000983 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000984
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000985 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
986 if (alignment)
987 F->setAlignment(alignment);
988
Dan Gohmanc2853072015-09-03 22:51:53 +0000989 // Some C++ ABIs require 2-byte alignment for member functions, in order to
990 // reserve a bit for differentiating between virtual and non-virtual member
991 // functions. If the current target's C++ ABI requires this and this is a
992 // member function, set its alignment accordingly.
993 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
994 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
995 F->setAlignment(2);
996 }
Evgeniy Stepanovf7543092016-10-31 22:28:10 +0000997
998 // In the cross-dso CFI mode, we want !type attributes on definitions only.
999 if (CodeGenOpts.SanitizeCfiCrossDso)
1000 if (auto *FD = dyn_cast<FunctionDecl>(D))
1001 CreateFunctionTypeMetadata(FD, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001002}
1003
Mike Stump11289f42009-09-09 15:08:12 +00001004void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +00001005 llvm::GlobalValue *GV) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001006 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
Anders Carlsson072ef742011-01-29 19:41:00 +00001007 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +00001008 else
1009 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +00001010
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001011 if (D && D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +00001012 addUsedGlobal(GV);
Rafael Espindola502f65a2014-05-05 20:21:03 +00001013}
1014
Dario Domiziolic4fb8ca72014-09-19 22:06:24 +00001015void CodeGenModule::setAliasAttributes(const Decl *D,
1016 llvm::GlobalValue *GV) {
1017 SetCommonAttributes(D, GV);
1018
1019 // Process the dllexport attribute based on whether the original definition
1020 // (not necessarily the aliasee) was exported.
1021 if (D->hasAttr<DLLExportAttr>())
1022 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1023}
1024
Rafael Espindola502f65a2014-05-05 20:21:03 +00001025void CodeGenModule::setNonAliasAttributes(const Decl *D,
Rafael Espindolaee076a22014-05-13 18:45:53 +00001026 llvm::GlobalObject *GO) {
1027 SetCommonAttributes(D, GO);
Daniel Dunbar38932572009-04-14 08:05:55 +00001028
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001029 if (D)
1030 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1031 GO->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001032
Eric Christopher162c91c2015-06-05 22:03:00 +00001033 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +00001034}
1035
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +00001036void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1037 llvm::Function *F,
1038 const CGFunctionInfo &FI) {
1039 SetLLVMFunctionAttributes(D, FI, F);
1040 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +00001041
1042 F->setLinkage(llvm::Function::InternalLinkage);
1043
Rafael Espindola502f65a2014-05-05 20:21:03 +00001044 setNonAliasAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +00001045}
1046
David Majnemerf6acb762014-04-25 17:07:16 +00001047static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1048 const NamedDecl *ND) {
1049 // Set linkage and visibility in case we never see a definition.
1050 LinkageInfo LV = ND->getLinkageAndVisibility();
1051 if (LV.getLinkage() != ExternalLinkage) {
1052 // Don't set internal linkage on declarations.
1053 } else {
1054 if (ND->hasAttr<DLLImportAttr>()) {
1055 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1056 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1057 } else if (ND->hasAttr<DLLExportAttr>()) {
1058 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
David Majnemerf6acb762014-04-25 17:07:16 +00001059 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1060 // "extern_weak" is overloaded in LLVM; we probably should have
1061 // separate linkage types for this.
1062 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1063 }
1064
1065 // Set visibility on a declaration only if it's explicit.
1066 if (LV.isVisibilityExplicit())
1067 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1068 }
1069}
1070
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001071void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1072 llvm::Function *F) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001073 // Only if we are checking indirect calls.
1074 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1075 return;
1076
1077 // Non-static class methods are handled via vtable pointer checks elsewhere.
1078 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1079 return;
1080
1081 // Additionally, if building with cross-DSO support...
1082 if (CodeGenOpts.SanitizeCfiCrossDso) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001083 // Skip available_externally functions. They won't be codegen'ed in the
1084 // current module anyway.
1085 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1086 return;
1087 }
1088
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001089 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001090 F->addTypeMetadata(0, MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001091
1092 // Emit a hash-based bit set entry for cross-DSO calls.
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00001093 if (CodeGenOpts.SanitizeCfiCrossDso)
1094 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1095 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00001096}
1097
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001098void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1099 bool IsIncompleteFunction,
1100 bool IsThunk) {
Pete Cooper2f1637a2015-05-20 17:17:45 +00001101 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001102 // If this is an intrinsic function, set the function's attributes
1103 // to the intrinsic's attributes.
Pete Cooper2f1637a2015-05-20 17:17:45 +00001104 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +00001105 return;
1106 }
1107
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001108 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlsson6710c532010-02-06 02:44:09 +00001109
Eli Friedman895771a2009-05-26 01:22:57 +00001110 if (!IsIncompleteFunction)
John McCalla729c622012-02-17 03:33:10 +00001111 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +00001112
Bob Wilsonfc6297f2014-04-01 01:38:16 +00001113 // Add the Returned attribute for "this", except for iOS 5 and earlier
1114 // where substantial code, including the libstdc++ dylib, was compiled with
1115 // GCC and does not actually return "this".
David Majnemerb9bd6fb2014-11-01 05:42:23 +00001116 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00001117 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001118 assert(!F->arg_empty() &&
1119 F->arg_begin()->getType()
1120 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1121 "unexpected this return");
1122 F->addAttribute(1, llvm::Attribute::Returned);
1123 }
1124
Daniel Dunbar38932572009-04-14 08:05:55 +00001125 // Only a few attributes are set on declarations; these may later be
1126 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +00001127
David Majnemerf6acb762014-04-25 17:07:16 +00001128 setLinkageAndVisibilityForGV(F, FD);
Daniel Dunbar38932572009-04-14 08:05:55 +00001129
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001130 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +00001131 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +00001132
Richard Smith351241c2016-04-07 21:46:12 +00001133 if (FD->isReplaceableGlobalAllocationFunction()) {
1134 // A replaceable global allocation function does not act like a builtin by
1135 // default, only if it is invoked by a new-expression or delete-expression.
Reid Klecknerde864822017-03-21 16:57:30 +00001136 F->addAttribute(llvm::AttributeList::FunctionIndex,
Richard Smith8d0dc312013-07-21 23:12:18 +00001137 llvm::Attribute::NoBuiltin);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00001138
Richard Smith351241c2016-04-07 21:46:12 +00001139 // A sane operator new returns a non-aliasing pointer.
1140 // FIXME: Also add NonNull attribute to the return value
1141 // for the non-nothrow forms?
1142 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1143 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1144 (Kind == OO_New || Kind == OO_Array_New))
Reid Klecknerde864822017-03-21 16:57:30 +00001145 F->addAttribute(llvm::AttributeList::ReturnIndex,
Richard Smith351241c2016-04-07 21:46:12 +00001146 llvm::Attribute::NoAlias);
1147 }
1148
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001149 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001150 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001151 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1152 if (MD->isVirtual())
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001153 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Peter Collingbourne0446e7c2016-03-14 18:41:59 +00001154
Evgeniy Stepanovf7543092016-10-31 22:28:10 +00001155 // Don't emit entries for function declarations in the cross-DSO mode. This
1156 // is handled with better precision by the receiving DSO.
1157 if (!CodeGenOpts.SanitizeCfiCrossDso)
1158 CreateFunctionTypeMetadata(FD, F);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001159}
1160
Rafael Espindola060062a2014-03-06 22:15:10 +00001161void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +00001162 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001163 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001164 LLVMUsed.emplace_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001165}
1166
Rafael Espindola060062a2014-03-06 22:15:10 +00001167void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1168 assert(!GV->isDeclaration() &&
1169 "Only globals with definition can force usage.");
Benjamin Kramer3204b152015-05-29 19:42:19 +00001170 LLVMCompilerUsed.emplace_back(GV);
Rafael Espindola060062a2014-03-06 22:15:10 +00001171}
1172
1173static void emitUsed(CodeGenModule &CGM, StringRef Name,
Sanjoy Dase369bd92017-05-01 17:08:00 +00001174 std::vector<llvm::WeakTrackingVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001175 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +00001176 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001177 return;
1178
Rafael Espindola060062a2014-03-06 22:15:10 +00001179 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +00001180 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +00001181 UsedArray.resize(List.size());
1182 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00001183 UsedArray[i] =
Justin Holewinskif37f3d32015-02-02 21:05:49 +00001184 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1185 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +00001186 }
Mike Stump11289f42009-09-09 15:08:12 +00001187
Fariborz Jahanian248c7192009-06-23 21:47:46 +00001188 if (UsedArray.empty())
1189 return;
Rafael Espindola060062a2014-03-06 22:15:10 +00001190 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +00001191
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001192 auto *GV = new llvm::GlobalVariable(
1193 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1194 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001195
1196 GV->setSection("llvm.metadata");
1197}
1198
Rafael Espindola060062a2014-03-06 22:15:10 +00001199void CodeGenModule::emitLLVMUsed() {
1200 emitUsed(*this, "llvm.used", LLVMUsed);
1201 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1202}
1203
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001204void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001205 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001206 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1207}
1208
Aaron Ballman5d041be2013-06-04 02:07:14 +00001209void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1210 llvm::SmallString<32> Opt;
1211 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001212 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballman5d041be2013-06-04 02:07:14 +00001213 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1214}
1215
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001216void CodeGenModule::AddDependentLib(StringRef Lib) {
1217 llvm::SmallString<24> Opt;
1218 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001219 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001220 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1221}
1222
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001223/// \brief Add link options implied by the given module, including modules
1224/// it depends on, using a postorder walk.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001225static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1226 SmallVectorImpl<llvm::Metadata *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001227 llvm::SmallPtrSet<Module *, 16> &Visited) {
1228 // Import this module's parent.
David Blaikie82e95a32014-11-19 07:49:47 +00001229 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001230 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001231 }
1232
1233 // Import this module's dependencies.
1234 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001235 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001236 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001237 }
1238
1239 // Add linker options to link against the libraries/frameworks
1240 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001241 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001242 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001243 // Link against a framework. Frameworks are currently Darwin only, so we
1244 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001245 if (Mod->LinkLibraries[I-1].IsFramework) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001246 llvm::Metadata *Args[2] = {
1247 llvm::MDString::get(Context, "-framework"),
1248 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001249
1250 Metadata.push_back(llvm::MDNode::get(Context, Args));
1251 continue;
1252 }
1253
1254 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001255 llvm::SmallString<24> Opt;
1256 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1257 Mod->LinkLibraries[I-1].Library, Opt);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001258 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001259 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1260 }
1261}
1262
1263void CodeGenModule::EmitModuleLinkOptions() {
1264 // Collect the set of all of the modules we want to visit to emit link
1265 // options, which is essentially the imported modules and all of their
1266 // non-explicit child modules.
1267 llvm::SetVector<clang::Module *> LinkModules;
1268 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1269 SmallVector<clang::Module *, 16> Stack;
1270
1271 // Seed the stack with imported modules.
Manman Ren9803ee82017-01-11 18:47:38 +00001272 for (Module *M : ImportedModules) {
1273 // Do not add any link flags when an implementation TU of a module imports
1274 // a header of that same module.
1275 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1276 !getLangOpts().isCompilingModule())
1277 continue;
Yaron Kerenb54db522015-06-11 12:33:25 +00001278 if (Visited.insert(M).second)
1279 Stack.push_back(M);
Manman Ren9803ee82017-01-11 18:47:38 +00001280 }
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001281
1282 // Find all of the modules to import, making a little effort to prune
1283 // non-leaf modules.
1284 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00001285 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001286
1287 bool AnyChildren = false;
1288
1289 // Visit the submodules of this module.
1290 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1291 SubEnd = Mod->submodule_end();
1292 Sub != SubEnd; ++Sub) {
1293 // Skip explicit children; they need to be explicitly imported to be
1294 // linked against.
1295 if ((*Sub)->IsExplicit)
1296 continue;
1297
David Blaikie82e95a32014-11-19 07:49:47 +00001298 if (Visited.insert(*Sub).second) {
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001299 Stack.push_back(*Sub);
1300 AnyChildren = true;
1301 }
1302 }
1303
1304 // We didn't find any children, so add this module to the list of
1305 // modules to link against.
1306 if (!AnyChildren) {
1307 LinkModules.insert(Mod);
1308 }
1309 }
1310
1311 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001312 // order. We don't do anything to try to order import link flags with respect
1313 // to linker options inserted by things like #pragma comment().
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001314 SmallVector<llvm::Metadata *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001315 Visited.clear();
Yaron Kerenb54db522015-06-11 12:33:25 +00001316 for (Module *M : LinkModules)
1317 if (Visited.insert(M).second)
1318 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
Daniel Dunbar69e47462013-01-17 01:35:06 +00001319 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001320 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001321
Daniel Dunbar69e47462013-01-17 01:35:06 +00001322 // Add the linker options metadata flag.
1323 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001324 llvm::MDNode::get(getLLVMContext(),
1325 LinkerOptionsMetadata));
Douglas Gregorbc25ff42013-01-14 20:53:57 +00001326}
1327
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001328void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +00001329 // Emit code for any potentially referenced deferred decls. Since a
1330 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001331 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001332
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001333 if (!DeferredVTables.empty()) {
1334 EmitDeferredVTables();
John McCall6bd2a892013-01-25 22:31:03 +00001335
Eric Christopherd160c502016-01-29 01:35:53 +00001336 // Emitting a vtable doesn't directly cause more vtables to
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001337 // become deferred, although it can cause functions to be
Eric Christopherd160c502016-01-29 01:35:53 +00001338 // emitted that then need those vtables.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001339 assert(DeferredVTables.empty());
1340 }
Rafael Espindolae7113ca2010-03-10 02:19:29 +00001341
Eric Christopherd160c502016-01-29 01:35:53 +00001342 // Stop if we're out of both deferred vtables and deferred declarations.
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001343 if (DeferredDeclsToEmit.empty())
1344 return;
John McCall6bd2a892013-01-25 22:31:03 +00001345
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001346 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1347 // work, it will not interfere with this.
Sanjoy Das70a60512017-05-01 06:12:13 +00001348 std::vector<GlobalDecl> CurDeclsToEmit;
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001349 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1350
Sanjoy Das70a60512017-05-01 06:12:13 +00001351 for (GlobalDecl &D : CurDeclsToEmit) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00001352 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1353 // to get GlobalValue with exactly the type we need, not something that
1354 // might had been created for another decl with the same mangled name but
1355 // different type.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001356 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
John McCalld195d4c2016-11-30 23:25:13 +00001357 GetAddrOfGlobal(D, ForDefinition));
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001358
1359 // In case of different address spaces, we may still get a cast, even with
1360 // IsForDefinition equal to true. Query mangled names table to get
1361 // GlobalValue.
1362 if (!GV)
1363 GV = GetGlobalValue(getMangledName(D));
1364
1365 // Make sure GetGlobalValue returned non-null.
1366 assert(GV);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001367
John McCallc2af9392010-05-27 01:45:30 +00001368 // Check to see if we've already emitted this. This is necessary
1369 // for a couple of reasons: first, decls can end up in the
1370 // deferred-decls queue multiple times, and second, decls can end
1371 // up with definitions in unusual ways (e.g. by an extern inline
1372 // function acquiring a strong function redefinition). Just
1373 // ignore these cases.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001374 if (!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +00001375 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001376
Chris Lattner45470942009-03-21 09:44:56 +00001377 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001378 EmitGlobalDefinition(D, GV);
Rafael Espindolae5df59f2015-01-22 00:24:57 +00001379
1380 // If we found out that we need to emit more decls, do that recursively.
1381 // This has the advantage that the decls are emitted in a DFS and related
1382 // ones are close together, which is convenient for testing.
1383 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1384 EmitDeferred();
1385 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1386 }
Chris Lattner45470942009-03-21 09:44:56 +00001387 }
Chris Lattnerbed31442007-05-28 01:07:47 +00001388}
Chris Lattner09153c02007-06-22 18:48:09 +00001389
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001390void CodeGenModule::EmitVTablesOpportunistically() {
1391 // Try to emit external vtables as available_externally if they have emitted
1392 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1393 // is not allowed to create new references to things that need to be emitted
1394 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1395
1396 assert(OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables() &&
1397 "Only emit opportunistic vtables with optimizations");
1398
1399 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1400 assert(getVTables().isVTableExternal(RD) &&
1401 "This queue should only contain external vtables");
1402 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1403 VTables.GenerateClassData(RD);
1404 }
1405 OpportunisticVTables.clear();
1406}
1407
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001408void CodeGenModule::EmitGlobalAnnotations() {
1409 if (Annotations.empty())
1410 return;
1411
1412 // Create a new global variable for the ConstantStruct in the Module.
1413 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1414 Annotations[0]->getType(), Annotations.size()), Annotations);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001415 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1416 llvm::GlobalValue::AppendingLinkage,
1417 Array, "llvm.global.annotations");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001418 gv->setSection(AnnotationSection);
1419}
1420
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001421llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001422 llvm::Constant *&AStr = AnnotationStrings[Str];
1423 if (AStr)
1424 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001425
1426 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001427 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001428 auto *gv =
1429 new llvm::GlobalVariable(getModule(), s->getType(), true,
1430 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001431 gv->setSection(AnnotationSection);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00001432 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Benjamin Kramereed80612013-11-10 16:55:11 +00001433 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001434 return gv;
1435}
1436
1437llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1438 SourceManager &SM = getContext().getSourceManager();
1439 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1440 if (PLoc.isValid())
1441 return EmitAnnotationString(PLoc.getFilename());
1442 return EmitAnnotationString(SM.getBufferName(Loc));
1443}
1444
1445llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1446 SourceManager &SM = getContext().getSourceManager();
1447 PresumedLoc PLoc = SM.getPresumedLoc(L);
1448 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1449 SM.getExpansionLineNumber(L);
1450 return llvm::ConstantInt::get(Int32Ty, LineNo);
1451}
1452
Mike Stump11289f42009-09-09 15:08:12 +00001453llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001454 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001455 SourceLocation L) {
1456 // Get the globals for file name, annotation, and the line number.
1457 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1458 *UnitGV = EmitAnnotationUnit(L),
1459 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001460
Daniel Dunbar346892a2009-04-14 22:41:13 +00001461 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001462 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001463 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1464 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1465 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1466 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001467 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001468 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001469}
1470
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001471void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1472 llvm::GlobalValue *GV) {
1473 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1474 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001475 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1476 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001477}
1478
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001479bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1480 SourceLocation Loc) const {
1481 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1482 // Blacklist by function name.
1483 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1484 return true;
1485 // Blacklist by location.
Yaron Kerened1fe5d2015-10-03 05:15:57 +00001486 if (Loc.isValid())
Alexey Samsonov1444bb92014-10-17 00:20:19 +00001487 return SanitizerBL.isBlacklistedLocation(Loc);
1488 // If location is unknown, this may be a compiler-generated function. Assume
1489 // it's located in the main file.
1490 auto &SM = Context.getSourceManager();
1491 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1492 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1493 }
1494 return false;
1495}
1496
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001497bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1498 SourceLocation Loc, QualType Ty,
1499 StringRef Category) const {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001500 // For now globals can be blacklisted only in ASan and KASan.
1501 if (!LangOpts.Sanitize.hasOneOf(
1502 SanitizerKind::Address | SanitizerKind::KernelAddress))
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00001503 return false;
1504 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1505 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1506 return true;
1507 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1508 return true;
1509 // Check global type.
1510 if (!Ty.isNull()) {
1511 // Drill down the array types: if global variable of a fixed type is
1512 // blacklisted, we also don't instrument arrays of them.
1513 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1514 Ty = AT->getElementType();
1515 Ty = Ty.getCanonicalType().getUnqualifiedType();
1516 // We allow to blacklist only record types (classes, structs etc.)
1517 if (Ty->isRecordType()) {
1518 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1519 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1520 return true;
1521 }
1522 }
1523 return false;
1524}
1525
Dean Michael Berris835832d2017-03-30 00:29:36 +00001526bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1527 StringRef Category) const {
1528 if (!LangOpts.XRayInstrument)
1529 return false;
1530 const auto &XRayFilter = getContext().getXRayFilter();
1531 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1532 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1533 if (Loc.isValid())
1534 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1535 if (Attr == ImbueAttr::NONE)
1536 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1537 switch (Attr) {
1538 case ImbueAttr::NONE:
1539 return false;
1540 case ImbueAttr::ALWAYS:
1541 Fn->addFnAttr("function-instrument", "xray-always");
1542 break;
Dean Michael Berris170429e2017-05-24 05:46:36 +00001543 case ImbueAttr::ALWAYS_ARG1:
1544 Fn->addFnAttr("function-instrument", "xray-always");
1545 Fn->addFnAttr("xray-log-args", "1");
1546 break;
Dean Michael Berris835832d2017-03-30 00:29:36 +00001547 case ImbueAttr::NEVER:
1548 Fn->addFnAttr("function-instrument", "xray-never");
1549 break;
1550 }
1551 return true;
1552}
1553
Hans Wennborg43a0f992015-01-10 01:19:48 +00001554bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001555 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001556 if (LangOpts.EmitAllDecls)
Hans Wennborg43a0f992015-01-10 01:19:48 +00001557 return true;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001558
Hans Wennborg43a0f992015-01-10 01:19:48 +00001559 return getContext().DeclMustBeEmitted(Global);
1560}
1561
1562bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1563 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1564 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1565 // Implicit template instantiations may change linkage if they are later
1566 // explicitly instantiated, so they should not be emitted eagerly.
1567 return false;
Richard Smithd9b90092016-07-02 01:32:16 +00001568 if (const auto *VD = dyn_cast<VarDecl>(Global))
1569 if (Context.getInlineVariableDefinitionKind(VD) ==
1570 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1571 // A definition of an inline constexpr static data member may change
1572 // linkage later if it's redeclared outside the class.
1573 return false;
Samuel Antaof8b50122015-07-13 22:54:53 +00001574 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1575 // codegen for global variables, because they may be marked as threadprivate.
1576 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1577 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1578 return false;
Hans Wennborg43a0f992015-01-10 01:19:48 +00001579
1580 return true;
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001581}
1582
John McCall7f416cc2015-09-08 08:05:57 +00001583ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
Nico Webercf4ff5862012-10-11 10:13:44 +00001584 const CXXUuidofExpr* E) {
1585 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1586 // well-formed.
David Majnemer2041b462016-03-28 03:19:50 +00001587 StringRef Uuid = E->getUuidStr();
David Majnemercf963ce2013-08-09 08:35:59 +00001588 std::string Name = "_GUID_" + Uuid.lower();
1589 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001590
David Majnemer65687602016-03-27 04:46:14 +00001591 // The UUID descriptor should be pointer aligned.
1592 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
John McCall7f416cc2015-09-08 08:05:57 +00001593
Nico Webercf4ff5862012-10-11 10:13:44 +00001594 // Look for an existing global.
1595 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
John McCall7f416cc2015-09-08 08:05:57 +00001596 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001597
Nico Weber17d3a2c2014-09-08 16:26:36 +00001598 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Webercf4ff5862012-10-11 10:13:44 +00001599 assert(Init && "failed to initialize as constant");
1600
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001601 auto *GV = new llvm::GlobalVariable(
David Majnemerbbecd092013-08-15 19:59:14 +00001602 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001603 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00001604 if (supportsCOMDAT())
1605 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
John McCall7f416cc2015-09-08 08:05:57 +00001606 return ConstantAddress(GV, Alignment);
Nico Webercf4ff5862012-10-11 10:13:44 +00001607}
1608
John McCall7f416cc2015-09-08 08:05:57 +00001609ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001610 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1611 assert(AA && "No alias?");
1612
John McCall7f416cc2015-09-08 08:05:57 +00001613 CharUnits Alignment = getContext().getDeclAlign(VD);
Chris Lattner2192fe52011-07-18 04:24:23 +00001614 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001615
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001616 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001617 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001618 if (Entry) {
1619 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
John McCall7f416cc2015-09-08 08:05:57 +00001620 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1621 return ConstantAddress(Ptr, Alignment);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001622 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001623
1624 llvm::Constant *Aliasee;
1625 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001626 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1627 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001628 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001629 else
John McCall7ec50432010-03-19 23:29:14 +00001630 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00001631 llvm::PointerType::getUnqual(DeclTy),
1632 nullptr);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001633
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001634 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001635 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1636 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001637
John McCall7f416cc2015-09-08 08:05:57 +00001638 return ConstantAddress(Aliasee, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001639}
1640
Chris Lattnere0be0df2009-05-12 21:21:08 +00001641void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001642 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001643
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001644 // Weak references don't produce any output by themselves.
1645 if (Global->hasAttr<WeakRefAttr>())
1646 return;
1647
Chris Lattner54041692009-03-22 21:47:11 +00001648 // If this is an alias definition (which otherwise looks like a declaration)
1649 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001650 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001651 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001652
Dmitry Polukhin85eda122016-04-11 07:48:59 +00001653 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1654 if (Global->hasAttr<IFuncAttr>())
1655 return emitIFuncDefinition(GD);
1656
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001657 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001658 if (LangOpts.CUDA) {
Artem Belevichf3d3db62015-03-19 18:58:18 +00001659 if (LangOpts.CUDAIsDevice) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001660 if (!Global->hasAttr<CUDADeviceAttr>() &&
1661 !Global->hasAttr<CUDAGlobalAttr>() &&
1662 !Global->hasAttr<CUDAConstantAttr>() &&
1663 !Global->hasAttr<CUDASharedAttr>())
1664 return;
1665 } else {
Artem Belevich42e19492016-03-02 18:28:50 +00001666 // We need to emit host-side 'shadows' for all global
1667 // device-side variables because the CUDA runtime needs their
1668 // size and host-side address in order to provide access to
1669 // their device-side incarnations.
1670
1671 // So device-only functions are the only things we skip.
1672 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1673 Global->hasAttr<CUDADeviceAttr>())
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001674 return;
Artem Belevich42e19492016-03-02 18:28:50 +00001675
1676 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1677 "Expected Variable or Function");
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001678 }
1679 }
1680
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001681 if (LangOpts.OpenMP) {
1682 // If this is OpenMP device, check if it is legal to emit this global
1683 // normally.
1684 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1685 return;
1686 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1687 if (MustBeEmitted(Global))
1688 EmitOMPDeclareReduction(DRD);
1689 return;
1690 }
1691 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001692
Chris Lattner45470942009-03-21 09:44:56 +00001693 // Ignore declarations, they will be emitted on their first use.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001694 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001695 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001696 if (!FD->doesThisDeclarationHaveABody()) {
1697 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1698 return;
1699
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001700 StringRef MangledName = getMangledName(GD);
David Majnemeraf369802014-03-29 14:19:55 +00001701
1702 // Compute the function info and LLVM type.
1703 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1704 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1705
1706 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1707 /*DontDefer=*/false);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001708 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001709 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001710 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001711 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001712 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
Artem Belevich42e19492016-03-02 18:28:50 +00001713 // We need to emit device-side global CUDA variables even if a
1714 // variable does not have a definition -- we still need to define
1715 // host-side shadow for it.
1716 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1717 !VD->hasDefinition() &&
1718 (VD->hasAttr<CUDAConstantAttr>() ||
1719 VD->hasAttr<CUDADeviceAttr>());
1720 if (!MustEmitForCuda &&
1721 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
Richard Smithd9b90092016-07-02 01:32:16 +00001722 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1723 // If this declaration may have caused an inline variable definition to
1724 // change linkage, make sure that it's emitted.
1725 if (Context.getInlineVariableDefinitionKind(VD) ==
1726 ASTContext::InlineVariableDefinitionKind::Strong)
1727 GetAddrOfGlobalVar(VD);
Douglas Gregorbeecd582009-04-21 17:11:58 +00001728 return;
Richard Smithd9b90092016-07-02 01:32:16 +00001729 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001730 }
1731
Hans Wennborg43a0f992015-01-10 01:19:48 +00001732 // Defer code generation to first use when possible, e.g. if this is an inline
1733 // function. If the global must always be emitted, do it eagerly if possible
1734 // to benefit from cache locality.
1735 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001736 // Emit the definition if it can't be deferred.
1737 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001738 return;
1739 }
John McCall70013b62010-07-15 23:40:35 +00001740
1741 // If we're deferring emission of a C++ variable with an
1742 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001743 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00001744 cast<VarDecl>(Global)->hasInit()) {
1745 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Craig Topper8a13c412014-05-21 05:09:00 +00001746 CXXGlobalInits.push_back(nullptr);
John McCall70013b62010-07-15 23:40:35 +00001747 }
Hans Wennborg43a0f992015-01-10 01:19:48 +00001748
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001749 StringRef MangledName = getMangledName(GD);
Sanjoy Das70a60512017-05-01 06:12:13 +00001750 if (GetGlobalValue(MangledName) != nullptr) {
Hans Wennborg43a0f992015-01-10 01:19:48 +00001751 // The value has already been used and should therefore be emitted.
Sanjoy Das70a60512017-05-01 06:12:13 +00001752 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001753 } else if (MustBeEmitted(Global)) {
1754 // The value must be emitted, but cannot be emitted eagerly.
1755 assert(!MayBeEmittedEagerly(Global));
Sanjoy Das70a60512017-05-01 06:12:13 +00001756 addDeferredDeclToEmit(GD);
Hans Wennborg43a0f992015-01-10 01:19:48 +00001757 } else {
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001758 // Otherwise, remember that we saw a deferred decl with this name. The
1759 // first use of the mangled name will cause it to move into
1760 // DeferredDeclsToEmit.
1761 DeferredDecls[MangledName] = GD;
1762 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001763}
1764
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001765// Check if T is a class type with a destructor that's not dllimport.
1766static bool HasNonDllImportDtor(QualType T) {
1767 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1768 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1769 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1770 return true;
1771
1772 return false;
1773}
1774
Rafael Espindolac5941352011-10-26 20:41:06 +00001775namespace {
1776 struct FunctionIsDirectlyRecursive :
1777 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1778 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001779 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00001780 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001781 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1782 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001783 }
1784 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1785
1786 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001787 const FunctionDecl *FD = E->getDirectCallee();
1788 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00001789 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001790 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1791 if (Attr && Name == Attr->getLabel()) {
1792 Result = true;
1793 return false;
1794 }
1795 unsigned BuiltinID = FD->getBuiltinID();
David Majnemer41011f62015-06-25 23:50:40 +00001796 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
Rafael Espindolac5941352011-10-26 20:41:06 +00001797 return true;
Eric Christopher02d5d862015-08-06 01:01:12 +00001798 StringRef BuiltinName = BI.getName(BuiltinID);
Nick Lewycky9ed5b152012-01-18 03:41:19 +00001799 if (BuiltinName.startswith("__builtin_") &&
1800 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001801 Result = true;
1802 return false;
1803 }
1804 return true;
1805 }
1806 };
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001807
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001808 // Make sure we're not referencing non-imported vars or functions.
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001809 struct DLLImportFunctionVisitor
1810 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1811 bool SafeToInline = true;
1812
Hans Wennborg1b3aee72016-09-13 22:51:42 +00001813 bool shouldVisitImplicitCode() const { return true; }
1814
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001815 bool VisitVarDecl(VarDecl *VD) {
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001816 if (VD->getTLSKind()) {
1817 // A thread-local variable cannot be imported.
1818 SafeToInline = false;
1819 return SafeToInline;
1820 }
1821
1822 // A variable definition might imply a destructor call.
1823 if (VD->isThisDeclarationADefinition())
1824 SafeToInline = !HasNonDllImportDtor(VD->getType());
1825
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001826 return SafeToInline;
1827 }
1828
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001829 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1830 if (const auto *D = E->getTemporary()->getDestructor())
1831 SafeToInline = D->hasAttr<DLLImportAttr>();
1832 return SafeToInline;
1833 }
1834
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001835 bool VisitDeclRefExpr(DeclRefExpr *E) {
1836 ValueDecl *VD = E->getDecl();
1837 if (isa<FunctionDecl>(VD))
1838 SafeToInline = VD->hasAttr<DLLImportAttr>();
1839 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1840 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1841 return SafeToInline;
1842 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001843
Hans Wennborg1b3aee72016-09-13 22:51:42 +00001844 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1845 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1846 return SafeToInline;
1847 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001848
Hans Wennborg251c2042017-01-23 23:57:50 +00001849 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1850 CXXMethodDecl *M = E->getMethodDecl();
1851 if (!M) {
1852 // Call through a pointer to member function. This is safe to inline.
1853 SafeToInline = true;
1854 } else {
1855 SafeToInline = M->hasAttr<DLLImportAttr>();
1856 }
1857 return SafeToInline;
1858 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001859
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001860 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1861 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1862 return SafeToInline;
1863 }
Hans Wennborgcac8ce02017-02-15 23:28:10 +00001864
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001865 bool VisitCXXNewExpr(CXXNewExpr *E) {
1866 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1867 return SafeToInline;
1868 }
1869 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001870}
Rafael Espindolac5941352011-10-26 20:41:06 +00001871
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001872// isTriviallyRecursive - Check if this function calls another
1873// decl that, because of the asm attribute or the other decl being a builtin,
1874// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00001875bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001876CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1877 StringRef Name;
1878 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00001879 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001880 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1881 if (!Attr)
1882 return false;
1883 Name = Attr->getLabel();
1884 } else {
1885 Name = FD->getName();
1886 }
Rafael Espindolac5941352011-10-26 20:41:06 +00001887
David Majnemer64b0bdf2015-06-30 04:41:18 +00001888 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001889 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00001890 return Walker.Result;
1891}
1892
Hans Wennborg93f75472016-09-13 21:08:20 +00001893bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001894 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00001895 return true;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001896 const auto *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00001897 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00001898 return false;
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001899
1900 if (F->hasAttr<DLLImportAttr>()) {
1901 // Check whether it would be safe to inline this dllimport function.
1902 DLLImportFunctionVisitor Visitor;
1903 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1904 if (!Visitor.SafeToInline)
1905 return false;
Hans Wennborg93f75472016-09-13 21:08:20 +00001906
1907 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1908 // Implicit destructor invocations aren't captured in the AST, so the
1909 // check above can't see them. Check for them manually here.
1910 for (const Decl *Member : Dtor->getParent()->decls())
1911 if (isa<FieldDecl>(Member))
1912 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1913 return false;
1914 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1915 if (HasNonDllImportDtor(B.getType()))
1916 return false;
1917 }
Hans Wennborg6eaa8322015-08-28 21:47:01 +00001918 }
1919
Rafael Espindolac5941352011-10-26 20:41:06 +00001920 // PR9614. Avoid cases where the source code is lying to us. An available
1921 // externally function should have an equivalent function somewhere else,
1922 // but a function that calls itself is clearly not equivalent to the real
1923 // implementation.
1924 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001925 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00001926}
1927
Piotr Padlewskid3b1cbd2017-06-01 08:04:05 +00001928bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
1929 return CodeGenOpts.OptimizationLevel > 0;
1930}
1931
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001932void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001933 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001934
Dan Gohman145f3f12010-04-19 16:39:44 +00001935 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00001936 Context.getSourceManager(),
1937 "Generating code for declaration");
1938
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001939 if (isa<FunctionDecl>(D)) {
Douglas Gregora700f682010-07-13 06:02:28 +00001940 // At -O0, don't generate IR for functions with available_externally
1941 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001942 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00001943 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00001944
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001945 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman49a94b12011-05-06 17:27:27 +00001946 // Make sure to emit the definition(s) before we emit the thunks.
1947 // This is necessary for the generation of certain thunks.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001948 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00001949 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001950 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Rafael Espindola91f68b42014-09-15 19:20:10 +00001951 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman49a94b12011-05-06 17:27:27 +00001952 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001953 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00001954
Douglas Gregora700f682010-07-13 06:02:28 +00001955 if (Method->isVirtual())
1956 getVTables().EmitThunks(GD);
1957
Eli Friedman49a94b12011-05-06 17:27:27 +00001958 return;
Douglas Gregora700f682010-07-13 06:02:28 +00001959 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001960
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001961 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00001962 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001963
1964 if (const auto *VD = dyn_cast<VarDecl>(D))
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00001965 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001966
David Blaikie83d382b2011-09-23 05:06:16 +00001967 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00001968}
1969
Andrey Bokhankocab58582015-08-31 13:20:44 +00001970static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1971 llvm::Function *NewFn);
1972
Chris Lattnerd4808922009-03-22 21:03:39 +00001973/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1974/// module, create and return an llvm Function with the specified type. If there
1975/// is something in the module with the specified name, return it potentially
1976/// bitcasted to the right type.
1977///
1978/// If D is non-null, it specifies a decl that correspond to this. This is used
1979/// to set the attributes on the function when it is first created.
Reid Klecknerde864822017-03-21 16:57:30 +00001980llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
1981 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
1982 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
1983 ForDefinition_t IsForDefinition) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001984 const Decl *D = GD.getDecl();
1985
Chris Lattnera85d68e2009-03-21 09:25:43 +00001986 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001987 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001988 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001989 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001990 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001991 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001992 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001993 }
1994
Hans Wennborg0a20f542014-08-29 00:16:06 +00001995 // Handle dropped DLL attributes.
1996 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1997 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1998
Andrey Bokhankocab58582015-08-31 13:20:44 +00001999 // If there are two attempts to define the same mangled name, issue an
2000 // error.
2001 if (IsForDefinition && !Entry->isDeclaration()) {
2002 GlobalDecl OtherGD;
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002003 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2004 // to make sure that we issue an error only once.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002005 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2006 (GD.getCanonicalDecl().getDecl() !=
2007 OtherGD.getCanonicalDecl().getDecl()) &&
2008 DiagnosedConflictingDefinitions.insert(GD).second) {
2009 getDiags().Report(D->getLocation(),
2010 diag::err_duplicate_mangled_name);
2011 getDiags().Report(OtherGD.getDecl()->getLocation(),
2012 diag::note_previous_definition);
2013 }
2014 }
2015
2016 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2017 (Entry->getType()->getElementType() == Ty)) {
Chris Lattnera85d68e2009-03-21 09:25:43 +00002018 return Entry;
Andrey Bokhankocab58582015-08-31 13:20:44 +00002019 }
Mike Stump11289f42009-09-09 15:08:12 +00002020
Chris Lattnera85d68e2009-03-21 09:25:43 +00002021 // Make sure the result is of the correct type.
Andrey Bokhankocab58582015-08-31 13:20:44 +00002022 // (If function is requested for a definition, we always need to create a new
2023 // function, not just return a bitcast.)
2024 if (!IsForDefinition)
2025 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00002026 }
Mike Stump11289f42009-09-09 15:08:12 +00002027
Eli Friedmancc522d92009-11-09 05:07:37 +00002028 // This function doesn't have a complete type (for example, the return
2029 // type is an incomplete struct). Use a fake type instead, and make
2030 // sure not to try to set attributes.
2031 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00002032
Chris Lattner2192fe52011-07-18 04:24:23 +00002033 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00002034 if (isa<llvm::FunctionType>(Ty)) {
2035 FTy = cast<llvm::FunctionType>(Ty);
2036 } else {
John McCall9dc0db22011-05-15 01:53:33 +00002037 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00002038 IsIncompleteFunction = true;
2039 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002040
2041 llvm::Function *F =
2042 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2043 Entry ? StringRef() : MangledName, &getModule());
2044
2045 // If we already created a function with the same mangled name (but different
2046 // type) before, take its name and add it to the list of functions to be
2047 // replaced with F at the end of CodeGen.
2048 //
2049 // This happens if there is a prototype for a function (e.g. "int f()") and
2050 // then a definition of a different type (e.g. "int f(int x)").
2051 if (Entry) {
2052 F->takeName(Entry);
2053
2054 // This might be an implementation of a function without a prototype, in
2055 // which case, try to do special replacement of calls which match the new
2056 // prototype. The really key thing here is that we also potentially drop
2057 // arguments from the call site so as to make a direct call, which makes the
2058 // inliner happier and suppresses a number of optimizer warnings (!) about
2059 // dropping arguments.
2060 if (!Entry->use_empty()) {
2061 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2062 Entry->removeDeadConstantUsers();
2063 }
2064
2065 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2066 F, Entry->getType()->getElementType()->getPointerTo());
2067 addGlobalValReplacement(Entry, BC);
2068 }
2069
John McCall7ec50432010-03-19 23:29:14 +00002070 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00002071 if (D)
David Majnemerb9bd6fb2014-11-01 05:42:23 +00002072 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Reid Klecknerde864822017-03-21 16:57:30 +00002073 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2074 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
Reid Kleckneree4930b2017-05-02 22:07:37 +00002075 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
Bill Wendling9a677922013-01-23 00:21:06 +00002076 }
Eli Friedmancc522d92009-11-09 05:07:37 +00002077
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002078 if (!DontDefer) {
2079 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2080 // each other bottoming out with the base dtor. Therefore we emit non-base
2081 // dtors on usage, even if there is no dtor definition in the TU.
2082 if (D && isa<CXXDestructorDecl>(D) &&
2083 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2084 GD.getDtorType()))
Sanjoy Das70a60512017-05-01 06:12:13 +00002085 addDeferredDeclToEmit(GD);
John McCall357d0f32010-12-15 04:00:32 +00002086
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002087 // This is the first use or definition of a mangled name. If there is a
2088 // deferred decl with this name, remember that we need to emit it at the end
2089 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002090 auto DDI = DeferredDecls.find(MangledName);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002091 if (DDI != DeferredDecls.end()) {
2092 // Move the potentially referenced deferred decl to the
2093 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2094 // don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002095 addDeferredDeclToEmit(DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002096 DeferredDecls.erase(DDI);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002097
2098 // Otherwise, there are cases we have to worry about where we're
2099 // using a declaration for which we must emit a definition but where
2100 // we might not find a top-level definition:
2101 // - member functions defined inline in their classes
2102 // - friend functions defined inline in some class
2103 // - special member functions with implicit definitions
2104 // If we ever change our AST traversal to walk into class methods,
2105 // this will be unnecessary.
2106 //
2107 // We also don't emit a definition for a function if it's going to be an
Richard Smith46bb5812014-08-01 01:56:39 +00002108 // entry in a vtable, unless it's already marked as used.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002109 } else if (getLangOpts().CPlusPlus && D) {
2110 // Look for a declaration that's lexically in a record.
Richard Smith46bb5812014-08-01 01:56:39 +00002111 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2112 FD = FD->getPreviousDecl()) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002113 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Richard Smith46bb5812014-08-01 01:56:39 +00002114 if (FD->doesThisDeclarationHaveABody()) {
Sanjoy Das70a60512017-05-01 06:12:13 +00002115 addDeferredDeclToEmit(GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002116 break;
2117 }
John McCall357d0f32010-12-15 04:00:32 +00002118 }
Richard Smith46bb5812014-08-01 01:56:39 +00002119 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002120 }
Chris Lattner45470942009-03-21 09:44:56 +00002121 }
Mike Stump11289f42009-09-09 15:08:12 +00002122
John McCalld06fb862010-04-28 00:00:30 +00002123 // Make sure the result is of the requested type.
2124 if (!IsIncompleteFunction) {
2125 assert(F->getType()->getElementType() == Ty);
2126 return F;
2127 }
2128
Chris Lattnera5f58b02011-07-09 17:41:47 +00002129 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00002130 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00002131}
2132
Chris Lattnerd4808922009-03-22 21:03:39 +00002133/// GetAddrOfFunction - Return the address of the given function. If Ty is
2134/// non-null, then this function will use the specified type if it has to
2135/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00002136llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00002137 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002138 bool ForVTable,
Andrey Bokhankocab58582015-08-31 13:20:44 +00002139 bool DontDefer,
John McCalld195d4c2016-11-30 23:25:13 +00002140 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002141 // If there was no specific requested type, just convert it now.
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002142 if (!Ty) {
2143 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2144 auto CanonTy = Context.getCanonicalType(FD->getType());
2145 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2146 }
Andrey Bokhankocab58582015-08-31 13:20:44 +00002147
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002148 StringRef MangledName = getMangledName(GD);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002149 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +00002150 /*IsThunk=*/false, llvm::AttributeList(),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002151 IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002152}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002153
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002154static const FunctionDecl *
2155GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2156 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2157 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2158
2159 IdentifierInfo &CII = C.Idents.get(Name);
2160 for (const auto &Result : DC->lookup(&CII))
2161 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2162 return FD;
2163
2164 if (!C.getLangOpts().CPlusPlus)
2165 return nullptr;
2166
2167 // Demangle the premangled name from getTerminateFn()
2168 IdentifierInfo &CXXII =
2169 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2170 ? C.Idents.get("terminate")
2171 : C.Idents.get(Name);
2172
2173 for (const auto &N : {"__cxxabiv1", "std"}) {
2174 IdentifierInfo &NS = C.Idents.get(N);
2175 for (const auto &Result : DC->lookup(&NS)) {
2176 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2177 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2178 for (const auto &Result : LSD->lookup(&NS))
2179 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2180 break;
2181
2182 if (ND)
2183 for (const auto &Result : ND->lookup(&CXXII))
2184 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2185 return FD;
2186 }
2187 }
2188
2189 return nullptr;
2190}
2191
Chris Lattnerd4808922009-03-22 21:03:39 +00002192/// CreateRuntimeFunction - Create a new runtime function with the specified
2193/// type and name.
2194llvm::Constant *
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002195CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
Reid Klecknerde864822017-03-21 16:57:30 +00002196 llvm::AttributeList ExtraAttrs,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002197 bool Local) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002198 llvm::Constant *C =
2199 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002200 /*DontDefer=*/false, /*IsThunk=*/false,
2201 ExtraAttrs);
2202
2203 if (auto *F = dyn_cast<llvm::Function>(C)) {
2204 if (F->empty()) {
John McCall882987f2013-02-28 19:01:20 +00002205 F->setCallingConv(getRuntimeCC());
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00002206
2207 if (!Local && getTriple().isOSBinFormatCOFF() &&
2208 !getCodeGenOpts().LTOVisibilityPublicStd) {
2209 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2210 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2211 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2212 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2213 }
2214 }
2215 }
2216 }
2217
John McCall882987f2013-02-28 19:01:20 +00002218 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00002219}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002220
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002221/// CreateBuiltinFunction - Create a new builtin function with the specified
2222/// type and name.
2223llvm::Constant *
Reid Klecknerde864822017-03-21 16:57:30 +00002224CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2225 llvm::AttributeList ExtraAttrs) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00002226 llvm::Constant *C =
2227 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2228 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2229 if (auto *F = dyn_cast<llvm::Function>(C))
2230 if (F->empty())
2231 F->setCallingConv(getBuiltinCC());
2232 return C;
2233}
2234
Richard Smithe070fd22012-02-17 06:48:11 +00002235/// isTypeConstant - Determine whether an object of this type can be emitted
2236/// as a constant.
2237///
2238/// If ExcludeCtor is true, the duration when the object's constructor runs
2239/// will not be considered. The caller will need to verify that the object is
2240/// not written to during its construction.
2241bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2242 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00002243 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00002244
David Blaikiebbafb8a2012-03-11 07:00:24 +00002245 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00002246 if (const CXXRecordDecl *Record
2247 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2248 return ExcludeCtor && !Record->hasMutableFields() &&
2249 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00002250 }
Richard Smithe070fd22012-02-17 06:48:11 +00002251
Eli Friedmanb095e152009-12-11 21:23:03 +00002252 return true;
2253}
2254
Chris Lattnerd4808922009-03-22 21:03:39 +00002255/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2256/// create and return an llvm GlobalVariable with the specified type. If there
2257/// is something in the module with the specified name, return it potentially
2258/// bitcasted to the right type.
2259///
2260/// If D is non-null, it specifies a decl that correspond to this. This is used
2261/// to set the attributes on the global when it is first created.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002262///
2263/// If IsForDefinition is true, it is guranteed that an actual global with
2264/// type Ty will be returned, not conversion of a variable with the same
2265/// mangled name but some other type.
John McCall7ec50432010-03-19 23:29:14 +00002266llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002267CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00002268 llvm::PointerType *Ty,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002269 const VarDecl *D,
John McCalld195d4c2016-11-30 23:25:13 +00002270 ForDefinition_t IsForDefinition) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00002271 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00002272 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00002273 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00002274 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002275 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00002276 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002277 }
2278
Hans Wennborg0a20f542014-08-29 00:16:06 +00002279 // Handle dropped DLL attributes.
2280 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2281 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2282
Chris Lattnerd4808922009-03-22 21:03:39 +00002283 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00002284 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00002285
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002286 // If there are two attempts to define the same mangled name, issue an
2287 // error.
2288 if (IsForDefinition && !Entry->isDeclaration()) {
2289 GlobalDecl OtherGD;
2290 const VarDecl *OtherD;
2291
2292 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2293 // to make sure that we issue an error only once.
Artem Belevich2c323a02016-05-19 18:00:18 +00002294 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002295 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2296 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2297 OtherD->hasInit() &&
2298 DiagnosedConflictingDefinitions.insert(D).second) {
2299 getDiags().Report(D->getLocation(),
2300 diag::err_duplicate_mangled_name);
2301 getDiags().Report(OtherGD.getDecl()->getLocation(),
2302 diag::note_previous_definition);
2303 }
2304 }
2305
Chris Lattner3bfce182009-03-21 08:03:33 +00002306 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00002307 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2308 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2309
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002310 // (If global is requested for a definition, we always need to create a new
2311 // global, not just return a bitcast.)
2312 if (!IsForDefinition)
2313 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00002314 }
Mike Stump11289f42009-09-09 15:08:12 +00002315
Rafael Espindolac0ff7442013-12-09 14:59:08 +00002316 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002317 auto *GV = new llvm::GlobalVariable(
2318 getModule(), Ty->getElementType(), false,
Craig Topper8a13c412014-05-21 05:09:00 +00002319 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002320 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00002321
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002322 // If we already created a global with the same mangled name (but different
2323 // type) before, take its name and remove it from its parent.
2324 if (Entry) {
2325 GV->takeName(Entry);
2326
2327 if (!Entry->use_empty()) {
2328 llvm::Constant *NewPtrForOldDecl =
2329 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2330 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2331 }
2332
2333 Entry->eraseFromParent();
2334 }
2335
Chris Lattner45470942009-03-21 09:44:56 +00002336 // This is the first use or definition of a mangled name. If there is a
2337 // deferred decl with this name, remember that we need to emit it at the end
2338 // of the file.
Alp Tokerfb8d02b2014-06-05 22:10:59 +00002339 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00002340 if (DDI != DeferredDecls.end()) {
2341 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2342 // list, and remove it from DeferredDecls (since we don't need it anymore).
Sanjoy Das70a60512017-05-01 06:12:13 +00002343 addDeferredDeclToEmit(DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00002344 DeferredDecls.erase(DDI);
2345 }
Mike Stump11289f42009-09-09 15:08:12 +00002346
Chris Lattner3bfce182009-03-21 08:03:33 +00002347 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00002348 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00002349 // FIXME: This code is overly simple and should be merged with other global
2350 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00002351 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00002352
Ulrich Weigand46084382015-04-21 17:27:59 +00002353 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2354
David Majnemerf6acb762014-04-25 17:07:16 +00002355 setLinkageAndVisibilityForGV(GV, D);
Eli Friedman4f856742009-04-19 21:05:03 +00002356
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002357 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00002358 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00002359 CXXThreadLocals.push_back(D);
Hans Wennborgf60f6af2012-06-28 08:01:44 +00002360 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00002361 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00002362
2363 // If required by the ABI, treat declarations of static data members with
2364 // inline initializers as definitions.
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002365 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Hans Wennborgfeedf852013-11-21 00:15:56 +00002366 EmitGlobalVarDefinition(D);
Hans Wennborg56fc62b2014-07-17 20:25:23 +00002367 }
Robert Lyttonf80d6882014-05-02 09:33:30 +00002368
2369 // Handle XCore specific ABI requirements.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00002370 if (getTriple().getArch() == llvm::Triple::xcore &&
Robert Lyttonf80d6882014-05-02 09:33:30 +00002371 D->getLanguageLinkage() == CLanguageLinkage &&
2372 D->getType().isConstant(Context) &&
2373 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2374 GV->setSection(".cp.rodata");
Chris Lattnerd4808922009-03-22 21:03:39 +00002375 }
Mike Stump11289f42009-09-09 15:08:12 +00002376
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002377 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault00e65b22013-11-15 02:19:52 +00002378 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2379
2380 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002381}
2382
Andrey Bokhankocab58582015-08-31 13:20:44 +00002383llvm::Constant *
2384CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
John McCalld195d4c2016-11-30 23:25:13 +00002385 ForDefinition_t IsForDefinition) {
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002386 const Decl *D = GD.getDecl();
2387 if (isa<CXXConstructorDecl>(D))
2388 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002389 getFromCtorType(GD.getCtorType()),
2390 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2391 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002392 else if (isa<CXXDestructorDecl>(D))
2393 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
Andrey Bokhankocab58582015-08-31 13:20:44 +00002394 getFromDtorType(GD.getDtorType()),
2395 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2396 /*DontDefer=*/false, IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002397 else if (isa<CXXMethodDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002398 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002399 cast<CXXMethodDecl>(D));
Andrey Bokhankocab58582015-08-31 13:20:44 +00002400 auto Ty = getTypes().GetFunctionType(*FInfo);
2401 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2402 IsForDefinition);
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002403 } else if (isa<FunctionDecl>(D)) {
Andrey Bokhankocab58582015-08-31 13:20:44 +00002404 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2405 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2406 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2407 IsForDefinition);
2408 } else
Yaron Keren1c4bbc92016-12-24 15:32:39 +00002409 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002410 IsForDefinition);
Andrey Bokhankocab58582015-08-31 13:20:44 +00002411}
Chris Lattnerd4808922009-03-22 21:03:39 +00002412
Anders Carlssonda80af32011-01-29 18:20:20 +00002413llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002414CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00002415 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00002416 llvm::GlobalValue::LinkageTypes Linkage) {
2417 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Craig Topper8a13c412014-05-21 05:09:00 +00002418 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlssonda80af32011-01-29 18:20:20 +00002419
Anders Carlssonda80af32011-01-29 18:20:20 +00002420 if (GV) {
2421 // Check if the variable has the right type.
2422 if (GV->getType()->getElementType() == Ty)
2423 return GV;
2424
2425 // Because C++ name mangling, the only way we can end up with an already
2426 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00002427 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00002428 OldGV = GV;
2429 }
2430
2431 // Create a new variable.
2432 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Craig Topper8a13c412014-05-21 05:09:00 +00002433 Linkage, nullptr, Name);
2434
Anders Carlssonda80af32011-01-29 18:20:20 +00002435 if (OldGV) {
2436 // Replace occurrences of the old variable if needed.
2437 GV->takeName(OldGV);
2438
2439 if (!OldGV->use_empty()) {
2440 llvm::Constant *NewPtrForOldDecl =
2441 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2442 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2443 }
2444
2445 OldGV->eraseFromParent();
2446 }
Rafael Espindolacb92c192015-01-15 23:18:01 +00002447
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00002448 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2449 !GV->hasAvailableExternallyLinkage())
2450 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Rafael Espindolacb92c192015-01-15 23:18:01 +00002451
Anders Carlssonda80af32011-01-29 18:20:20 +00002452 return GV;
2453}
2454
Chris Lattnerd4808922009-03-22 21:03:39 +00002455/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2456/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00002457/// then it will be created with the specified type instead of whatever the
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002458/// normal requested type would be. If IsForDefinition is true, it is guranteed
2459/// that an actual global with type Ty will be returned, not conversion of a
2460/// variable with the same mangled name but some other type.
Chris Lattnerd4808922009-03-22 21:03:39 +00002461llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002462 llvm::Type *Ty,
John McCalld195d4c2016-11-30 23:25:13 +00002463 ForDefinition_t IsForDefinition) {
Chris Lattnerd4808922009-03-22 21:03:39 +00002464 assert(D->hasGlobalStorage() && "Not a global variable");
2465 QualType ASTTy = D->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00002466 if (!Ty)
Chris Lattnerd4808922009-03-22 21:03:39 +00002467 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00002468
Chris Lattner2192fe52011-07-18 04:24:23 +00002469 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002470 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00002471
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002472 StringRef MangledName = getMangledName(D);
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002473 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
Chris Lattnerd4808922009-03-22 21:03:39 +00002474}
2475
2476/// CreateRuntimeVariable - Create a new runtime global variable with the
2477/// specified type and name.
2478llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00002479CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002480 StringRef Name) {
Rafael Espindolab73c9732014-05-22 23:33:27 +00002481 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
Chris Lattnerd4808922009-03-22 21:03:39 +00002482}
2483
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002484void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2485 assert(!D->getInit() && "Cannot emit definite definitions here!");
2486
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002487 StringRef MangledName = getMangledName(D);
2488 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2489
2490 // We already have a definition, not declaration, with the same mangled name.
2491 // Emitting of declaration is not required (and actually overwrites emitted
2492 // definition).
2493 if (GV && !GV->isDeclaration())
2494 return;
2495
2496 // If we have not seen a reference to this variable yet, place it into the
2497 // deferred declarations table to be emitted if needed later.
2498 if (!MustBeEmitted(D) && !GV) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002499 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002500 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00002501 }
2502
2503 // The tentative definition is the only definition.
Reid Kleckner953fe032015-12-05 01:52:14 +00002504 EmitGlobalVarDefinition(D);
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002505}
2506
Chris Lattner2192fe52011-07-18 04:24:23 +00002507CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00002508 return Context.toCharUnitsFromBits(
2509 getDataLayout().getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00002510}
2511
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002512unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2513 unsigned AddrSpace) {
Artem Belevich2c323a02016-05-19 18:00:18 +00002514 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002515 if (D->hasAttr<CUDAConstantAttr>())
2516 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2517 else if (D->hasAttr<CUDASharedAttr>())
2518 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2519 else
2520 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2521 }
2522
2523 return AddrSpace;
2524}
2525
Richard Smithdf931ce2013-04-06 05:00:46 +00002526template<typename SomeDecl>
2527void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2528 llvm::GlobalValue *GV) {
2529 if (!getLangOpts().CPlusPlus)
2530 return;
2531
2532 // Must have 'used' attribute, or else inline assembly can't rely on
2533 // the name existing.
2534 if (!D->template hasAttr<UsedAttr>())
2535 return;
2536
2537 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00002538 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00002539 return;
2540
2541 // Must be in an extern "C" context. Entities declared directly within
2542 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00002543 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00002544 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00002545 return;
2546
2547 // OK, this is an internal linkage entity inside an extern "C" linkage
2548 // specification. Make a note of that so we can give it the "expected"
2549 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00002550 std::pair<StaticExternCMap::iterator, bool> R =
2551 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00002552
2553 // If we have multiple internal linkage entities with the same name
2554 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00002555 if (!R.second)
Craig Topper8a13c412014-05-21 05:09:00 +00002556 R.first->second = nullptr;
Richard Smithdf931ce2013-04-06 05:00:46 +00002557}
2558
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002559static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2560 if (!CGM.supportsCOMDAT())
2561 return false;
2562
2563 if (D.hasAttr<SelectAnyAttr>())
2564 return true;
2565
2566 GVALinkage Linkage;
2567 if (auto *VD = dyn_cast<VarDecl>(&D))
2568 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2569 else
2570 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2571
2572 switch (Linkage) {
2573 case GVA_Internal:
2574 case GVA_AvailableExternally:
2575 case GVA_StrongExternal:
2576 return false;
2577 case GVA_DiscardableODR:
2578 case GVA_StrongODR:
2579 return true;
2580 }
2581 llvm_unreachable("No such linkage");
2582}
2583
Rafael Espindoladbee8a72015-01-15 21:36:08 +00002584void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2585 llvm::GlobalObject &GO) {
2586 if (!shouldBeInCOMDAT(*this, D))
2587 return;
2588 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2589}
2590
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002591/// Pass IsTentative as true if you want to create a tentative definition.
2592void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2593 bool IsTentative) {
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002594 // OpenCL global variables of sampler type are translated to function calls,
2595 // therefore no need to be translated.
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002596 QualType ASTTy = D->getType();
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002597 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2598 return;
2599
2600 llvm::Constant *Init = nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00002601 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2602 bool NeedsGlobalCtor = false;
2603 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00002604
Richard Smithdafff942012-01-14 04:30:29 +00002605 const VarDecl *InitDecl;
2606 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00002607
Artem Belevich97c01c32016-02-02 22:29:48 +00002608 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2609 // as part of their declaration." Sema has already checked for
2610 // error cases, so we just need to set Init to UndefValue.
2611 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2612 D->hasAttr<CUDASharedAttr>())
Jingyue Wu284ebe22015-08-22 05:49:28 +00002613 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
Artem Belevich97c01c32016-02-02 22:29:48 +00002614 else if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00002615 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00002616 // implicitly initialized with { 0 }.
2617 //
2618 // Note that tentative definitions are only emitted at the end of
2619 // a translation unit, so they should never have incomplete
2620 // type. In addition, EmitTentativeDefinition makes sure that we
2621 // never attempt to emit a tentative definition if a real one
2622 // exists. A use may still exists, however, so we still may need
2623 // to do a RAUW.
2624 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00002625 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002626 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00002627 initializedGlobalDecl = GlobalDecl(D);
2628 Init = EmitConstantInit(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00002629
Fariborz Jahanian63628032012-06-26 16:06:38 +00002630 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00002631 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00002632 if (D->getType()->isReferenceType())
2633 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00002634
David Blaikiebbafb8a2012-03-11 07:00:24 +00002635 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00002636 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00002637 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00002638 } else {
2639 ErrorUnsupported(D, "static initializer");
2640 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2641 }
John McCall70013b62010-07-15 23:40:35 +00002642 } else {
2643 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00002644 // initializer position (just in case this entry was delayed) if we
2645 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002646 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00002647 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00002648 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002649 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002650
Chris Lattner2192fe52011-07-18 04:24:23 +00002651 llvm::Type* InitType = Init->getType();
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002652 llvm::Constant *Entry =
John McCalld195d4c2016-11-30 23:25:13 +00002653 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
Mike Stump11289f42009-09-09 15:08:12 +00002654
Chris Lattner149927c2009-03-21 09:16:30 +00002655 // Strip off a bitcast if we got one back.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002656 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00002657 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00002658 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2659 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00002660 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00002661 Entry = CE->getOperand(0);
2662 }
Mike Stump11289f42009-09-09 15:08:12 +00002663
Chris Lattner149927c2009-03-21 09:16:30 +00002664 // Entry is now either a Function or GlobalVariable.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002665 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002666
Chris Lattner149927c2009-03-21 09:16:30 +00002667 // We have a definition after a declaration with the wrong type.
2668 // We must make a new GlobalVariable* and update everything that used OldGV
2669 // (a declaration or tentative definition) with the new GlobalVariable*
2670 // (which will be a definition).
2671 //
2672 // This happens if there is a prototype for a global (e.g.
2673 // "extern int x[];") and then a definition of a different type (e.g.
2674 // "int x[10];"). This also happens when an initializer has a different type
2675 // from the type of the global (this happens with unions).
Craig Topper8a13c412014-05-21 05:09:00 +00002676 if (!GV ||
Chris Lattner149927c2009-03-21 09:16:30 +00002677 GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00002678 GV->getType()->getAddressSpace() !=
Peter Collingbournef44bdf92012-05-20 21:08:35 +00002679 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump11289f42009-09-09 15:08:12 +00002680
John McCall7ec50432010-03-19 23:29:14 +00002681 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002682 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00002683
Chris Lattner149927c2009-03-21 09:16:30 +00002684 // Make a new global with the correct type, this is now guaranteed to work.
Andrey Bokhanko7aa88ce2016-01-14 10:41:16 +00002685 GV = cast<llvm::GlobalVariable>(
John McCalld195d4c2016-11-30 23:25:13 +00002686 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
Chris Lattnera85d68e2009-03-21 09:25:43 +00002687
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002688 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00002689 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00002690 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00002691 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00002692
2693 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00002694 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00002695 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00002696
Richard Smithdf931ce2013-04-06 05:00:46 +00002697 MaybeHandleStaticInExternC(D, GV);
2698
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002699 if (D->hasAttr<AnnotateAttr>())
2700 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00002701
Artem Belevich42e19492016-03-02 18:28:50 +00002702 // Set the llvm linkage type as appropriate.
2703 llvm::GlobalValue::LinkageTypes Linkage =
2704 getLLVMLinkageVarDefinition(D, GV->isConstant());
2705
Jingyue Wu284ebe22015-08-22 05:49:28 +00002706 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2707 // the device. [...]"
2708 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2709 // __device__, declares a variable that: [...]
2710 // Is accessible from all the threads within the grid and from the host
2711 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2712 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
Artem Belevich42e19492016-03-02 18:28:50 +00002713 if (GV && LangOpts.CUDA) {
2714 if (LangOpts.CUDAIsDevice) {
2715 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2716 GV->setExternallyInitialized(true);
2717 } else {
2718 // Host-side shadows of external declarations of device-side
2719 // global variables become internal definitions. These have to
2720 // be internal in order to prevent name conflicts with global
2721 // host variables with the same name in a different TUs.
2722 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2723 Linkage = llvm::GlobalValue::InternalLinkage;
2724
2725 // Shadow variables and their properties must be registered
2726 // with CUDA runtime.
2727 unsigned Flags = 0;
2728 if (!D->hasDefinition())
2729 Flags |= CGCUDARuntime::ExternDeviceVar;
2730 if (D->hasAttr<CUDAConstantAttr>())
2731 Flags |= CGCUDARuntime::ConstantDeviceVar;
2732 getCUDARuntime().registerDeviceVar(*GV, Flags);
2733 } else if (D->hasAttr<CUDASharedAttr>())
2734 // __shared__ variables are odd. Shadows do get created, but
2735 // they are not registered with the CUDA runtime, so they
2736 // can't really be used to access their device-side
2737 // counterparts. It's not clear yet whether it's nvcc's bug or
2738 // a feature, but we've got to do the same for compatibility.
2739 Linkage = llvm::GlobalValue::InternalLinkage;
2740 }
Jingyue Wu284ebe22015-08-22 05:49:28 +00002741 }
Chris Lattnerd14bfa92007-07-13 05:13:43 +00002742 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00002743
2744 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00002745 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2746 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00002747
Hans Wennborg899ded92014-10-16 20:52:46 +00002748 // If it is in a read-only section, mark it 'constant'.
2749 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2750 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2751 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2752 GV->setConstant(true);
2753 }
2754
Ken Dyck160146e2010-01-27 17:10:57 +00002755 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00002756
David Majnemer35ab3282014-06-11 04:08:55 +00002757
Manman Ren68150262015-11-11 22:42:31 +00002758 // On Darwin, if the normal linkage of a C++ thread_local variable is
2759 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2760 // copies within a linkage unit; otherwise, the backing variable has
2761 // internal linkage and all accesses should just be calls to the
David Majnemer35ab3282014-06-11 04:08:55 +00002762 // Itanium-specified entry point, which has the normal linkage of the
Manman Ren68150262015-11-11 22:42:31 +00002763 // variable. This is to preserve the ability to change the implementation
2764 // behind the scenes.
David Majnemerbb525f7c2014-10-15 22:38:23 +00002765 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
Manman Renf93fff22015-11-11 23:08:18 +00002766 Context.getTargetInfo().getTriple().isOSDarwin() &&
Manman Ren68150262015-11-11 22:42:31 +00002767 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2768 !llvm::GlobalVariable::isWeakLinkage(Linkage))
David Majnemerbb525f7c2014-10-15 22:38:23 +00002769 Linkage = llvm::GlobalValue::InternalLinkage;
David Majnemer35ab3282014-06-11 04:08:55 +00002770
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002771 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00002772 if (D->hasAttr<DLLImportAttr>())
2773 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2774 else if (D->hasAttr<DLLExportAttr>())
2775 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborg606bd6d2014-11-03 14:24:45 +00002776 else
2777 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00002778
Yaxun Liu402804b2016-12-15 08:09:08 +00002779 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
Chris Lattnerf49573d2009-08-05 05:20:29 +00002780 // common vars aren't constant even if declared const.
2781 GV->setConstant(false);
Yaxun Liu402804b2016-12-15 08:09:08 +00002782 // Tentative definition of global variables may be initialized with
2783 // non-zero null pointers. In this case they should have weak linkage
2784 // since common linkage must have zero initializer and must not have
2785 // explicit section therefore cannot have non-zero initial value.
2786 if (!GV->getInitializer()->isNullValue())
2787 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2788 }
Daniel Dunbard272cca2009-04-10 20:26:50 +00002789
Rafael Espindola502f65a2014-05-05 20:21:03 +00002790 setNonAliasAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00002791
David Majnemerbb525f7c2014-10-15 22:38:23 +00002792 if (D->getTLSKind() && !GV->isThreadLocal()) {
2793 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
Richard Smith5a99c492015-12-01 01:10:48 +00002794 CXXThreadLocals.push_back(D);
David Majnemerbb525f7c2014-10-15 22:38:23 +00002795 setTLSMode(GV, *D);
2796 }
2797
Rafael Espindoladbee8a72015-01-15 21:36:08 +00002798 maybeSetTrivialComdat(*D, *GV);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00002799
John McCallcdf7ef52010-11-06 09:44:32 +00002800 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00002801 if (NeedsGlobalCtor || NeedsGlobalDtor)
2802 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00002803
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002804 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany28a26c82012-08-21 06:53:28 +00002805
Sanjiv Gupta158143a2008-06-05 08:59:10 +00002806 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00002807 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00002808 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00002809 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00002810}
Chris Lattner09153c02007-06-22 18:48:09 +00002811
David Majnemerc017d362014-08-05 00:01:13 +00002812static bool isVarDeclStrongDefinition(const ASTContext &Context,
Nico Weber608e7682015-04-15 23:04:24 +00002813 CodeGenModule &CGM, const VarDecl *D,
2814 bool NoCommon) {
David Majnemer9832a3d2014-04-10 16:53:16 +00002815 // Don't give variables common linkage if -fno-common was specified unless it
2816 // was overridden by a NoCommon attribute.
2817 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2818 return true;
2819
2820 // C11 6.9.2/2:
2821 // A declaration of an identifier for an object that has file scope without
2822 // an initializer, and without a storage-class specifier or with the
2823 // storage-class specifier static, constitutes a tentative definition.
2824 if (D->getInit() || D->hasExternalStorage())
2825 return true;
2826
2827 // A variable cannot be both common and exist in a section.
2828 if (D->hasAttr<SectionAttr>())
2829 return true;
2830
2831 // Thread local vars aren't considered common linkage.
2832 if (D->getTLSKind())
2833 return true;
2834
2835 // Tentative definitions marked with WeakImportAttr are true definitions.
2836 if (D->hasAttr<WeakImportAttr>())
2837 return true;
2838
Nico Weber608e7682015-04-15 23:04:24 +00002839 // A variable cannot be both common and exist in a comdat.
2840 if (shouldBeInCOMDAT(CGM, *D))
2841 return true;
2842
Sanjay Patel2f9303a2016-06-30 21:02:40 +00002843 // Declarations with a required alignment do not have common linkage in MSVC
David Majnemerc017d362014-08-05 00:01:13 +00002844 // mode.
David Majnemer3f021502015-10-08 04:53:31 +00002845 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemere1a0b2e2015-02-03 08:49:32 +00002846 if (D->hasAttr<AlignedAttr>())
2847 return true;
2848 QualType VarType = D->getType();
2849 if (Context.isAlignmentRequired(VarType))
2850 return true;
2851
2852 if (const auto *RT = VarType->getAs<RecordType>()) {
2853 const RecordDecl *RD = RT->getDecl();
2854 for (const FieldDecl *FD : RD->fields()) {
2855 if (FD->isBitField())
2856 continue;
2857 if (FD->hasAttr<AlignedAttr>())
2858 return true;
2859 if (Context.isAlignmentRequired(FD->getType()))
2860 return true;
2861 }
2862 }
2863 }
David Majnemerc017d362014-08-05 00:01:13 +00002864
David Majnemer9832a3d2014-04-10 16:53:16 +00002865 return false;
2866}
2867
Hans Wennborg1a3a0742014-05-14 19:54:53 +00002868llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
Hans Wennborg275efb92014-05-28 01:52:23 +00002869 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002870 if (Linkage == GVA_Internal)
2871 return llvm::Function::InternalLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00002872
2873 if (D->hasAttr<WeakAttr>()) {
2874 if (IsConstantVariable)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002875 return llvm::GlobalVariable::WeakODRLinkage;
2876 else
2877 return llvm::GlobalVariable::WeakAnyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00002878 }
2879
2880 // We are guaranteed to have a strong definition somewhere else,
2881 // so we can use available_externally linkage.
2882 if (Linkage == GVA_AvailableExternally)
David Blaikie9ffe5a32017-01-30 05:00:26 +00002883 return llvm::GlobalValue::AvailableExternallyLinkage;
David Majnemer27d69db2014-04-28 22:17:59 +00002884
David Majnemer27d69db2014-04-28 22:17:59 +00002885 // Note that Apple's kernel linker doesn't support symbol
2886 // coalescing, so we need to avoid linkonce and weak linkages there.
2887 // Normally, this means we just map to internal, but for explicit
2888 // instantiations we'll map to external.
2889
2890 // In C++, the compiler has to emit a definition in every translation unit
2891 // that references the function. We should use linkonce_odr because
2892 // a) if all references in this translation unit are optimized away, we
2893 // don't need to codegen it. b) if the function persists, it needs to be
2894 // merged with other definitions. c) C++ has the ODR, so we know the
2895 // definition is dependable.
2896 if (Linkage == GVA_DiscardableODR)
Hans Wennborgb0f2f142014-05-15 22:07:49 +00002897 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
David Majnemer27d69db2014-04-28 22:17:59 +00002898 : llvm::Function::InternalLinkage;
2899
2900 // An explicit instantiation of a template has weak linkage, since
2901 // explicit instantiations can occur in multiple translation units
2902 // and must all be equivalent. However, we are not allowed to
2903 // throw away these explicit instantiations.
Justin Lebar27ee1302016-06-30 18:41:33 +00002904 //
2905 // We don't currently support CUDA device code spread out across multiple TUs,
2906 // so say that CUDA templates are either external (for kernels) or internal.
2907 // This lets llvm perform aggressive inter-procedural optimizations.
2908 if (Linkage == GVA_StrongODR) {
2909 if (Context.getLangOpts().AppleKext)
2910 return llvm::Function::ExternalLinkage;
2911 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2912 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2913 : llvm::Function::InternalLinkage;
2914 return llvm::Function::WeakODRLinkage;
2915 }
David Majnemer27d69db2014-04-28 22:17:59 +00002916
David Majnemer27d69db2014-04-28 22:17:59 +00002917 // C++ doesn't have tentative definitions and thus cannot have common
2918 // linkage.
2919 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Nico Weber608e7682015-04-15 23:04:24 +00002920 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
David Majnemerc017d362014-08-05 00:01:13 +00002921 CodeGenOpts.NoCommon))
David Majnemer9832a3d2014-04-10 16:53:16 +00002922 return llvm::GlobalVariable::CommonLinkage;
2923
David Majnemer27d69db2014-04-28 22:17:59 +00002924 // selectany symbols are externally visible, so use weak instead of
2925 // linkonce. MSVC optimizes away references to const selectany globals, so
2926 // all definitions should be the same and ODR linkage should be used.
2927 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2928 if (D->hasAttr<SelectAnyAttr>())
2929 return llvm::GlobalVariable::WeakODRLinkage;
2930
2931 // Otherwise, we have strong external linkage.
2932 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00002933 return llvm::GlobalVariable::ExternalLinkage;
2934}
2935
David Majnemer27d69db2014-04-28 22:17:59 +00002936llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2937 const VarDecl *VD, bool IsConstant) {
2938 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
Hans Wennborg275efb92014-05-28 01:52:23 +00002939 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
David Majnemer27d69db2014-04-28 22:17:59 +00002940}
2941
John McCall49954ca2012-12-12 22:21:47 +00002942/// Replace the uses of a function that was declared with a non-proto type.
2943/// We want to silently drop extra arguments from call sites
2944static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2945 llvm::Function *newFn) {
2946 // Fast path.
2947 if (old->use_empty()) return;
2948
2949 llvm::Type *newRetTy = newFn->getReturnType();
2950 SmallVector<llvm::Value*, 4> newArgs;
David Majnemer0b17d442015-12-15 21:27:59 +00002951 SmallVector<llvm::OperandBundleDef, 1> newBundles;
John McCall49954ca2012-12-12 22:21:47 +00002952
2953 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2954 ui != ue; ) {
2955 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002956 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00002957
2958 // Recognize and replace uses of bitcasts. Most calls to
2959 // unprototyped functions will use bitcasts.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002960 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCall49954ca2012-12-12 22:21:47 +00002961 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2962 replaceUsesOfNonProtoConstant(bitcast, newFn);
2963 continue;
2964 }
2965
2966 // Recognize calls to the function.
2967 llvm::CallSite callSite(user);
2968 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00002969 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00002970
2971 // If the return types don't match exactly, then we can't
2972 // transform this call unless it's dead.
2973 if (callSite->getType() != newRetTy && !callSite->use_empty())
2974 continue;
2975
2976 // Get the call site's attribute list.
Reid Kleckner7f720332017-04-13 00:58:09 +00002977 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
Reid Klecknerde864822017-03-21 16:57:30 +00002978 llvm::AttributeList oldAttrs = callSite.getAttributes();
John McCall49954ca2012-12-12 22:21:47 +00002979
John McCall49954ca2012-12-12 22:21:47 +00002980 // If the function was passed too few arguments, don't transform.
2981 unsigned newNumArgs = newFn->arg_size();
2982 if (callSite.arg_size() < newNumArgs) continue;
2983
2984 // If extra arguments were passed, we silently drop them.
2985 // If any of the types mismatch, we don't transform.
2986 unsigned argNo = 0;
2987 bool dontTransform = false;
Reid Kleckner7f720332017-04-13 00:58:09 +00002988 for (llvm::Argument &A : newFn->args()) {
2989 if (callSite.getArgument(argNo)->getType() != A.getType()) {
John McCall49954ca2012-12-12 22:21:47 +00002990 dontTransform = true;
2991 break;
2992 }
2993
2994 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00002995 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
Reid Kleckner7f720332017-04-13 00:58:09 +00002996 argNo++;
John McCall49954ca2012-12-12 22:21:47 +00002997 }
2998 if (dontTransform)
2999 continue;
3000
John McCall49954ca2012-12-12 22:21:47 +00003001 // Okay, we can transform this. Create the new call instruction and copy
3002 // over the required information.
3003 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3004
David Majnemer0b17d442015-12-15 21:27:59 +00003005 // Copy over any operand bundles.
3006 callSite.getOperandBundlesAsDefs(newBundles);
3007
John McCall49954ca2012-12-12 22:21:47 +00003008 llvm::CallSite newCall;
3009 if (callSite.isCall()) {
David Majnemer0b17d442015-12-15 21:27:59 +00003010 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003011 callSite.getInstruction());
3012 } else {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003013 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCall49954ca2012-12-12 22:21:47 +00003014 newCall = llvm::InvokeInst::Create(newFn,
3015 oldInvoke->getNormalDest(),
3016 oldInvoke->getUnwindDest(),
David Majnemer0b17d442015-12-15 21:27:59 +00003017 newArgs, newBundles, "",
John McCall49954ca2012-12-12 22:21:47 +00003018 callSite.getInstruction());
3019 }
3020 newArgs.clear(); // for the next iteration
3021
3022 if (!newCall->getType()->isVoidTy())
3023 newCall->takeName(callSite.getInstruction());
Reid Kleckner7f720332017-04-13 00:58:09 +00003024 newCall.setAttributes(llvm::AttributeList::get(
3025 newFn->getContext(), oldAttrs.getFnAttributes(),
3026 oldAttrs.getRetAttributes(), newArgAttrs));
John McCall49954ca2012-12-12 22:21:47 +00003027 newCall.setCallingConv(callSite.getCallingConv());
3028
3029 // Finally, remove the old call, replacing any uses with the new one.
3030 if (!callSite->use_empty())
3031 callSite->replaceAllUsesWith(newCall.getInstruction());
3032
3033 // Copy debug location attached to CI.
Duncan P. N. Exon Smith2809cc72015-03-30 20:01:41 +00003034 if (callSite->getDebugLoc())
John McCall49954ca2012-12-12 22:21:47 +00003035 newCall->setDebugLoc(callSite->getDebugLoc());
David Majnemer0b17d442015-12-15 21:27:59 +00003036
John McCall49954ca2012-12-12 22:21:47 +00003037 callSite->eraseFromParent();
3038 }
3039}
3040
Chris Lattner36797ab2009-05-05 06:16:31 +00003041/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3042/// implement a function with no prototype, e.g. "int foo() {}". If there are
3043/// existing call uses of the old function in the module, this adjusts them to
3044/// call the new function directly.
3045///
3046/// This is not just a cleanup: the always_inline pass requires direct calls to
3047/// functions to be able to inline them. If there is a bitcast in the way, it
3048/// won't inline them. Instcombine normally deletes these calls, but it isn't
3049/// run at -O0.
3050static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3051 llvm::Function *NewFn) {
3052 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00003053 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00003054
John McCall49954ca2012-12-12 22:21:47 +00003055 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00003056}
3057
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003058void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
David Majnemer60e5bdc2016-07-11 04:28:21 +00003059 auto DK = VD->isThisDeclarationADefinition();
3060 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3061 return;
3062
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003063 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3064 // If we have a definition, this might be a deferred decl. If the
3065 // instantiation is explicit, make sure we emit it at the end.
3066 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3067 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003068
3069 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00003070}
Daniel Dunbar9c426522008-07-29 23:18:29 +00003071
Rafael Espindolacd7743b2013-12-09 16:01:03 +00003072void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3073 llvm::GlobalValue *GV) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003074 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00003075
John McCall46288ef2011-03-09 08:12:35 +00003076 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00003077 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3078 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00003079
Chris Lattnereb7466d2009-05-12 20:58:15 +00003080 // Get or create the prototype for the function.
Andrey Bokhankocab58582015-08-31 13:20:44 +00003081 if (!GV || (GV->getType()->getElementType() != Ty))
3082 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3083 /*DontDefer=*/true,
John McCalld195d4c2016-11-30 23:25:13 +00003084 ForDefinition));
Mike Stump11289f42009-09-09 15:08:12 +00003085
Andrey Bokhankocab58582015-08-31 13:20:44 +00003086 // Already emitted.
3087 if (!GV->isDeclaration())
Renato Golinc640ff62015-04-15 08:44:40 +00003088 return;
Mike Stump11289f42009-09-09 15:08:12 +00003089
John McCall8e7cb6d2010-11-02 21:04:24 +00003090 // We need to set linkage and visibility on the function before
3091 // generating code for it because various parts of IR generation
3092 // want to propagate this information down (e.g. to local static
3093 // declarations).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003094 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00003095 setFunctionLinkage(GD, Fn);
Hans Wennborgbb4f9622015-05-28 17:44:56 +00003096 setFunctionDLLStorageClass(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003097
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003098 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00003099 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00003100
Richard Smithdf931ce2013-04-06 05:00:46 +00003101 MaybeHandleStaticInExternC(D, Fn);
3102
Rafael Espindoladbee8a72015-01-15 21:36:08 +00003103 maybeSetTrivialComdat(*D, *Fn);
Rafael Espindola0d4fb982015-01-12 22:13:53 +00003104
John McCalla738c252011-03-09 04:27:21 +00003105 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00003106
Rafael Espindolae033c8c2014-05-08 15:26:12 +00003107 setFunctionDefinitionAttributes(D, Fn);
Daniel Dunbar38932572009-04-14 08:05:55 +00003108 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00003109
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003110 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003111 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003112 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00003113 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003114 if (D->hasAttr<AnnotateAttr>())
3115 AddGlobalAnnotations(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00003116}
3117
John McCall7ec50432010-03-19 23:29:14 +00003118void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003119 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003120 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00003121 assert(AA && "Not an alias?");
3122
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003123 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00003124
Hal Finkel0e2b9752015-09-04 21:49:21 +00003125 if (AA->getAliasee() == MangledName) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003126 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Hal Finkel0e2b9752015-09-04 21:49:21 +00003127 return;
3128 }
3129
John McCall7ec50432010-03-19 23:29:14 +00003130 // If there is a definition in the module, then it wins over the alias.
3131 // This is dubious, but allow it to be safe. Just ignore the alias.
3132 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3133 if (Entry && !Entry->isDeclaration())
3134 return;
3135
Rafael Espindola208b5c02013-10-22 19:26:13 +00003136 Aliases.push_back(GD);
3137
Chris Lattner2192fe52011-07-18 04:24:23 +00003138 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00003139
3140 // Create a reference to the named value. This ensures that it is emitted
3141 // if a deferred decl.
3142 llvm::Constant *Aliasee;
3143 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00003144 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00003145 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00003146 else
John McCall7ec50432010-03-19 23:29:14 +00003147 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Craig Topper8a13c412014-05-21 05:09:00 +00003148 llvm::PointerType::getUnqual(DeclTy),
David Majnemerbb525f7c2014-10-15 22:38:23 +00003149 /*D=*/nullptr);
Chris Lattner54041692009-03-22 21:47:11 +00003150
3151 // Create the new alias itself, but don't set a name yet.
Rafael Espindola234405b2014-05-17 21:30:14 +00003152 auto *GA = llvm::GlobalAlias::create(
David Blaikie2a791d72015-09-14 18:38:22 +00003153 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00003154
Chris Lattner54041692009-03-22 21:47:11 +00003155 if (Entry) {
Rafael Espindolab2633b92014-05-16 19:35:48 +00003156 if (GA->getAliasee() == Entry) {
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003157 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
Rafael Espindolab2633b92014-05-16 19:35:48 +00003158 return;
3159 }
3160
John McCall7ec50432010-03-19 23:29:14 +00003161 assert(Entry->isDeclaration());
3162
Chris Lattner54041692009-03-22 21:47:11 +00003163 // If there is a declaration in the module, then we had an extern followed
3164 // by the alias, as in:
3165 // extern int test6();
3166 // ...
3167 // int test6() __attribute__((alias("test7")));
3168 //
3169 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00003170 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00003171
Owen Andersonade90fd2009-07-29 18:54:39 +00003172 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00003173 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00003174 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00003175 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00003176 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00003177 }
Mike Stump11289f42009-09-09 15:08:12 +00003178
Daniel Dunbar38932572009-04-14 08:05:55 +00003179 // Set attributes which are particular to an alias; this is a
3180 // specialization of the attributes which may be set on a global
3181 // variable/function.
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00003182 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3183 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00003184 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3185 }
3186
David Majnemerbb525f7c2014-10-15 22:38:23 +00003187 if (const auto *VD = dyn_cast<VarDecl>(D))
3188 if (VD->getTLSKind())
3189 setTLSMode(GA, *VD);
3190
Rafael Espindolafcfbcc62014-10-08 00:00:09 +00003191 setAliasAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00003192}
3193
Dmitry Polukhin85eda122016-04-11 07:48:59 +00003194void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3195 const auto *D = cast<ValueDecl>(GD.getDecl());
3196 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3197 assert(IFA && "Not an ifunc?");
3198
3199 StringRef MangledName = getMangledName(GD);
3200
3201 if (IFA->getResolver() == MangledName) {
3202 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3203 return;
3204 }
3205
3206 // Report an error if some definition overrides ifunc.
3207 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3208 if (Entry && !Entry->isDeclaration()) {
3209 GlobalDecl OtherGD;
3210 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3211 DiagnosedConflictingDefinitions.insert(GD).second) {
3212 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3213 Diags.Report(OtherGD.getDecl()->getLocation(),
3214 diag::note_previous_definition);
3215 }
3216 return;
3217 }
3218
3219 Aliases.push_back(GD);
3220
3221 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3222 llvm::Constant *Resolver =
3223 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3224 /*ForVTable=*/false);
3225 llvm::GlobalIFunc *GIF =
3226 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3227 "", Resolver, &getModule());
3228 if (Entry) {
3229 if (GIF->getResolver() == Entry) {
3230 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3231 return;
3232 }
3233 assert(Entry->isDeclaration());
3234
3235 // If there is a declaration in the module, then we had an extern followed
3236 // by the ifunc, as in:
3237 // extern int test();
3238 // ...
3239 // int test() __attribute__((ifunc("resolver")));
3240 //
3241 // Remove it and replace uses of it with the ifunc.
3242 GIF->takeName(Entry);
3243
3244 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3245 Entry->getType()));
3246 Entry->eraseFromParent();
3247 } else
3248 GIF->setName(MangledName);
3249
3250 SetCommonAttributes(D, GIF);
3251}
3252
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003253llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00003254 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00003255 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003256 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00003257}
Chris Lattner1eec6602007-08-31 04:31:45 +00003258
David Blaikie2e804282015-04-05 22:47:07 +00003259static llvm::StringMapEntry<llvm::GlobalVariable *> &
3260GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3261 const StringLiteral *Literal, bool TargetIsLSB,
3262 bool &IsUTF16, unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003263 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003264 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00003265
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003266 // Check for simple case.
3267 if (!Literal->containsNonAsciiOrNull()) {
3268 StringLength = NumBytes;
David Blaikie13156b62014-11-19 03:06:06 +00003269 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00003270 }
3271
Bill Wendling82b87f12012-03-30 00:26:17 +00003272 // Otherwise, convert the UTF8 literals into a string of shorts.
3273 IsUTF16 = true;
3274
Justin Lebar90910552016-09-30 00:38:45 +00003275 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3276 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3277 llvm::UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00003278
Justin Lebar90910552016-09-30 00:38:45 +00003279 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3280 ToPtr + NumBytes, llvm::strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00003281
Daniel Dunbar91ade142009-07-23 23:41:22 +00003282 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00003283 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00003284
Bill Wendling82b87f12012-03-30 00:26:17 +00003285 // Add an explicit null.
3286 *ToPtr = 0;
David Blaikie13156b62014-11-19 03:06:06 +00003287 return *Map.insert(std::make_pair(
3288 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3289 (StringLength + 1) * 2),
3290 nullptr)).first;
Daniel Dunbar64509b22009-07-23 22:52:48 +00003291}
3292
John McCall7f416cc2015-09-08 08:05:57 +00003293ConstantAddress
Daniel Dunbar64509b22009-07-23 22:52:48 +00003294CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3295 unsigned StringLength = 0;
3296 bool isUTF16 = false;
David Blaikie2e804282015-04-05 22:47:07 +00003297 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3298 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3299 getDataLayout().isLittleEndian(), isUTF16,
3300 StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003301
David Blaikie13156b62014-11-19 03:06:06 +00003302 if (auto *C = Entry.second)
John McCall7f416cc2015-09-08 08:05:57 +00003303 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
Mike Stump11289f42009-09-09 15:08:12 +00003304
Chris Lattnerece04092012-02-07 00:39:47 +00003305 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00003306 llvm::Constant *Zeros[] = { Zero, Zero };
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003307
Chris Lattneraa64ca22009-07-16 16:48:25 +00003308 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00003309 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00003310 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00003311 Ty = llvm::ArrayType::get(Ty, 0);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003312 llvm::Constant *GV =
3313 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003314
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003315 if (getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasool49766342016-06-01 04:22:24 +00003316 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3317 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3318 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3319 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3320
3321 const VarDecl *VD = nullptr;
3322 for (const auto &Result : DC->lookup(&II))
3323 if ((VD = dyn_cast<VarDecl>(Result)))
3324 break;
3325
3326 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3327 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3328 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3329 } else {
3330 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3331 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3332 }
3333 }
3334
Daniel Dunbard644ad62008-08-23 18:37:06 +00003335 // Decay array -> ptr
Saleem Abdulrasool4fab7452016-09-11 01:25:15 +00003336 CFConstantStringClassRef =
3337 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003338 }
Mike Stump11289f42009-09-09 15:08:12 +00003339
Anders Carlssonc2480a52008-11-15 18:54:24 +00003340 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00003341
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003342 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssonc2480a52008-11-15 18:54:24 +00003343
John McCall23c9dc62016-11-28 22:18:27 +00003344 ConstantInitBuilder Builder(*this);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003345 auto Fields = Builder.beginStruct(STy);
Douglas Gregor91f84212008-12-11 16:49:14 +00003346
Anders Carlssonb04ea612007-08-21 00:21:21 +00003347 // Class pointer.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003348 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
Mike Stump11289f42009-09-09 15:08:12 +00003349
Anders Carlssonb04ea612007-08-21 00:21:21 +00003350 // Flags.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003351 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
Anders Carlsson157c3212009-08-16 05:55:31 +00003352
Anders Carlssonb04ea612007-08-21 00:21:21 +00003353 // String pointer.
Craig Topper8a13c412014-05-21 05:09:00 +00003354 llvm::Constant *C = nullptr;
Bill Wendling82b87f12012-03-30 00:26:17 +00003355 if (isUTF16) {
Craig Topperc005cc02015-09-27 03:44:08 +00003356 auto Arr = llvm::makeArrayRef(
David Blaikie13156b62014-11-19 03:06:06 +00003357 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3358 Entry.first().size() / 2);
Bill Wendling82b87f12012-03-30 00:26:17 +00003359 C = llvm::ConstantDataArray::get(VMContext, Arr);
3360 } else {
David Blaikie13156b62014-11-19 03:06:06 +00003361 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling82b87f12012-03-30 00:26:17 +00003362 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00003363
Bill Wendling86131f22012-01-10 08:46:39 +00003364 // Note: -fwritable-strings doesn't make the backing store strings of
3365 // CFStrings writable. (See <rdar://problem/10657500>)
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003366 auto *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00003367 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3368 llvm::GlobalValue::PrivateLinkage, C, ".str");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003369 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Ulrich Weigandfa806422013-05-06 16:23:57 +00003370 // Don't enforce the target's minimum global alignment, since the only use
3371 // of the string is via this class initializer.
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003372 CharUnits Align = isUTF16
3373 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3374 : getContext().getTypeAlignInChars(getContext().CharTy);
3375 GV->setAlignment(Align.getQuantity());
3376
3377 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3378 // Without it LLVM can merge the string with a non unnamed_addr one during
3379 // LTO. Doing that changes the section it ends in, which surprises ld64.
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003380 if (getTriple().isOSBinFormatMachO())
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003381 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3382 : "__TEXT,__cstring,cstring_literals");
Bill Wendling82b87f12012-03-30 00:26:17 +00003383
3384 // String.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003385 llvm::Constant *Str =
David Blaikied3c127e2015-05-07 17:27:56 +00003386 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00003387
Bill Wendling82b87f12012-03-30 00:26:17 +00003388 if (isUTF16)
3389 // Cast the UTF16 string to the correct type.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003390 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3391 Fields.add(Str);
Bill Wendling82b87f12012-03-30 00:26:17 +00003392
Anders Carlssonb04ea612007-08-21 00:21:21 +00003393 // String length.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003394 auto Ty = getTypes().ConvertType(getContext().LongTy);
3395 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00003396
John McCall7f416cc2015-09-08 08:05:57 +00003397 CharUnits Alignment = getPointerAlign();
3398
Anders Carlssonb04ea612007-08-21 00:21:21 +00003399 // The struct.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003400 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3401 /*isConstant=*/false,
3402 llvm::GlobalVariable::PrivateLinkage);
Saleem Abdulrasool7246dcc2016-09-14 15:17:46 +00003403 switch (getTriple().getObjectFormat()) {
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003404 case llvm::Triple::UnknownObjectFormat:
3405 llvm_unreachable("unknown file format");
3406 case llvm::Triple::COFF:
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003407 case llvm::Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00003408 case llvm::Triple::Wasm:
Saleem Abdulrasool0295f8c2016-07-09 01:59:51 +00003409 GV->setSection("cfstring");
Saleem Abdulrasoolf7444e62016-05-30 16:23:07 +00003410 break;
3411 case llvm::Triple::MachO:
3412 GV->setSection("__DATA,__cfstring");
3413 break;
3414 }
David Blaikie13156b62014-11-19 03:06:06 +00003415 Entry.second = GV;
Mike Stump11289f42009-09-09 15:08:12 +00003416
John McCall7f416cc2015-09-08 08:05:57 +00003417 return ConstantAddress(GV, Alignment);
Anders Carlssonb04ea612007-08-21 00:21:21 +00003418}
Chris Lattnerfb300092007-11-28 05:34:05 +00003419
Douglas Gregor636e2002011-08-09 17:23:49 +00003420QualType CodeGenModule::getObjCFastEnumerationStateType() {
3421 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00003422 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00003423 D->startDefinition();
3424
3425 QualType FieldTypes[] = {
3426 Context.UnsignedLongTy,
3427 Context.getPointerType(Context.getObjCIdType()),
3428 Context.getPointerType(Context.UnsignedLongTy),
3429 Context.getConstantArrayType(Context.UnsignedLongTy,
3430 llvm::APInt(32, 5), ArrayType::Normal, 0)
3431 };
3432
3433 for (size_t i = 0; i < 4; ++i) {
3434 FieldDecl *Field = FieldDecl::Create(Context,
3435 D,
3436 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003437 SourceLocation(), nullptr,
3438 FieldTypes[i], /*TInfo=*/nullptr,
3439 /*BitWidth=*/nullptr,
Douglas Gregor636e2002011-08-09 17:23:49 +00003440 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003441 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00003442 Field->setAccess(AS_public);
3443 D->addDecl(Field);
3444 }
3445
3446 D->completeDefinition();
3447 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3448 }
3449
3450 return ObjCFastEnumerationStateType;
3451}
3452
Eli Friedmanfcec6302011-11-01 02:23:42 +00003453llvm::Constant *
3454CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3455 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3456
3457 // Don't emit it as the address of the string, emit the string data itself
3458 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00003459 if (E->getCharByteWidth() == 1) {
3460 SmallString<64> Str(E->getString());
3461
3462 // Resize the string to the right size, which is indicated by its type.
3463 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3464 Str.resize(CAT->getSize().getZExtValue());
3465 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3466 }
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003467
3468 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner9c818332012-02-05 02:30:40 +00003469 llvm::Type *ElemTy = AType->getElementType();
3470 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00003471
3472 // Wide strings have either 2-byte or 4-byte elements.
3473 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3474 SmallVector<uint16_t, 32> Elements;
3475 Elements.reserve(NumElements);
3476
3477 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3478 Elements.push_back(E->getCodeUnit(i));
3479 Elements.resize(NumElements);
3480 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00003481 }
3482
Chris Lattner02cb1712012-02-06 22:52:04 +00003483 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3484 SmallVector<uint32_t, 32> Elements;
3485 Elements.reserve(NumElements);
3486
3487 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3488 Elements.push_back(E->getCodeUnit(i));
3489 Elements.resize(NumElements);
3490 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00003491}
3492
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003493static llvm::GlobalVariable *
3494GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3495 CodeGenModule &CGM, StringRef GlobalName,
John McCall7f416cc2015-09-08 08:05:57 +00003496 CharUnits Alignment) {
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003497 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3498 unsigned AddrSpace = 0;
3499 if (CGM.getLangOpts().OpenCL)
3500 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3501
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003502 llvm::Module &M = CGM.getModule();
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003503 // Create a global variable for this string
3504 auto *GV = new llvm::GlobalVariable(
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003505 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3506 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +00003507 GV->setAlignment(Alignment.getQuantity());
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003508 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003509 if (GV->isWeakForLinker()) {
3510 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3511 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3512 }
Rafael Espindolad9b26d52015-01-16 20:32:35 +00003513
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003514 return GV;
3515}
3516
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003517/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3518/// constant array for the given string literal.
John McCall7f416cc2015-09-08 08:05:57 +00003519ConstantAddress
Alexey Bataevec474782014-10-09 08:45:04 +00003520CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3521 StringRef Name) {
John McCall7f416cc2015-09-08 08:05:57 +00003522 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
James Molloye735b2b2014-05-09 16:28:56 +00003523
Richard Smith00db2f12014-07-29 21:20:12 +00003524 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3525 llvm::GlobalVariable **Entry = nullptr;
David Majnemer58e5bee2014-03-24 21:43:36 +00003526 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00003527 Entry = &ConstantStringMap[C];
3528 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00003529 if (Alignment.getQuantity() > GV->getAlignment())
3530 GV->setAlignment(Alignment.getQuantity());
3531 return ConstantAddress(GV, Alignment);
David Majnemer58e5bee2014-03-24 21:43:36 +00003532 }
Eli Friedman49ddc5f2009-11-16 05:55:46 +00003533 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00003534
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003535 SmallString<256> MangledNameBuffer;
3536 StringRef GlobalVariableName;
3537 llvm::GlobalValue::LinkageTypes LT;
David Majnemer3843a052014-03-23 17:47:16 +00003538
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003539 // Mangle the string literal if the ABI allows for it. However, we cannot
3540 // do this if we are compiling with ASan or -fwritable-strings because they
3541 // rely on strings having normal linkage.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003542 if (!LangOpts.WritableStrings &&
3543 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003544 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3545 llvm::raw_svector_ostream Out(MangledNameBuffer);
3546 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
David Majnemer58e5bee2014-03-24 21:43:36 +00003547
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003548 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3549 GlobalVariableName = MangledNameBuffer;
3550 } else {
3551 LT = llvm::GlobalValue::PrivateLinkage;
Alexey Bataevec474782014-10-09 08:45:04 +00003552 GlobalVariableName = Name;
David Majnemer58e5bee2014-03-24 21:43:36 +00003553 }
3554
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003555 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3556 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00003557 *Entry = GV;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00003558
Alexey Samsonova0ac3c22014-10-17 22:37:33 +00003559 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3560 QualType());
John McCall7f416cc2015-09-08 08:05:57 +00003561 return ConstantAddress(GV, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003562}
3563
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003564/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3565/// array for the given ObjCEncodeExpr node.
John McCall7f416cc2015-09-08 08:05:57 +00003566ConstantAddress
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003567CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3568 std::string Str;
3569 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00003570
3571 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00003572}
3573
Alexey Samsonovadc90372014-06-04 20:25:57 +00003574/// GetAddrOfConstantCString - Returns a pointer to a character array containing
3575/// the literal and a terminating '\0' character.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003576/// The result has pointer to array type.
John McCall7f416cc2015-09-08 08:05:57 +00003577ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3578 const std::string &Str, const char *GlobalName) {
Alexey Samsonovadc90372014-06-04 20:25:57 +00003579 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall7f416cc2015-09-08 08:05:57 +00003580 CharUnits Alignment =
3581 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003582
Richard Smith00db2f12014-07-29 21:20:12 +00003583 llvm::Constant *C =
3584 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3585
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003586 // Don't share any string literals if strings aren't constant.
Richard Smith00db2f12014-07-29 21:20:12 +00003587 llvm::GlobalVariable **Entry = nullptr;
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003588 if (!LangOpts.WritableStrings) {
Richard Smith00db2f12014-07-29 21:20:12 +00003589 Entry = &ConstantStringMap[C];
3590 if (auto GV = *Entry) {
John McCall7f416cc2015-09-08 08:05:57 +00003591 if (Alignment.getQuantity() > GV->getAlignment())
3592 GV->setAlignment(Alignment.getQuantity());
3593 return ConstantAddress(GV, Alignment);
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003594 }
3595 }
3596
Daniel Dunbar08b216a2009-03-31 23:42:16 +00003597 // Get the default prefix if a name wasn't specified.
3598 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00003599 GlobalName = ".str";
Chris Lattnerfb300092007-11-28 05:34:05 +00003600 // Create a global variable for this.
Alexey Samsonov175e52f2014-06-04 19:56:57 +00003601 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3602 GlobalName, Alignment);
3603 if (Entry)
Richard Smith00db2f12014-07-29 21:20:12 +00003604 *Entry = GV;
John McCall7f416cc2015-09-08 08:05:57 +00003605 return ConstantAddress(GV, Alignment);
Chris Lattnerfb300092007-11-28 05:34:05 +00003606}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00003607
John McCall7f416cc2015-09-08 08:05:57 +00003608ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00003609 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00003610 assert((E->getStorageDuration() == SD_Static ||
3611 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003612 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smithe6c01442013-06-05 00:46:14 +00003613
3614 // If we're not materializing a subobject of the temporary, keep the
3615 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00003616 QualType MaterializedType = Init->getType();
3617 if (Init == E->GetTemporaryExpr())
3618 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00003619
John McCall7f416cc2015-09-08 08:05:57 +00003620 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3621
David Majnemer2dcef9e2015-08-13 23:50:15 +00003622 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
John McCall7f416cc2015-09-08 08:05:57 +00003623 return ConstantAddress(Slot, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00003624
3625 // FIXME: If an externally-visible declaration extends multiple temporaries,
3626 // we need to give each temporary the same name in every translation unit (and
3627 // we also need to make the temporaries externally-visible).
3628 SmallString<256> Name;
3629 llvm::raw_svector_ostream Out(Name);
David Majnemerdaff3702014-05-01 17:50:17 +00003630 getCXXABI().getMangleContext().mangleReferenceTemporary(
3631 VD, E->getManglingNumber(), Out);
Richard Smithe6c01442013-06-05 00:46:14 +00003632
Craig Topper8a13c412014-05-21 05:09:00 +00003633 APValue *Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00003634 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00003635 // We might have a cached constant initializer for this temporary. Note
3636 // that this might have a different value from the value computed by
3637 // evaluating the initializer if the surrounding constant expression
3638 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00003639 Value = getContext().getMaterializedTemporaryValue(E, false);
3640 if (Value && Value->isUninit())
Craig Topper8a13c412014-05-21 05:09:00 +00003641 Value = nullptr;
Richard Smithe6c01442013-06-05 00:46:14 +00003642 }
3643
Richard Smitha509f2f2013-06-14 03:07:01 +00003644 // Try evaluating it now, it might have a constant initializer.
3645 Expr::EvalResult EvalResult;
3646 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3647 !EvalResult.hasSideEffects())
3648 Value = &EvalResult.Val;
3649
Craig Topper8a13c412014-05-21 05:09:00 +00003650 llvm::Constant *InitialValue = nullptr;
Richard Smitha509f2f2013-06-14 03:07:01 +00003651 bool Constant = false;
3652 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00003653 if (Value) {
3654 // The temporary has a constant initializer, use it.
Craig Topper8a13c412014-05-21 05:09:00 +00003655 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
Richard Smitha509f2f2013-06-14 03:07:01 +00003656 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3657 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00003658 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00003659 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00003660 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00003661 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00003662 }
3663
3664 // Create a global variable for this lifetime-extended temporary.
David Majnemer27d69db2014-04-28 22:17:59 +00003665 llvm::GlobalValue::LinkageTypes Linkage =
3666 getLLVMLinkageVarDefinition(VD, Constant);
David Majnemerc9a9c7a2015-02-19 19:25:17 +00003667 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3668 const VarDecl *InitVD;
3669 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3670 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3671 // Temporaries defined inside a class get linkonce_odr linkage because the
3672 // class can be defined in multipe translation units.
3673 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3674 } else {
3675 // There is no need for this temporary to have external linkage if the
3676 // VarDecl has external linkage.
3677 Linkage = llvm::GlobalVariable::InternalLinkage;
3678 }
3679 }
David Majnemer27d69db2014-04-28 22:17:59 +00003680 unsigned AddrSpace = GetGlobalVarAddressSpace(
3681 VD, getContext().getTargetAddressSpace(MaterializedType));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003682 auto *GV = new llvm::GlobalVariable(
David Majnemer27d69db2014-04-28 22:17:59 +00003683 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3684 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3685 AddrSpace);
David Majnemer846c2832014-04-29 06:18:53 +00003686 setGlobalVisibility(GV, VD);
John McCall7f416cc2015-09-08 08:05:57 +00003687 GV->setAlignment(Align.getQuantity());
NAKAMURA Takumic7da6da2015-05-09 21:10:07 +00003688 if (supportsCOMDAT() && GV->isWeakForLinker())
3689 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smithe6c01442013-06-05 00:46:14 +00003690 if (VD->getTLSKind())
3691 setTLSMode(GV, *VD);
David Majnemer2dcef9e2015-08-13 23:50:15 +00003692 MaterializedGlobalTemporaryMap[E] = GV;
John McCall7f416cc2015-09-08 08:05:57 +00003693 return ConstantAddress(GV, Align);
Richard Smithe6c01442013-06-05 00:46:14 +00003694}
3695
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003696/// EmitObjCPropertyImplementations - Emit information for synthesized
3697/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00003698void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003699 ObjCImplementationDecl *D) {
Aaron Ballmand85eff42014-03-14 15:02:45 +00003700 for (const auto *PID : D->property_impls()) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003701 // Dynamic is just for type-checking.
3702 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3703 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3704
3705 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00003706 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003707 // we want, that just indicates if the decl came from a
3708 // property. What we want to know is if the method is defined in
3709 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003710 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00003711 CodeGenFunction(*this).GenerateObjCGetter(
3712 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003713 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003714 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00003715 CodeGenFunction(*this).GenerateObjCSetter(
3716 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003717 }
3718 }
3719}
3720
John McCall6a4fa522011-03-22 07:05:39 +00003721static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00003722 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3723 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00003724 ivar; ivar = ivar->getNextIvar())
3725 if (ivar->getType().isDestructedType())
3726 return true;
3727
3728 return false;
3729}
3730
Fariborz Jahanian800821a2014-11-12 22:37:43 +00003731static bool AllTrivialInitializers(CodeGenModule &CGM,
3732 ObjCImplementationDecl *D) {
3733 CodeGenFunction CGF(CGM);
3734 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3735 E = D->init_end(); B != E; ++B) {
3736 CXXCtorInitializer *CtorInitExp = *B;
3737 Expr *Init = CtorInitExp->getInit();
3738 if (!CGF.isTrivialInitializer(Init))
3739 return false;
3740 }
3741 return true;
3742}
3743
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003744/// EmitObjCIvarInitializations - Emit information for ivar initialization
3745/// for an implementation.
3746void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00003747 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3748 if (needsDestructMethod(D)) {
3749 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3750 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3751 ObjCMethodDecl *DTORMethod =
3752 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003753 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003754 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00003755 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003756 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00003757 D->addInstanceMethod(DTORMethod);
3758 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00003759 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00003760 }
3761
3762 // If the implementation doesn't have any ivar initializers, we don't need
3763 // a .cxx_construct.
Fariborz Jahanian800821a2014-11-12 22:37:43 +00003764 if (D->getNumIvarInitializers() == 0 ||
3765 AllTrivialInitializers(*this, D))
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003766 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003767
John McCall6a4fa522011-03-22 07:05:39 +00003768 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3769 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003770 // The constructor returns 'self'.
3771 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3772 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00003773 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00003774 cxxSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003775 getContext().getObjCIdType(),
3776 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003777 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00003778 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00003779 /*isImplicitlyDeclared=*/true,
3780 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003781 ObjCMethodDecl::Required);
3782 D->addInstanceMethod(CTORMethod);
3783 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00003784 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003785}
3786
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003787// EmitLinkageSpec - Emit all declarations in a linkage spec.
3788void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00003789 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3790 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003791 ErrorUnsupported(LSD, "linkage spec");
3792 return;
3793 }
3794
Richard Smith8df390f2016-09-08 23:14:54 +00003795 EmitDeclContext(LSD);
3796}
3797
3798void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3799 for (auto *I : DC->decls()) {
3800 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3801 // are themselves considered "top-level", so EmitTopLevelDecl on an
3802 // ObjCImplDecl does not recursively visit them. We need to do that in
3803 // case they're nested inside another construct (LinkageSpecDecl /
3804 // ExportDecl) that does stop them from being considered "top-level".
Aaron Ballman629afae2014-03-07 19:56:05 +00003805 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00003806 for (auto *M : OID->methods())
3807 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003808 }
Richard Smith8df390f2016-09-08 23:14:54 +00003809
Aaron Ballman629afae2014-03-07 19:56:05 +00003810 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00003811 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003812}
3813
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003814/// EmitTopLevelDecl - Emit code for a single top level declaration.
3815void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00003816 // Ignore dependent declarations.
3817 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3818 return;
Mike Stump11289f42009-09-09 15:08:12 +00003819
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003820 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00003821 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00003822 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003823 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00003824 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003825 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3826 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00003827 return;
Mike Stump11289f42009-09-09 15:08:12 +00003828
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003829 EmitGlobal(cast<FunctionDecl>(D));
Alex Lorenzee024992014-08-04 18:41:51 +00003830 // Always provide some coverage mapping
3831 // even for the functions that aren't emitted.
3832 AddDeferredUnusedCoverageMapping(D);
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003833 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003834
Richard Smithada08882017-04-19 21:15:45 +00003835 case Decl::CXXDeductionGuide:
3836 // Function-like, but does not result in code emission.
3837 break;
3838
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003839 case Decl::Var:
Richard Smithbdb84f32016-07-22 23:36:59 +00003840 case Decl::Decomposition:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003841 // Skip variable templates
3842 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3843 return;
3844 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00003845 EmitGlobal(cast<VarDecl>(D));
Richard Smithda383632016-08-15 01:33:41 +00003846 if (auto *DD = dyn_cast<DecompositionDecl>(D))
3847 for (auto *B : DD->bindings())
3848 if (auto *HD = B->getHoldingVar())
3849 EmitGlobal(HD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003850 break;
3851
John McCall32f44bd2011-04-12 01:01:22 +00003852 // Indirect fields from global anonymous structs and unions can be
3853 // ignored; only the actual variable requires IR gen support.
3854 case Decl::IndirectField:
3855 break;
3856
Anders Carlssonf7475242009-04-15 15:55:24 +00003857 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003858 case Decl::Namespace:
Richard Smith8df390f2016-09-08 23:14:54 +00003859 EmitDeclContext(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003860 break;
Richard Smith62f19e72016-06-25 00:15:56 +00003861 case Decl::CXXRecord:
David Blaikie1ac9c982017-04-11 21:13:37 +00003862 if (DebugInfo) {
3863 if (auto *ES = D->getASTContext().getExternalSource())
3864 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3865 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3866 }
Richard Smith62f19e72016-06-25 00:15:56 +00003867 // Emit any static data members, they may be definitions.
3868 for (auto *I : cast<CXXRecordDecl>(D)->decls())
3869 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3870 EmitTopLevelDecl(I);
3871 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00003872 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00003873 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003874 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00003875 case Decl::VarTemplate:
3876 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00003877 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00003878 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00003879 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00003880 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00003881 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00003882 case Decl::Using: // using X; [C++]
3883 if (CGDebugInfo *DI = getModuleDebugInfo())
3884 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3885 return;
David Blaikief121b932013-05-20 22:50:41 +00003886 case Decl::NamespaceAlias:
3887 if (CGDebugInfo *DI = getModuleDebugInfo())
3888 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3889 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00003890 case Decl::UsingDirective: // using namespace X; [C++]
3891 if (CGDebugInfo *DI = getModuleDebugInfo())
3892 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3893 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00003894 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00003895 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00003896 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3897 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00003898 return;
3899
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00003900 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00003901 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003902 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00003903 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3904 return;
Reid Klecknere7de47e2013-07-22 13:51:44 +00003905 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00003906 break;
Anders Carlsson87835432009-06-11 21:22:55 +00003907
3908 case Decl::StaticAssert:
3909 // Nothing to do.
3910 break;
3911
Anders Carlssonf7475242009-04-15 15:55:24 +00003912 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00003913
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003914 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00003915 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00003916 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00003917 break;
3918
Douglas Gregorf6102672012-01-01 21:23:57 +00003919 case Decl::ObjCProtocol: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003920 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorf6102672012-01-01 21:23:57 +00003921 if (Proto->isThisDeclarationADefinition())
3922 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003923 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00003924 }
3925
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003926 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003927 // Categories have properties but don't support synthesize so we
3928 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00003929 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003930 break;
3931
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003932 case Decl::ObjCImplementation: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003933 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00003934 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00003935 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00003936 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00003937 // Emit global variable debug information.
3938 if (CGDebugInfo *DI = getModuleDebugInfo())
Benjamin Kramer8c305922016-02-02 11:06:51 +00003939 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00003940 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3941 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003942 break;
Mike Stump11289f42009-09-09 15:08:12 +00003943 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003944 case Decl::ObjCMethod: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003945 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003946 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003947 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003948 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3949 break;
3950 }
Mike Stump11289f42009-09-09 15:08:12 +00003951 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00003952 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003953 break;
3954
Nico Weber66220292016-03-02 17:28:48 +00003955 case Decl::PragmaComment: {
3956 const auto *PCD = cast<PragmaCommentDecl>(D);
3957 switch (PCD->getCommentKind()) {
3958 case PCK_Unknown:
3959 llvm_unreachable("unexpected pragma comment kind");
3960 case PCK_Linker:
3961 AppendLinkerOptions(PCD->getArg());
3962 break;
3963 case PCK_Lib:
3964 AddDependentLib(PCD->getArg());
3965 break;
3966 case PCK_Compiler:
3967 case PCK_ExeStr:
3968 case PCK_User:
3969 break; // We ignore all of these.
3970 }
3971 break;
3972 }
3973
Nico Webercbbaeb12016-03-02 19:28:54 +00003974 case Decl::PragmaDetectMismatch: {
3975 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3976 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3977 break;
3978 }
3979
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00003980 case Decl::LinkageSpec:
3981 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003982 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003983
3984 case Decl::FileScopeAsm: {
Artem Belevich0488d1e2015-04-27 18:52:00 +00003985 // File-scope asm is ignored during device-side CUDA compilation.
3986 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3987 break;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003988 // File-scope asm is ignored during device-side OpenMP compilation.
3989 if (LangOpts.OpenMPIsDevice)
3990 break;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003991 auto *AD = cast<FileScopeAsmDecl>(D);
Joerg Sonnenbergerdfd511e2015-03-13 00:54:30 +00003992 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003993 break;
3994 }
Mike Stump11289f42009-09-09 15:08:12 +00003995
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003996 case Decl::Import: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003997 auto *Import = cast<ImportDecl>(D);
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003998
Richard Smithdc1f0422016-07-20 19:10:16 +00003999 // If we've already imported this module, we're done.
4000 if (!ImportedModules.insert(Import->getImportedModule()))
Richard Smithc52efa72015-08-19 02:30:28 +00004001 break;
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004002
Richard Smithdc1f0422016-07-20 19:10:16 +00004003 // Emit debug information for direct imports.
4004 if (!Import->getImportedOwningModule()) {
4005 if (CGDebugInfo *DI = getModuleDebugInfo())
4006 DI->EmitImportDecl(*Import);
4007 }
4008
Manman Ren3b5dbf22016-10-14 18:55:44 +00004009 // Find all of the submodules and emit the module initializers.
4010 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4011 SmallVector<clang::Module *, 16> Stack;
4012 Visited.insert(Import->getImportedModule());
4013 Stack.push_back(Import->getImportedModule());
4014
4015 while (!Stack.empty()) {
4016 clang::Module *Mod = Stack.pop_back_val();
4017 if (!EmittedModuleInitializers.insert(Mod).second)
4018 continue;
4019
4020 for (auto *D : Context.getModuleInitializers(Mod))
4021 EmitTopLevelDecl(D);
4022
4023 // Visit the submodules of this module.
4024 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4025 SubEnd = Mod->submodule_end();
4026 Sub != SubEnd; ++Sub) {
4027 // Skip explicit children; they need to be explicitly imported to emit
4028 // the initializers.
4029 if ((*Sub)->IsExplicit)
4030 continue;
4031
4032 if (Visited.insert(*Sub).second)
4033 Stack.push_back(*Sub);
4034 }
4035 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004036 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004037 }
4038
Richard Smith8df390f2016-09-08 23:14:54 +00004039 case Decl::Export:
4040 EmitDeclContext(cast<ExportDecl>(D));
4041 break;
4042
Alexey Bataev97720002014-11-11 04:05:39 +00004043 case Decl::OMPThreadPrivate:
4044 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4045 break;
4046
David Blaikie0e716b42014-03-03 23:48:23 +00004047 case Decl::ClassTemplateSpecialization: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004048 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
David Blaikie0e716b42014-03-03 23:48:23 +00004049 if (DebugInfo &&
David Blaikie0317bc92014-12-16 23:49:18 +00004050 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4051 Spec->hasDefinition())
David Blaikie0e716b42014-03-03 23:48:23 +00004052 DebugInfo->completeTemplateDefinition(*Spec);
Richard Smitha634ff22014-12-01 18:59:10 +00004053 break;
David Blaikie0e716b42014-03-03 23:48:23 +00004054 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00004055
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004056 case Decl::OMPDeclareReduction:
4057 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4058 break;
4059
Mike Stump11289f42009-09-09 15:08:12 +00004060 default:
Mike Stump18bb9282009-05-16 07:57:57 +00004061 // Make sure we handled everything we should, every other kind is a
4062 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4063 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004064 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Richard Smitha634ff22014-12-01 18:59:10 +00004065 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00004066 }
4067}
John McCall09ae0322010-07-06 23:57:41 +00004068
Alex Lorenzee024992014-08-04 18:41:51 +00004069void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4070 // Do we need to generate coverage mapping?
4071 if (!CodeGenOpts.CoverageMapping)
4072 return;
4073 switch (D->getKind()) {
4074 case Decl::CXXConversion:
4075 case Decl::CXXMethod:
4076 case Decl::Function:
4077 case Decl::ObjCMethod:
4078 case Decl::CXXConstructor:
4079 case Decl::CXXDestructor: {
Justin Bogner203f0922015-07-28 00:41:51 +00004080 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
Alex Lorenzee024992014-08-04 18:41:51 +00004081 return;
4082 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4083 if (I == DeferredEmptyCoverageMappingDecls.end())
4084 DeferredEmptyCoverageMappingDecls[D] = true;
4085 break;
4086 }
4087 default:
4088 break;
4089 };
4090}
4091
4092void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4093 // Do we need to generate coverage mapping?
4094 if (!CodeGenOpts.CoverageMapping)
4095 return;
4096 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4097 if (Fn->isTemplateInstantiation())
4098 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4099 }
4100 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4101 if (I == DeferredEmptyCoverageMappingDecls.end())
4102 DeferredEmptyCoverageMappingDecls[D] = false;
4103 else
4104 I->second = false;
4105}
4106
4107void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00004108 std::vector<const Decl *> DeferredDecls;
Richard Trieub5841332015-04-15 01:21:42 +00004109 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
Alex Lorenzee024992014-08-04 18:41:51 +00004110 if (!I.second)
4111 continue;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00004112 DeferredDecls.push_back(I.first);
4113 }
4114 // Sort the declarations by their location to make sure that the tests get a
4115 // predictable order for the coverage mapping for the unused declarations.
4116 if (CodeGenOpts.DumpCoverageMapping)
4117 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4118 [] (const Decl *LHS, const Decl *RHS) {
4119 return LHS->getLocStart() < RHS->getLocStart();
4120 });
4121 for (const auto *D : DeferredDecls) {
Alex Lorenzee024992014-08-04 18:41:51 +00004122 switch (D->getKind()) {
4123 case Decl::CXXConversion:
4124 case Decl::CXXMethod:
4125 case Decl::Function:
4126 case Decl::ObjCMethod: {
4127 CodeGenPGO PGO(*this);
4128 GlobalDecl GD(cast<FunctionDecl>(D));
4129 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4130 getFunctionLinkage(GD));
4131 break;
4132 }
4133 case Decl::CXXConstructor: {
4134 CodeGenPGO PGO(*this);
4135 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4136 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4137 getFunctionLinkage(GD));
4138 break;
4139 }
4140 case Decl::CXXDestructor: {
4141 CodeGenPGO PGO(*this);
4142 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4143 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4144 getFunctionLinkage(GD));
4145 break;
4146 }
4147 default:
4148 break;
4149 };
4150 }
4151}
4152
John McCall09ae0322010-07-06 23:57:41 +00004153/// Turns the given pointer into a constant.
4154static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4155 const void *Ptr) {
4156 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00004157 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00004158 return llvm::ConstantInt::get(i64, PtrInt);
4159}
4160
4161static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4162 llvm::NamedMDNode *&GlobalMetadata,
4163 GlobalDecl D,
4164 llvm::GlobalValue *Addr) {
4165 if (!GlobalMetadata)
4166 GlobalMetadata =
4167 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4168
4169 // TODO: should we report variant information for ctors/dtors?
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004170 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4171 llvm::ConstantAsMetadata::get(GetPointerConstant(
4172 CGM.getLLVMContext(), D.getDecl()))};
Jay Foadea324f12011-04-21 19:59:12 +00004173 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00004174}
4175
Richard Smithdf931ce2013-04-06 05:00:46 +00004176/// For each function which is declared within an extern "C" region and marked
4177/// as 'used', but has internal linkage, create an alias from the unmangled
4178/// name to the mangled name if possible. People expect to be able to refer
4179/// to such functions with an unmangled name from inline assembly within the
4180/// same translation unit.
4181void CodeGenModule::EmitStaticExternCAliases() {
Justin Lebarcd2f6bb2016-01-25 22:36:37 +00004182 // Don't do anything if we're generating CUDA device code -- the NVPTX
4183 // assembly target doesn't support aliases.
4184 if (Context.getTargetInfo().getTriple().isNVPTX())
4185 return;
Yaron Kerenb54db522015-06-11 12:33:25 +00004186 for (auto &I : StaticExternCValues) {
4187 IdentifierInfo *Name = I.first;
4188 llvm::GlobalValue *Val = I.second;
Richard Smith85465e62013-04-06 07:07:44 +00004189 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola27c60b52014-06-03 02:42:01 +00004190 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith85465e62013-04-06 07:07:44 +00004191 }
Richard Smithdf931ce2013-04-06 05:00:46 +00004192}
4193
Alp Tokerfb8d02b2014-06-05 22:10:59 +00004194bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4195 GlobalDecl &Result) const {
4196 auto Res = Manglings.find(MangledName);
4197 if (Res == Manglings.end())
4198 return false;
4199 Result = Res->getValue();
4200 return true;
4201}
4202
John McCall09ae0322010-07-06 23:57:41 +00004203/// Emits metadata nodes associating all the global values in the
4204/// current module with the Decls they came from. This is useful for
4205/// projects using IR gen as a subroutine.
4206///
4207/// Since there's currently no way to associate an MDNode directly
4208/// with an llvm::GlobalValue, we create a global named metadata
4209/// with the name 'clang.global.decl.ptrs'.
4210void CodeGenModule::EmitDeclMetadata() {
Craig Topper8a13c412014-05-21 05:09:00 +00004211 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004212
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004213 for (auto &I : MangledDeclNames) {
4214 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
Keno Fischer0e2d4222015-11-05 23:18:44 +00004215 // Some mangled names don't necessarily have an associated GlobalValue
4216 // in this module, e.g. if we mangled it for DebugInfo.
4217 if (Addr)
4218 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall09ae0322010-07-06 23:57:41 +00004219 }
4220}
4221
4222/// Emits metadata nodes for all the local variables in the current
4223/// function.
4224void CodeGenFunction::EmitDeclMetadata() {
4225 if (LocalDeclMap.empty()) return;
4226
4227 llvm::LLVMContext &Context = getLLVMContext();
4228
4229 // Find the unique metadata ID for this name.
4230 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4231
Craig Topper8a13c412014-05-21 05:09:00 +00004232 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall09ae0322010-07-06 23:57:41 +00004233
Robert Lytton5b88f78f2014-07-03 09:30:29 +00004234 for (auto &I : LocalDeclMap) {
4235 const Decl *D = I.first;
John McCall7f416cc2015-09-08 08:05:57 +00004236 llvm::Value *Addr = I.second.getPointer();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004237 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004238 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004239 Alloca->setMetadata(
4240 DeclPtrKind, llvm::MDNode::get(
4241 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004242 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall09ae0322010-07-06 23:57:41 +00004243 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4244 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4245 }
4246 }
4247}
Daniel Dunbar900546d2010-07-16 00:00:15 +00004248
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004249void CodeGenModule::EmitVersionIdentMetadata() {
4250 llvm::NamedMDNode *IdentMetadata =
4251 TheModule.getOrInsertNamedMetadata("llvm.ident");
4252 std::string Version = getClangFullVersion();
4253 llvm::LLVMContext &Ctx = TheModule.getContext();
4254
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00004255 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola3bfa4682013-10-16 19:28:50 +00004256 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4257}
4258
Robert Lytton57765d52014-07-03 09:30:33 +00004259void CodeGenModule::EmitTargetMetadata() {
Richard Smith1ba0a072014-08-01 20:39:36 +00004260 // Warning, new MangledDeclNames may be appended within this loop.
4261 // We rely on MapVector insertions adding new elements to the end
4262 // of the container.
4263 // FIXME: Move this loop into the one target that needs it, and only
4264 // loop over those declarations for which we couldn't emit the target
4265 // metadata when we emitted the declaration.
4266 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
Richard Smith570706d2014-08-01 22:17:28 +00004267 auto Val = *(MangledDeclNames.begin() + I);
Richard Smith1ba0a072014-08-01 20:39:36 +00004268 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4269 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Robert Lytton57765d52014-07-03 09:30:33 +00004270 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4271 }
4272}
4273
Nick Lewycky85c011d2011-05-05 00:08:20 +00004274void CodeGenModule::EmitCoverageFile() {
Nick Lewycky97e49ac2016-08-31 23:04:32 +00004275 if (getCodeGenOpts().CoverageDataFile.empty() &&
4276 getCodeGenOpts().CoverageNotesFile.empty())
4277 return;
4278
4279 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4280 if (!CUNode)
4281 return;
4282
4283 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4284 llvm::LLVMContext &Ctx = TheModule.getContext();
4285 auto *CoverageDataFile =
4286 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4287 auto *CoverageNotesFile =
4288 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4289 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4290 llvm::MDNode *CU = CUNode->getOperand(i);
4291 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4292 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky480cb992011-05-04 20:46:58 +00004293 }
4294}
Nico Webercf4ff5862012-10-11 10:13:44 +00004295
Nico Weber17d3a2c2014-09-08 16:26:36 +00004296llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Webercf4ff5862012-10-11 10:13:44 +00004297 // Sema has checked that all uuid strings are of the form
4298 // "12345678-1234-1234-1234-1234567890ab".
4299 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00004300 for (unsigned i = 0; i < 36; ++i) {
4301 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4302 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00004303 }
Nico Webercf4ff5862012-10-11 10:13:44 +00004304
Nico Weberdfa274e2014-09-08 16:11:15 +00004305 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemerbbecd092013-08-15 19:59:14 +00004306 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00004307
David Majnemerbbecd092013-08-15 19:59:14 +00004308 llvm::Constant *Field3[8];
4309 for (unsigned Idx = 0; Idx < 8; ++Idx)
4310 Field3[Idx] = llvm::ConstantInt::get(
4311 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4312
4313 llvm::Constant *Fields[4] = {
4314 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4315 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4316 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4317 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4318 };
4319
4320 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00004321}
David Majnemere2cb8d12014-07-07 06:20:47 +00004322
4323llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4324 bool ForEH) {
4325 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4326 // FIXME: should we even be calling this method if RTTI is disabled
4327 // and it's not for EH?
4328 if (!ForEH && !getLangOpts().RTTI)
4329 return llvm::Constant::getNullValue(Int8PtrTy);
4330
4331 if (ForEH && Ty->isObjCObjectPointerType() &&
4332 LangOpts.ObjCRuntime.isGNUFamily())
4333 return ObjCRuntime->GetEHType(Ty);
4334
David Majnemer443250f2015-03-17 20:35:00 +00004335 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
David Majnemere2cb8d12014-07-07 06:20:47 +00004336}
4337
Alexey Bataev97720002014-11-11 04:05:39 +00004338void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4339 for (auto RefExpr : D->varlists()) {
4340 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4341 bool PerformInit =
4342 VD->getAnyInitializer() &&
4343 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4344 /*ForRef=*/false);
John McCall7f416cc2015-09-08 08:05:57 +00004345
4346 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
Alexey Bataev3eff5f42015-02-25 08:32:46 +00004347 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00004348 VD, Addr, RefExpr->getLocStart(), PerformInit))
Alexey Bataev97720002014-11-11 04:05:39 +00004349 CXXGlobalInits.push_back(InitFunction);
4350 }
4351}
Peter Collingbourne86d34a72015-06-17 19:08:05 +00004352
Peter Collingbourne25a80bf2015-09-08 23:01:30 +00004353llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4354 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4355 if (InternalId)
4356 return InternalId;
4357
4358 if (isExternallyVisible(T->getLinkage())) {
4359 std::string OutName;
4360 llvm::raw_string_ostream Out(OutName);
4361 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4362
4363 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4364 } else {
4365 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4366 llvm::ArrayRef<llvm::Metadata *>());
4367 }
4368
4369 return InternalId;
4370}
4371
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004372/// Returns whether this module needs the "all-vtables" type identifier.
4373bool CodeGenModule::NeedAllVtablesTypeId() const {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004374 // Returns true if at least one of vtable-based CFI checkers is enabled and
4375 // is not in the trapping mode.
4376 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4377 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4378 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4379 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4380 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4381 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4382 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4383 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4384}
4385
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004386void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4387 CharUnits Offset,
4388 const CXXRecordDecl *RD) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004389 llvm::Metadata *MD =
4390 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004391 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004392
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004393 if (CodeGenOpts.SanitizeCfiCrossDso)
4394 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4395 VTable->addTypeMetadata(Offset.getQuantity(),
4396 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004397
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004398 if (NeedAllVtablesTypeId()) {
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004399 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004400 VTable->addTypeMetadata(Offset.getQuantity(), MD);
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004401 }
Peter Collingbourne86d34a72015-06-17 19:08:05 +00004402}
Eric Christopher2b90a642015-11-11 23:05:08 +00004403
4404// Fills in the supplied string map with the set of target features for the
4405// passed in function.
4406void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4407 const FunctionDecl *FD) {
4408 StringRef TargetCPU = Target.getTargetOpts().CPU;
4409 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4410 // If we have a TargetAttr build up the feature map based on that.
4411 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4412
4413 // Make a copy of the features as passed on the command line into the
4414 // beginning of the additional features from the function to override.
4415 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4416 Target.getTargetOpts().FeaturesAsWritten.begin(),
4417 Target.getTargetOpts().FeaturesAsWritten.end());
4418
4419 if (ParsedAttr.second != "")
4420 TargetCPU = ParsedAttr.second;
4421
4422 // Now populate the feature map, first with the TargetCPU which is either
4423 // the default or a new one from the target attribute string. Then we'll use
4424 // the passed in features (FeaturesAsWritten) along with the new ones from
4425 // the attribute.
4426 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4427 } else {
4428 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4429 Target.getTargetOpts().Features);
4430 }
4431}
Peter Collingbournedc134532016-01-16 00:31:22 +00004432
4433llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4434 if (!SanStats)
4435 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4436
4437 return *SanStats;
4438}
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00004439llvm::Value *
4440CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4441 CodeGenFunction &CGF) {
4442 llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4443 auto SamplerT = getOpenCLRuntime().getSamplerType();
4444 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4445 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4446 "__translate_sampler_initializer"),
4447 {C});
4448}