blob: 1b6439b68171b729f3fd26616d10524d40d914e6 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070021#include "CGOpenMPRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "CodeGenFunction.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070023#include "CodeGenPGO.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "CodeGenTBAA.h"
Stephen Hines0e2c34f2015-03-23 12:09:02 -070025#include "CoverageMappingGen.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000026#include "TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000028#include "clang/AST/CharUnits.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000029#include "clang/AST/DeclCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/AST/DeclObjC.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000031#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000032#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000033#include "clang/AST/RecordLayout.h"
Rafael Espindolaa411d2f2011-10-26 20:41:06 +000034#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindolabcf6b982011-12-19 14:41:01 +000035#include "clang/Basic/Builtins.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000036#include "clang/Basic/CharInfo.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000037#include "clang/Basic/Diagnostic.h"
Douglas Gregorb6cbe512013-01-14 17:21:00 +000038#include "clang/Basic/Module.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000039#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040#include "clang/Basic/TargetInfo.h"
Rafael Espindola9686f122013-10-16 19:28:50 +000041#include "clang/Basic/Version.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000042#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindolad2054982013-10-22 19:26:13 +000043#include "clang/Sema/SemaDiagnostic.h"
Sebastian Redl19b1a6e2012-02-25 20:51:20 +000044#include "llvm/ADT/APSInt.h"
John McCall6374c332010-03-06 00:35:14 +000045#include "llvm/ADT/Triple.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070046#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000047#include "llvm/IR/CallingConv.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/Intrinsics.h"
50#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Module.h"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070052#include "llvm/ProfileData/InstrProfReader.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000053#include "llvm/Support/ConvertUTF.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000054#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000055
Reid Spencer5f016e22007-07-11 17:01:13 +000056using namespace clang;
57using namespace CodeGen;
58
Julien Lerouge77f68bb2011-09-09 22:41:49 +000059static const char AnnotationSection[] = "llvm.metadata";
60
Stephen Hines651f13c2014-04-23 16:59:28 -070061static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCall64aa4b32013-04-16 22:48:15 +000062 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +000063 case TargetCXXABI::GenericAArch64:
John McCall96fcde02013-01-25 23:36:14 +000064 case TargetCXXABI::GenericARM:
65 case TargetCXXABI::iOS:
Stephen Hines651f13c2014-04-23 16:59:28 -070066 case TargetCXXABI::iOS64:
Stephen Hines0e2c34f2015-03-23 12:09:02 -070067 case TargetCXXABI::GenericMIPS:
John McCall96fcde02013-01-25 23:36:14 +000068 case TargetCXXABI::GenericItanium:
Stephen Hines651f13c2014-04-23 16:59:28 -070069 return CreateItaniumCXXABI(CGM);
John McCall96fcde02013-01-25 23:36:14 +000070 case TargetCXXABI::Microsoft:
Stephen Hines651f13c2014-04-23 16:59:28 -070071 return CreateMicrosoftCXXABI(CGM);
John McCallf16aa102010-08-22 21:01:12 +000072 }
73
74 llvm_unreachable("invalid C++ ABI kind");
John McCallf16aa102010-08-22 21:01:12 +000075}
76
Chandler Carruth2811ccf2009-11-12 17:24:48 +000077CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall3abae092013-04-16 22:48:20 +000078 llvm::Module &M, const llvm::DataLayout &TD,
Stephen Hines176edba2014-12-01 14:53:08 -080079 DiagnosticsEngine &diags,
80 CoverageSourceInfo *CoverageInfo)
Alexey Samsonov6a4c5dc2013-08-12 11:48:05 +000081 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
82 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -070083 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
84 TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
85 ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
86 CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
87 NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
88 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
89 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
90 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
91 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
92 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
Stephen Hines176edba2014-12-01 14:53:08 -080093 LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
Will Dietz4f45bc02013-01-18 11:30:38 +000094
Chris Lattner8b418682012-02-07 00:39:47 +000095 // Initialize the type cache.
96 llvm::LLVMContext &LLVMContext = M.getContext();
97 VoidTy = llvm::Type::getVoidTy(LLVMContext);
98 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
99 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
100 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
101 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
102 FloatTy = llvm::Type::getFloatTy(LLVMContext);
103 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
104 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
105 PointerAlignInBytes =
106 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
108 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
109 Int8PtrTy = Int8Ty->getPointerTo(0);
110 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
111
John McCallbd7370a2013-02-28 19:01:20 +0000112 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700113 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
John McCallbd7370a2013-02-28 19:01:20 +0000114
David Blaikie4e4d0842012-03-11 07:00:24 +0000115 if (LangOpts.ObjC1)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000116 createObjCRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000117 if (LangOpts.OpenCL)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000118 createOpenCLRuntime();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700119 if (LangOpts.OpenMP)
120 createOpenMPRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000121 if (LangOpts.CUDA)
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000122 createCUDARuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000123
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000124 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Stephen Hines176edba2014-12-01 14:53:08 -0800125 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000126 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
127 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Stephen Hines651f13c2014-04-23 16:59:28 -0700128 getCXXABI().getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +0000129
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000130 // If debug info or coverage generation is enabled, create the CGDebugInfo
131 // object.
Douglas Gregor4cdad312012-10-23 20:05:01 +0000132 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000133 CodeGenOpts.EmitGcovArcs ||
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000134 CodeGenOpts.EmitGcovNotes)
135 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +0000136
137 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +0000138
David Blaikie4e4d0842012-03-11 07:00:24 +0000139 if (C.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000140 ARCData = new ARCEntrypoints();
141 RRData = new RREntrypoints();
Stephen Hines651f13c2014-04-23 16:59:28 -0700142
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700143 if (!CodeGenOpts.InstrProfileInput.empty()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700144 auto ReaderOrErr =
145 llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
146 if (std::error_code EC = ReaderOrErr.getError()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700147 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
148 "Could not read profile: %0");
149 getDiags().Report(DiagID) << EC.message();
150 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700151 PGOReader = std::move(ReaderOrErr.get());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700152 }
Stephen Hines176edba2014-12-01 14:53:08 -0800153
154 // If coverage mapping generation is enabled, create the
155 // CoverageMappingModuleGen object.
156 if (CodeGenOpts.CoverageMapping)
157 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
Chris Lattner2b94fe32008-03-01 08:45:05 +0000158}
159
160CodeGenModule::~CodeGenModule() {
Peter Collingbournee9265232011-07-27 20:29:46 +0000161 delete ObjCRuntime;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000162 delete OpenCLRuntime;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700163 delete OpenMPRuntime;
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000164 delete CUDARuntime;
Ted Kremenek0628b722011-10-08 05:28:26 +0000165 delete TheTargetCodeGenInfo;
Dan Gohman4376c852010-10-15 18:04:46 +0000166 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000167 delete DebugInfo;
John McCallf85e1932011-06-15 23:02:42 +0000168 delete ARCData;
169 delete RRData;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000170}
171
David Chisnall0d13f6f2010-01-23 02:40:42 +0000172void CodeGenModule::createObjCRuntime() {
John McCall260611a2012-06-20 06:18:46 +0000173 // This is just isGNUFamily(), but we want to force implementors of
174 // new ABIs to decide how best to do this.
175 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000176 case ObjCRuntime::GNUstep:
177 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000178 case ObjCRuntime::ObjFW:
Peter Collingbournee9265232011-07-27 20:29:46 +0000179 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000180 return;
181
182 case ObjCRuntime::FragileMacOSX:
183 case ObjCRuntime::MacOSX:
184 case ObjCRuntime::iOS:
Peter Collingbournee9265232011-07-27 20:29:46 +0000185 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000186 return;
187 }
188 llvm_unreachable("bad runtime kind");
David Chisnall0d13f6f2010-01-23 02:40:42 +0000189}
190
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000191void CodeGenModule::createOpenCLRuntime() {
192 OpenCLRuntime = new CGOpenCLRuntime(*this);
193}
194
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700195void CodeGenModule::createOpenMPRuntime() {
196 OpenMPRuntime = new CGOpenMPRuntime(*this);
197}
198
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000199void CodeGenModule::createCUDARuntime() {
200 CUDARuntime = CreateNVCUDARuntime(*this);
201}
202
Stephen Hines176edba2014-12-01 14:53:08 -0800203void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
204 Replacements[Name] = C;
205}
206
Rafael Espindola61a0a752013-11-05 21:37:29 +0000207void CodeGenModule::applyReplacements() {
208 for (ReplacementsTy::iterator I = Replacements.begin(),
209 E = Replacements.end();
210 I != E; ++I) {
211 StringRef MangledName = I->first();
212 llvm::Constant *Replacement = I->second;
213 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
214 if (!Entry)
215 continue;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700216 auto *OldF = cast<llvm::Function>(Entry);
217 auto *NewF = dyn_cast<llvm::Function>(Replacement);
Rafael Espindola081c2152013-11-12 04:53:19 +0000218 if (!NewF) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700219 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
220 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
Stephen Hines651f13c2014-04-23 16:59:28 -0700221 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700222 auto *CE = cast<llvm::ConstantExpr>(Replacement);
Stephen Hines651f13c2014-04-23 16:59:28 -0700223 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
224 CE->getOpcode() == llvm::Instruction::GetElementPtr);
225 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
226 }
Rafael Espindola081c2152013-11-12 04:53:19 +0000227 }
228
229 // Replace old with new, but keep the old order.
230 OldF->replaceAllUsesWith(Replacement);
231 if (NewF) {
232 NewF->removeFromParent();
233 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
234 }
235 OldF->eraseFromParent();
Rafael Espindola61a0a752013-11-05 21:37:29 +0000236 }
237}
238
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700239// This is only used in aliases that we created and we know they have a
240// linear structure.
241static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
242 llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
243 const llvm::Constant *C = &GA;
244 for (;;) {
245 C = C->stripPointerCasts();
246 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
247 return GO;
248 // stripPointerCasts will not walk over weak aliases.
249 auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
250 if (!GA2)
251 return nullptr;
Stephen Hines176edba2014-12-01 14:53:08 -0800252 if (!Visited.insert(GA2).second)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700253 return nullptr;
254 C = GA2->getAliasee();
255 }
256}
257
Rafael Espindolad2054982013-10-22 19:26:13 +0000258void CodeGenModule::checkAliases() {
Stephen Hines651f13c2014-04-23 16:59:28 -0700259 // Check if the constructed aliases are well formed. It is really unfortunate
260 // that we have to do this in CodeGen, but we only construct mangled names
261 // and aliases during codegen.
Rafael Espindolad2054982013-10-22 19:26:13 +0000262 bool Error = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700263 DiagnosticsEngine &Diags = getDiags();
Rafael Espindolad2054982013-10-22 19:26:13 +0000264 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
265 E = Aliases.end(); I != E; ++I) {
266 const GlobalDecl &GD = *I;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700267 const auto *D = cast<ValueDecl>(GD.getDecl());
Rafael Espindolad2054982013-10-22 19:26:13 +0000268 const AliasAttr *AA = D->getAttr<AliasAttr>();
269 StringRef MangledName = getMangledName(GD);
270 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700271 auto *Alias = cast<llvm::GlobalAlias>(Entry);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700272 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
273 if (!GV) {
274 Error = true;
275 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
276 } else if (GV->isDeclaration()) {
Rafael Espindolad2054982013-10-22 19:26:13 +0000277 Error = true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700278 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
Stephen Hines651f13c2014-04-23 16:59:28 -0700279 }
280
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700281 llvm::Constant *Aliasee = Alias->getAliasee();
282 llvm::GlobalValue *AliaseeGV;
283 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
284 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
285 else
286 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
287
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700288 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
289 StringRef AliasSection = SA->getName();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700290 if (AliasSection != AliaseeGV->getSection())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700291 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
292 << AliasSection;
Rafael Espindolad2054982013-10-22 19:26:13 +0000293 }
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700294
295 // We have to handle alias to weak aliases in here. LLVM itself disallows
296 // this since the object semantics would not match the IL one. For
297 // compatibility with gcc we implement it by just pointing the alias
298 // to its aliasee's aliasee. We also warn, since the user is probably
299 // expecting the link to be weak.
300 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
301 if (GA->mayBeOverridden()) {
302 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
303 << GV->getName() << GA->getName();
304 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
305 GA->getAliasee(), Alias->getType());
306 Alias->setAliasee(Aliasee);
307 }
308 }
Rafael Espindolad2054982013-10-22 19:26:13 +0000309 }
310 if (!Error)
311 return;
312
313 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
314 E = Aliases.end(); I != E; ++I) {
315 const GlobalDecl &GD = *I;
316 StringRef MangledName = getMangledName(GD);
317 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700318 auto *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindolad2054982013-10-22 19:26:13 +0000319 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
320 Alias->eraseFromParent();
321 }
322}
323
Stephen Hines651f13c2014-04-23 16:59:28 -0700324void CodeGenModule::clear() {
325 DeferredDeclsToEmit.clear();
326}
327
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700328void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
329 StringRef MainFile) {
330 if (!hasDiagnostics())
331 return;
332 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
333 if (MainFile.empty())
334 MainFile = "<stdin>";
335 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
336 } else
337 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
338 << Mismatched;
339}
340
Ted Kremenek815c78f2008-08-05 18:50:11 +0000341void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000342 EmitDeferred();
Rafael Espindola61a0a752013-11-05 21:37:29 +0000343 applyReplacements();
Rafael Espindolad2054982013-10-22 19:26:13 +0000344 checkAliases();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000345 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000346 EmitCXXGlobalDtorFunc();
Richard Smithb80a16e2013-04-19 16:42:07 +0000347 EmitCXXThreadLocalInitFunc();
Peter Collingbournee9265232011-07-27 20:29:46 +0000348 if (ObjCRuntime)
349 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000350 AddGlobalCtor(ObjCInitFunction);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700351 if (PGOReader && PGOStats.hasDiagnostics())
352 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000353 EmitCtorList(GlobalCtors, "llvm.global_ctors");
354 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000355 EmitGlobalAnnotations();
Richard Smith00249372013-04-06 05:00:46 +0000356 EmitStaticExternCAliases();
Stephen Hines176edba2014-12-01 14:53:08 -0800357 EmitDeferredUnusedCoverageMappings();
358 if (CoverageMapping)
359 CoverageMapping->emit();
Stephen Hines651f13c2014-04-23 16:59:28 -0700360 emitLLVMUsed();
Douglas Gregorf43b7212013-01-16 01:23:41 +0000361
Reid Kleckner3190ca92013-05-08 13:44:39 +0000362 if (CodeGenOpts.Autolink &&
363 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorf43b7212013-01-16 01:23:41 +0000364 EmitModuleLinkOptions();
365 }
Manman Renfc0f91c2013-06-19 01:46:49 +0000366 if (CodeGenOpts.DwarfVersion)
367 // We actually want the latest version when there are conflicts.
368 // We can change from Warning to Latest if such mode is supported.
369 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
370 CodeGenOpts.DwarfVersion);
Manman Ren1f856a02013-12-09 20:27:01 +0000371 if (DebugInfo)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700372 // We support a single version in the linked module. The LLVM
373 // parser will drop debug info with a different version number
374 // (and warn about it, too).
375 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
Manman Ren82e23c22013-12-09 21:04:35 +0000376 llvm::DEBUG_METADATA_VERSION);
Douglas Gregor5d75ea72013-01-14 18:28:43 +0000377
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700378 // We need to record the widths of enums and wchar_t, so that we can generate
379 // the correct build attributes in the ARM backend.
380 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
381 if ( Arch == llvm::Triple::arm
382 || Arch == llvm::Triple::armeb
383 || Arch == llvm::Triple::thumb
384 || Arch == llvm::Triple::thumbeb) {
385 // Width of wchar_t in bytes
386 uint64_t WCharWidth =
387 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
388 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
389
390 // The minimum width of an enum in bytes
391 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
392 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
393 }
394
Stephen Hines176edba2014-12-01 14:53:08 -0800395 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
396 llvm::PICLevel::Level PL = llvm::PICLevel::Default;
397 switch (PLevel) {
398 case 0: break;
399 case 1: PL = llvm::PICLevel::Small; break;
400 case 2: PL = llvm::PICLevel::Large; break;
401 default: llvm_unreachable("Invalid PIC Level");
402 }
403
404 getModule().setPICLevel(PL);
405 }
406
John McCallb2593832010-09-16 06:16:50 +0000407 SimplifyPersonality();
408
John McCall744016d2010-07-06 23:57:41 +0000409 if (getCodeGenOpts().EmitDeclMetadata)
410 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000411
412 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000413 EmitCoverageFile();
Devang Patelf391dbe2011-08-16 20:58:22 +0000414
415 if (DebugInfo)
416 DebugInfo->finalize();
Rafael Espindola9686f122013-10-16 19:28:50 +0000417
418 EmitVersionIdentMetadata();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700419
420 EmitTargetMetadata();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000421}
422
Devang Patele80d5672011-03-23 16:29:39 +0000423void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
424 // Make sure that this type is translated.
425 Types.UpdateCompletedType(TD);
Devang Patele80d5672011-03-23 16:29:39 +0000426}
427
Dan Gohman3d5aff52010-10-14 23:06:10 +0000428llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
429 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700430 return nullptr;
Dan Gohman3d5aff52010-10-14 23:06:10 +0000431 return TBAA->getTBAAInfo(QTy);
432}
433
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000434llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
435 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700436 return nullptr;
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000437 return TBAA->getTBAAInfoForVTablePtr();
438}
439
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000440llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
441 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700442 return nullptr;
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000443 return TBAA->getTBAAStructInfo(QTy);
444}
445
Manman Renb37a73d2013-04-04 21:53:22 +0000446llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
447 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700448 return nullptr;
Manman Renb37a73d2013-04-04 21:53:22 +0000449 return TBAA->getTBAAStructTypeInfo(QTy);
450}
451
452llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
453 llvm::MDNode *AccessN,
454 uint64_t O) {
455 if (!TBAA)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700456 return nullptr;
Manman Renb37a73d2013-04-04 21:53:22 +0000457 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
458}
459
Manman Renfeba9f22013-10-08 00:08:49 +0000460/// Decorate the instruction with a TBAA tag. For both scalar TBAA
461/// and struct-path aware TBAA, the tag has the same format:
462/// base type, access type and offset.
Manman Renca835182013-04-11 23:02:56 +0000463/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Dan Gohman3d5aff52010-10-14 23:06:10 +0000464void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
Manman Renca835182013-04-11 23:02:56 +0000465 llvm::MDNode *TBAAInfo,
466 bool ConvertTypeToTag) {
Manman Renfeba9f22013-10-08 00:08:49 +0000467 if (ConvertTypeToTag && TBAA)
Manman Renca835182013-04-11 23:02:56 +0000468 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
469 TBAA->getTBAAScalarTagInfo(TBAAInfo));
470 else
471 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman3d5aff52010-10-14 23:06:10 +0000472}
473
Stephen Hines651f13c2014-04-23 16:59:28 -0700474void CodeGenModule::Error(SourceLocation loc, StringRef message) {
475 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
476 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall32096692011-03-18 02:56:14 +0000477}
478
Daniel Dunbar488e9932008-08-16 00:56:44 +0000479/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000480/// specified stmt yet.
David Blaikie0a1c8622013-08-19 21:02:26 +0000481void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikied6471f72011-09-25 23:23:43 +0000482 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000483 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000484 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000485 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
486 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000487}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000488
Daniel Dunbar488e9932008-08-16 00:56:44 +0000489/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000490/// specified decl yet.
David Blaikie0a1c8622013-08-19 21:02:26 +0000491void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikied6471f72011-09-25 23:23:43 +0000492 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000493 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000494 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000495 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000496}
497
John McCallbc8d40d2011-06-24 21:55:10 +0000498llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
499 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
500}
501
Mike Stump1eb44332009-09-09 15:08:12 +0000502void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000503 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000504 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000505 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000506 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000507 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000508 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000509
John McCallaf146032010-10-30 11:50:40 +0000510 // Set visibility for definitions.
Rafael Espindola2beda122013-02-27 02:15:29 +0000511 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindolaf127eb82013-02-27 02:56:45 +0000512 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
513 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000514}
515
Hans Wennborgde981f32012-06-28 08:01:44 +0000516static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
517 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
518 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
519 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
520 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
521 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
522}
523
524static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
525 CodeGenOptions::TLSModel M) {
526 switch (M) {
527 case CodeGenOptions::GeneralDynamicTLSModel:
528 return llvm::GlobalVariable::GeneralDynamicTLSModel;
529 case CodeGenOptions::LocalDynamicTLSModel:
530 return llvm::GlobalVariable::LocalDynamicTLSModel;
531 case CodeGenOptions::InitialExecTLSModel:
532 return llvm::GlobalVariable::InitialExecTLSModel;
533 case CodeGenOptions::LocalExecTLSModel:
534 return llvm::GlobalVariable::LocalExecTLSModel;
535 }
536 llvm_unreachable("Invalid TLS model!");
537}
538
Stephen Hines176edba2014-12-01 14:53:08 -0800539void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
Richard Smith38afbc72013-04-13 02:43:54 +0000540 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgde981f32012-06-28 08:01:44 +0000541
Stephen Hines176edba2014-12-01 14:53:08 -0800542 llvm::GlobalValue::ThreadLocalMode TLM;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000543 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgde981f32012-06-28 08:01:44 +0000544
545 // Override the TLS model if it is explicitly specified.
Stephen Hines651f13c2014-04-23 16:59:28 -0700546 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgde981f32012-06-28 08:01:44 +0000547 TLM = GetLLVMTLSModel(Attr->getModel());
548 }
549
550 GV->setThreadLocalMode(TLM);
551}
552
Chris Lattner5f9e2722011-07-23 10:55:15 +0000553StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700554 StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
555 if (!FoundStr.empty())
556 return FoundStr;
557
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700558 const auto *ND = cast<NamedDecl>(GD.getDecl());
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700559 SmallString<256> Buffer;
560 StringRef Str;
561 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
562 llvm::raw_svector_ostream Out(Buffer);
563 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
564 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
565 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
566 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
567 else
568 getCXXABI().getMangleContext().mangleName(ND, Out);
569 Str = Out.str();
570 } else {
Anders Carlsson793a9902010-06-22 16:05:32 +0000571 IdentifierInfo *II = ND->getIdentifier();
572 assert(II && "Attempt to mangle unnamed decl.");
Anders Carlsson793a9902010-06-22 16:05:32 +0000573 Str = II->getName();
Anders Carlsson793a9902010-06-22 16:05:32 +0000574 }
Anders Carlsson793a9902010-06-22 16:05:32 +0000575
Stephen Hines176edba2014-12-01 14:53:08 -0800576 // Keep the first result in the case of a mangling collision.
577 auto Result = Manglings.insert(std::make_pair(Str, GD));
578 return FoundStr = Result.first->first();
Anders Carlsson793a9902010-06-22 16:05:32 +0000579}
580
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700581StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
582 const BlockDecl *BD) {
Peter Collingbourne14110472011-01-13 18:57:25 +0000583 MangleContext &MangleCtx = getCXXABI().getMangleContext();
584 const Decl *D = GD.getDecl();
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700585
586 SmallString<256> Buffer;
587 llvm::raw_svector_ostream Out(Buffer);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700588 if (!D)
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000589 MangleCtx.mangleGlobalBlock(BD,
590 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700591 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000592 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700593 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000594 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000595 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000596 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700597
Stephen Hines176edba2014-12-01 14:53:08 -0800598 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
599 return Result.first->first();
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000600}
601
Chris Lattner5f9e2722011-07-23 10:55:15 +0000602llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCallf746aa62010-03-19 23:29:14 +0000603 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000604}
605
Chris Lattner6d397602008-03-14 17:18:18 +0000606/// AddGlobalCtor - Add a function to the list that will be called before
607/// main() runs.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700608void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
609 llvm::Constant *AssociatedData) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000610 // FIXME: Type coercion of void()* types.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700611 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
Chris Lattner6d397602008-03-14 17:18:18 +0000612}
613
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000614/// AddGlobalDtor - Add a function to the list that will be called
615/// when the module is unloaded.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700616void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000617 // FIXME: Type coercion of void()* types.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700618 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000619}
620
621void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
622 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000623 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000624 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000625
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700626 // Get the type of a ctor entry, { i32, void ()*, i8* }.
627 llvm::StructType *CtorStructTy = llvm::StructType::get(
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700628 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
Chris Lattner6d397602008-03-14 17:18:18 +0000629
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000630 // Construct the constructor and destructor arrays.
Chris Lattner0b239712012-02-06 22:16:34 +0000631 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000632 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner0b239712012-02-06 22:16:34 +0000633 llvm::Constant *S[] = {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700634 llvm::ConstantInt::get(Int32Ty, I->Priority, false),
635 llvm::ConstantExpr::getBitCast(I->Initializer, CtorPFTy),
636 (I->AssociatedData
637 ? llvm::ConstantExpr::getBitCast(I->AssociatedData, VoidPtrTy)
638 : llvm::Constant::getNullValue(VoidPtrTy))
Chris Lattner0b239712012-02-06 22:16:34 +0000639 };
Owen Anderson08e25242009-07-27 22:29:56 +0000640 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000641 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000642
643 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000644 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000645 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000646 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000647 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000648 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000649 }
Chris Lattner6d397602008-03-14 17:18:18 +0000650}
651
John McCalld46f9852010-02-19 01:32:20 +0000652llvm::GlobalValue::LinkageTypes
Peter Collingbourne144a31f2013-06-05 17:49:37 +0000653CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700654 const auto *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknera4130ba2013-07-22 13:51:44 +0000655
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000656 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000657
Stephen Hines651f13c2014-04-23 16:59:28 -0700658 if (isa<CXXDestructorDecl>(D) &&
659 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700660 GD.getDtorType())) {
661 // Destructor variants in the Microsoft C++ ABI are always internal or
662 // linkonce_odr thunks emitted on an as-needed basis.
663 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
664 : llvm::GlobalValue::LinkOnceODRLinkage;
665 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700666
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700667 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
John McCalld46f9852010-02-19 01:32:20 +0000668}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000669
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700670void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
671 llvm::Function *F) {
672 setNonAliasAttributes(D, F);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000673}
674
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000675void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000676 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000677 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000678 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000679 AttributeListType AttributeList;
Bill Wendling94236e72013-02-22 00:13:35 +0000680 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling785b7782012-12-07 23:17:26 +0000681 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000682 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000683}
684
John McCalld1e40d52011-10-02 01:16:38 +0000685/// Determines whether the language options require us to model
686/// unwind exceptions. We treat -fexceptions as mandating this
687/// except under the fragile ObjC ABI with only ObjC exceptions
688/// enabled. This means, for example, that C with -fexceptions
689/// enables this.
David Blaikie4e4d0842012-03-11 07:00:24 +0000690static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCalld1e40d52011-10-02 01:16:38 +0000691 // If exceptions are completely disabled, obviously this is false.
David Blaikie4e4d0842012-03-11 07:00:24 +0000692 if (!LangOpts.Exceptions) return false;
John McCalld1e40d52011-10-02 01:16:38 +0000693
694 // If C++ exceptions are enabled, this is true.
David Blaikie4e4d0842012-03-11 07:00:24 +0000695 if (LangOpts.CXXExceptions) return true;
John McCalld1e40d52011-10-02 01:16:38 +0000696
697 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikie4e4d0842012-03-11 07:00:24 +0000698 if (LangOpts.ObjCExceptions) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000699 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCalld1e40d52011-10-02 01:16:38 +0000700 }
701
702 return true;
703}
704
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000705void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
706 llvm::Function *F) {
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000707 llvm::AttrBuilder B;
708
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000709 if (CodeGenOpts.UnwindTables)
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000710 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000711
David Blaikie4e4d0842012-03-11 07:00:24 +0000712 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000713 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000714
Eli Friedman2873aee2011-08-22 23:55:33 +0000715 if (D->hasAttr<NakedAttr>()) {
716 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000717 B.addAttribute(llvm::Attribute::Naked);
718 B.addAttribute(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -0700719 } else if (D->hasAttr<NoDuplicateAttr>()) {
720 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000721 } else if (D->hasAttr<NoInlineAttr>()) {
722 B.addAttribute(llvm::Attribute::NoInline);
Stephen Hines651f13c2014-04-23 16:59:28 -0700723 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000724 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
725 llvm::Attribute::NoInline)) {
726 // (noinline wins over always_inline, and we can't specify both in IR)
727 B.addAttribute(llvm::Attribute::AlwaysInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000728 }
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000729
Diego Novillod27e5cb2013-05-24 20:18:15 +0000730 if (D->hasAttr<ColdAttr>()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700731 if (!D->hasAttr<OptimizeNoneAttr>())
732 B.addAttribute(llvm::Attribute::OptimizeForSize);
Diego Novillod27e5cb2013-05-24 20:18:15 +0000733 B.addAttribute(llvm::Attribute::Cold);
734 }
Benjamin Krameree409a92012-05-12 21:10:52 +0000735
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000736 if (D->hasAttr<MinSizeAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000737 B.addAttribute(llvm::Attribute::MinSize);
Richard Smithef4d5ce2012-09-28 22:46:07 +0000738
David Blaikie4e4d0842012-03-11 07:00:24 +0000739 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000740 B.addAttribute(llvm::Attribute::StackProtect);
Stephen Hines651f13c2014-04-23 16:59:28 -0700741 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
742 B.addAttribute(llvm::Attribute::StackProtectStrong);
David Blaikie4e4d0842012-03-11 07:00:24 +0000743 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000744 B.addAttribute(llvm::Attribute::StackProtectReq);
Will Dietz4f45bc02013-01-18 11:30:38 +0000745
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000746 // Add sanitizer attributes if function is not blacklisted.
Stephen Hines176edba2014-12-01 14:53:08 -0800747 if (!isInSanitizerBlacklist(F, D->getLocation())) {
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000748 // When AddressSanitizer is enabled, set SanitizeAddress attribute
749 // unless __attribute__((no_sanitize_address)) is used.
Stephen Hines176edba2014-12-01 14:53:08 -0800750 if (LangOpts.Sanitize.has(SanitizerKind::Address) &&
751 !D->hasAttr<NoSanitizeAddressAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000752 B.addAttribute(llvm::Attribute::SanitizeAddress);
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000753 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
Stephen Hines176edba2014-12-01 14:53:08 -0800754 if (LangOpts.Sanitize.has(SanitizerKind::Thread) &&
755 !D->hasAttr<NoSanitizeThreadAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000756 B.addAttribute(llvm::Attribute::SanitizeThread);
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000757 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
Stephen Hines176edba2014-12-01 14:53:08 -0800758 if (LangOpts.Sanitize.has(SanitizerKind::Memory) &&
759 !D->hasAttr<NoSanitizeMemoryAttr>())
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000760 B.addAttribute(llvm::Attribute::SanitizeMemory);
Alexey Samsonov7e73f942013-03-06 10:54:18 +0000761 }
Alexander Potapenko89651ea2012-02-02 11:49:28 +0000762
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000763 F->addAttributes(llvm::AttributeSet::FunctionIndex,
764 llvm::AttributeSet::get(
765 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
766
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700767 if (D->hasAttr<OptimizeNoneAttr>()) {
768 // OptimizeNone implies noinline; we should not be inlining such functions.
769 F->addFnAttr(llvm::Attribute::OptimizeNone);
770 F->addFnAttr(llvm::Attribute::NoInline);
771
772 // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
773 assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
774 "OptimizeNone and OptimizeForSize on same function!");
775 assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
776 "OptimizeNone and MinSize on same function!");
777 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
778 "OptimizeNone and AlwaysInline on same function!");
779
780 // Attribute 'inlinehint' has no effect on 'optnone' functions.
781 // Explicitly remove it from the set of function attributes.
782 F->removeFnAttr(llvm::Attribute::InlineHint);
783 }
784
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000785 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
786 F->setUnnamedAddr(true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700787 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
Benjamin Kramer06a9d042013-05-11 12:45:37 +0000788 if (MD->isVirtual())
789 F->setUnnamedAddr(true);
790
Sean Huntcf807c42010-08-18 23:23:40 +0000791 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
792 if (alignment)
793 F->setAlignment(alignment);
794
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000795 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000796 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
797 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000798}
799
Mike Stump1eb44332009-09-09 15:08:12 +0000800void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000801 llvm::GlobalValue *GV) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700802 if (const auto *ND = dyn_cast<NamedDecl>(D))
Anders Carlsson934176f2011-01-29 19:41:00 +0000803 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000804 else
805 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000806
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000807 if (D->hasAttr<UsedAttr>())
Stephen Hines651f13c2014-04-23 16:59:28 -0700808 addUsedGlobal(GV);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700809}
810
Stephen Hines176edba2014-12-01 14:53:08 -0800811void CodeGenModule::setAliasAttributes(const Decl *D,
812 llvm::GlobalValue *GV) {
813 SetCommonAttributes(D, GV);
814
815 // Process the dllexport attribute based on whether the original definition
816 // (not necessarily the aliasee) was exported.
817 if (D->hasAttr<DLLExportAttr>())
818 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
819}
820
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700821void CodeGenModule::setNonAliasAttributes(const Decl *D,
822 llvm::GlobalObject *GO) {
823 SetCommonAttributes(D, GO);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000824
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000825 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700826 GO->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000827
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700828 getTargetCodeGenInfo().SetTargetAttributes(D, GO, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000829}
830
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000831void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
832 llvm::Function *F,
833 const CGFunctionInfo &FI) {
834 SetLLVMFunctionAttributes(D, FI, F);
835 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000836
837 F->setLinkage(llvm::Function::InternalLinkage);
838
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700839 setNonAliasAttributes(D, F);
840}
841
842static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
843 const NamedDecl *ND) {
844 // Set linkage and visibility in case we never see a definition.
845 LinkageInfo LV = ND->getLinkageAndVisibility();
846 if (LV.getLinkage() != ExternalLinkage) {
847 // Don't set internal linkage on declarations.
848 } else {
849 if (ND->hasAttr<DLLImportAttr>()) {
850 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
851 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
852 } else if (ND->hasAttr<DLLExportAttr>()) {
853 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
854 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
855 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
856 // "extern_weak" is overloaded in LLVM; we probably should have
857 // separate linkage types for this.
858 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
859 }
860
861 // Set visibility on a declaration only if it's explicit.
862 if (LV.isVisibilityExplicit())
863 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
864 }
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000865}
866
Stephen Hines176edba2014-12-01 14:53:08 -0800867void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
868 bool IsIncompleteFunction,
869 bool IsThunk) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000870 if (unsigned IID = F->getIntrinsicID()) {
871 // If this is an intrinsic function, set the function's attributes
872 // to the intrinsic's attributes.
Bill Wendling50e6b182012-10-15 04:47:45 +0000873 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
874 (llvm::Intrinsic::ID)IID));
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000875 return;
876 }
877
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700878 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000879
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000880 if (!IsIncompleteFunction)
John McCallde5d3c72012-02-17 03:33:10 +0000881 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Stephen Hines651f13c2014-04-23 16:59:28 -0700883 // Add the Returned attribute for "this", except for iOS 5 and earlier
884 // where substantial code, including the libstdc++ dylib, was compiled with
885 // GCC and does not actually return "this".
Stephen Hines176edba2014-12-01 14:53:08 -0800886 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700887 !(getTarget().getTriple().isiOS() &&
888 getTarget().getTriple().isOSVersionLT(6))) {
Stephen Lin3b50e8d2013-06-30 20:40:16 +0000889 assert(!F->arg_empty() &&
890 F->arg_begin()->getType()
891 ->canLosslesslyBitCastTo(F->getReturnType()) &&
892 "unexpected this return");
893 F->addAttribute(1, llvm::Attribute::Returned);
894 }
895
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000896 // Only a few attributes are set on declarations; these may later be
897 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700899 setLinkageAndVisibilityForGV(F, FD);
John McCallaf146032010-10-30 11:50:40 +0000900
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700901 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
902 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
903 // Don't dllexport/import destructor thunks.
904 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
John McCallaf146032010-10-30 11:50:40 +0000905 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000906 }
907
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000908 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000909 F->setSection(SA->getName());
Richard Smithddcff1b2013-07-21 23:12:18 +0000910
911 // A replaceable global allocation function does not act like a builtin by
912 // default, only if it is invoked by a new-expression or delete-expression.
913 if (FD->isReplaceableGlobalAllocationFunction())
914 F->addAttribute(llvm::AttributeSet::FunctionIndex,
915 llvm::Attribute::NoBuiltin);
Daniel Dunbar219df662008-09-08 23:44:31 +0000916}
917
Stephen Hines651f13c2014-04-23 16:59:28 -0700918void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000919 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000920 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000921 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000922}
923
Stephen Hines651f13c2014-04-23 16:59:28 -0700924void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
925 assert(!GV->isDeclaration() &&
926 "Only globals with definition can force usage.");
927 LLVMCompilerUsed.push_back(GV);
928}
929
930static void emitUsed(CodeGenModule &CGM, StringRef Name,
931 std::vector<llvm::WeakVH> &List) {
Daniel Dunbar02698712009-02-13 20:29:50 +0000932 // Don't create llvm.used if there is no need.
Stephen Hines651f13c2014-04-23 16:59:28 -0700933 if (List.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000934 return;
935
Stephen Hines651f13c2014-04-23 16:59:28 -0700936 // Convert List to what ConstantArray needs.
Chris Lattner0b239712012-02-06 22:16:34 +0000937 SmallVector<llvm::Constant*, 8> UsedArray;
Stephen Hines651f13c2014-04-23 16:59:28 -0700938 UsedArray.resize(List.size());
939 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000940 UsedArray[i] =
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700941 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
942 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000943 }
Mike Stump1eb44332009-09-09 15:08:12 +0000944
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000945 if (UsedArray.empty())
946 return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700947 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700949 auto *GV = new llvm::GlobalVariable(
950 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
951 llvm::ConstantArray::get(ATy, UsedArray), Name);
Daniel Dunbar02698712009-02-13 20:29:50 +0000952
953 GV->setSection("llvm.metadata");
954}
955
Stephen Hines651f13c2014-04-23 16:59:28 -0700956void CodeGenModule::emitLLVMUsed() {
957 emitUsed(*this, "llvm.used", LLVMUsed);
958 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
959}
960
Reid Kleckner3190ca92013-05-08 13:44:39 +0000961void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700962 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
Reid Kleckner3190ca92013-05-08 13:44:39 +0000963 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
964}
965
Aaron Ballmana7ff62f2013-06-04 02:07:14 +0000966void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
967 llvm::SmallString<32> Opt;
968 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700969 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Aaron Ballmana7ff62f2013-06-04 02:07:14 +0000970 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
971}
972
Reid Kleckner3190ca92013-05-08 13:44:39 +0000973void CodeGenModule::AddDependentLib(StringRef Lib) {
974 llvm::SmallString<24> Opt;
975 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700976 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
Reid Kleckner3190ca92013-05-08 13:44:39 +0000977 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
978}
979
Douglas Gregor858afb32013-01-14 20:53:57 +0000980/// \brief Add link options implied by the given module, including modules
981/// it depends on, using a postorder walk.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700982static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
983 SmallVectorImpl<llvm::Metadata *> &Metadata,
Douglas Gregor858afb32013-01-14 20:53:57 +0000984 llvm::SmallPtrSet<Module *, 16> &Visited) {
985 // Import this module's parent.
Stephen Hines176edba2014-12-01 14:53:08 -0800986 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
Reid Kleckner3190ca92013-05-08 13:44:39 +0000987 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregor858afb32013-01-14 20:53:57 +0000988 }
989
990 // Import this module's dependencies.
991 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
Stephen Hines176edba2014-12-01 14:53:08 -0800992 if (Visited.insert(Mod->Imports[I - 1]).second)
Reid Kleckner3190ca92013-05-08 13:44:39 +0000993 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregor858afb32013-01-14 20:53:57 +0000994 }
995
996 // Add linker options to link against the libraries/frameworks
997 // described by this module.
Reid Kleckner3190ca92013-05-08 13:44:39 +0000998 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregor858afb32013-01-14 20:53:57 +0000999 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Kleckner3190ca92013-05-08 13:44:39 +00001000 // Link against a framework. Frameworks are currently Darwin only, so we
1001 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregor858afb32013-01-14 20:53:57 +00001002 if (Mod->LinkLibraries[I-1].IsFramework) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001003 llvm::Metadata *Args[2] = {
1004 llvm::MDString::get(Context, "-framework"),
1005 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
Douglas Gregor858afb32013-01-14 20:53:57 +00001006
1007 Metadata.push_back(llvm::MDNode::get(Context, Args));
1008 continue;
1009 }
1010
1011 // Link against a library.
Reid Kleckner3190ca92013-05-08 13:44:39 +00001012 llvm::SmallString<24> Opt;
1013 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1014 Mod->LinkLibraries[I-1].Library, Opt);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001015 auto *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregor858afb32013-01-14 20:53:57 +00001016 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1017 }
1018}
1019
1020void CodeGenModule::EmitModuleLinkOptions() {
1021 // Collect the set of all of the modules we want to visit to emit link
1022 // options, which is essentially the imported modules and all of their
1023 // non-explicit child modules.
1024 llvm::SetVector<clang::Module *> LinkModules;
1025 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1026 SmallVector<clang::Module *, 16> Stack;
1027
1028 // Seed the stack with imported modules.
1029 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
1030 MEnd = ImportedModules.end();
1031 M != MEnd; ++M) {
Stephen Hines176edba2014-12-01 14:53:08 -08001032 if (Visited.insert(*M).second)
Douglas Gregor858afb32013-01-14 20:53:57 +00001033 Stack.push_back(*M);
1034 }
1035
1036 // Find all of the modules to import, making a little effort to prune
1037 // non-leaf modules.
1038 while (!Stack.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00001039 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregor858afb32013-01-14 20:53:57 +00001040
1041 bool AnyChildren = false;
1042
1043 // Visit the submodules of this module.
1044 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1045 SubEnd = Mod->submodule_end();
1046 Sub != SubEnd; ++Sub) {
1047 // Skip explicit children; they need to be explicitly imported to be
1048 // linked against.
1049 if ((*Sub)->IsExplicit)
1050 continue;
1051
Stephen Hines176edba2014-12-01 14:53:08 -08001052 if (Visited.insert(*Sub).second) {
Douglas Gregor858afb32013-01-14 20:53:57 +00001053 Stack.push_back(*Sub);
1054 AnyChildren = true;
1055 }
1056 }
1057
1058 // We didn't find any children, so add this module to the list of
1059 // modules to link against.
1060 if (!AnyChildren) {
1061 LinkModules.insert(Mod);
1062 }
1063 }
1064
1065 // Add link options for all of the imported modules in reverse topological
Reid Kleckner3190ca92013-05-08 13:44:39 +00001066 // order. We don't do anything to try to order import link flags with respect
1067 // to linker options inserted by things like #pragma comment().
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001068 SmallVector<llvm::Metadata *, 16> MetadataArgs;
Douglas Gregor858afb32013-01-14 20:53:57 +00001069 Visited.clear();
1070 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
1071 MEnd = LinkModules.end();
1072 M != MEnd; ++M) {
Stephen Hines176edba2014-12-01 14:53:08 -08001073 if (Visited.insert(*M).second)
Reid Kleckner3190ca92013-05-08 13:44:39 +00001074 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
Douglas Gregor858afb32013-01-14 20:53:57 +00001075 }
Daniel Dunbarf9d03c12013-01-17 01:35:06 +00001076 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Kleckner3190ca92013-05-08 13:44:39 +00001077 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregor858afb32013-01-14 20:53:57 +00001078
Daniel Dunbarf9d03c12013-01-17 01:35:06 +00001079 // Add the linker options metadata flag.
1080 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Kleckner3190ca92013-05-08 13:44:39 +00001081 llvm::MDNode::get(getLLVMContext(),
1082 LinkerOptionsMetadata));
Douglas Gregor858afb32013-01-14 20:53:57 +00001083}
1084
Daniel Dunbar02698712009-02-13 20:29:50 +00001085void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +00001086 // Emit code for any potentially referenced deferred decls. Since a
1087 // previously unused static decl may become used during the generation of code
Nick Lewyckydce67a72011-07-18 05:26:13 +00001088 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00001089
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001090 if (!DeferredVTables.empty()) {
1091 EmitDeferredVTables();
John McCalld5617ee2013-01-25 22:31:03 +00001092
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001093 // Emitting a v-table doesn't directly cause more v-tables to
1094 // become deferred, although it can cause functions to be
1095 // emitted that then need those v-tables.
1096 assert(DeferredVTables.empty());
1097 }
Rafael Espindolabbf58bb2010-03-10 02:19:29 +00001098
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001099 // Stop if we're out of both deferred v-tables and deferred declarations.
1100 if (DeferredDeclsToEmit.empty())
1101 return;
John McCalld5617ee2013-01-25 22:31:03 +00001102
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001103 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1104 // work, it will not interfere with this.
1105 std::vector<DeferredGlobal> CurDeclsToEmit;
1106 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1107
1108 for (DeferredGlobal &G : CurDeclsToEmit) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001109 GlobalDecl D = G.GD;
1110 llvm::GlobalValue *GV = G.GV;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001111 G.GV = nullptr;
Chris Lattner67b00522009-03-21 09:44:56 +00001112
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001113 assert(!GV || GV == GetGlobalValue(getMangledName(D)));
1114 if (!GV)
1115 GV = GetGlobalValue(getMangledName(D));
1116
John McCallc76702c2010-05-27 01:45:30 +00001117 // Check to see if we've already emitted this. This is necessary
1118 // for a couple of reasons: first, decls can end up in the
1119 // deferred-decls queue multiple times, and second, decls can end
1120 // up with definitions in unusual ways (e.g. by an extern inline
1121 // function acquiring a strong function redefinition). Just
1122 // ignore these cases.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001123 if (GV && !GV->isDeclaration())
John McCallc76702c2010-05-27 01:45:30 +00001124 continue;
1125
Chris Lattner67b00522009-03-21 09:44:56 +00001126 // Otherwise, emit the definition and move on to the next one.
Stephen Hines651f13c2014-04-23 16:59:28 -07001127 EmitGlobalDefinition(D, GV);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001128
1129 // If we found out that we need to emit more decls, do that recursively.
1130 // This has the advantage that the decls are emitted in a DFS and related
1131 // ones are close together, which is convenient for testing.
1132 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1133 EmitDeferred();
1134 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1135 }
Chris Lattner67b00522009-03-21 09:44:56 +00001136 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001137}
1138
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001139void CodeGenModule::EmitGlobalAnnotations() {
1140 if (Annotations.empty())
1141 return;
1142
1143 // Create a new global variable for the ConstantStruct in the Module.
1144 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1145 Annotations[0]->getType(), Annotations.size()), Annotations);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001146 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1147 llvm::GlobalValue::AppendingLinkage,
1148 Array, "llvm.global.annotations");
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001149 gv->setSection(AnnotationSection);
1150}
1151
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001152llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramer471b52a2013-11-10 16:55:11 +00001153 llvm::Constant *&AStr = AnnotationStrings[Str];
1154 if (AStr)
1155 return AStr;
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001156
1157 // Not found yet, create a new global.
Chris Lattner94010692012-02-05 02:30:40 +00001158 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001159 auto *gv =
1160 new llvm::GlobalVariable(getModule(), s->getType(), true,
1161 llvm::GlobalValue::PrivateLinkage, s, ".str");
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001162 gv->setSection(AnnotationSection);
1163 gv->setUnnamedAddr(true);
Benjamin Kramer471b52a2013-11-10 16:55:11 +00001164 AStr = gv;
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001165 return gv;
1166}
1167
1168llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1169 SourceManager &SM = getContext().getSourceManager();
1170 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1171 if (PLoc.isValid())
1172 return EmitAnnotationString(PLoc.getFilename());
1173 return EmitAnnotationString(SM.getBufferName(Loc));
1174}
1175
1176llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1177 SourceManager &SM = getContext().getSourceManager();
1178 PresumedLoc PLoc = SM.getPresumedLoc(L);
1179 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1180 SM.getExpansionLineNumber(L);
1181 return llvm::ConstantInt::get(Int32Ty, LineNo);
1182}
1183
Mike Stump1eb44332009-09-09 15:08:12 +00001184llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001185 const AnnotateAttr *AA,
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001186 SourceLocation L) {
1187 // Get the globals for file name, annotation, and the line number.
1188 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1189 *UnitGV = EmitAnnotationUnit(L),
1190 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001191
Daniel Dunbar57d5cee2009-04-14 22:41:13 +00001192 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001193 llvm::Constant *Fields[4] = {
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001194 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1195 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1196 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1197 LineNoCst
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001198 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001199 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001200}
1201
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001202void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1203 llvm::GlobalValue *GV) {
1204 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1205 // Get the struct elements for these annotations.
Stephen Hines651f13c2014-04-23 16:59:28 -07001206 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1207 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001208}
1209
Stephen Hines176edba2014-12-01 14:53:08 -08001210bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1211 SourceLocation Loc) const {
1212 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1213 // Blacklist by function name.
1214 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1215 return true;
1216 // Blacklist by location.
1217 if (!Loc.isInvalid())
1218 return SanitizerBL.isBlacklistedLocation(Loc);
1219 // If location is unknown, this may be a compiler-generated function. Assume
1220 // it's located in the main file.
1221 auto &SM = Context.getSourceManager();
1222 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1223 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1224 }
1225 return false;
1226}
1227
1228bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1229 SourceLocation Loc, QualType Ty,
1230 StringRef Category) const {
1231 // For now globals can be blacklisted only in ASan.
1232 if (!LangOpts.Sanitize.has(SanitizerKind::Address))
1233 return false;
1234 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1235 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1236 return true;
1237 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1238 return true;
1239 // Check global type.
1240 if (!Ty.isNull()) {
1241 // Drill down the array types: if global variable of a fixed type is
1242 // blacklisted, we also don't instrument arrays of them.
1243 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1244 Ty = AT->getElementType();
1245 Ty = Ty.getCanonicalType().getUnqualifiedType();
1246 // We allow to blacklist only record types (classes, structs etc.)
1247 if (Ty->isRecordType()) {
1248 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1249 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1250 return true;
1251 }
1252 }
1253 return false;
1254}
1255
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001256bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +00001257 // Never defer when EmitAllDecls is specified.
David Blaikie4e4d0842012-03-11 07:00:24 +00001258 if (LangOpts.EmitAllDecls)
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001259 return true;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001260
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001261 return getContext().DeclMustBeEmitted(Global);
1262}
1263
1264bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1265 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1266 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1267 // Implicit template instantiations may change linkage if they are later
1268 // explicitly instantiated, so they should not be emitted eagerly.
1269 return false;
1270
1271 return true;
Daniel Dunbar73241df2009-02-13 21:18:01 +00001272}
1273
Nico Weberc5f80462012-10-11 10:13:44 +00001274llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1275 const CXXUuidofExpr* E) {
1276 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1277 // well-formed.
David Majnemerc80eb462013-08-13 06:32:20 +00001278 StringRef Uuid = E->getUuidAsStringRef(Context);
David Majnemerc8fe0112013-08-09 08:35:59 +00001279 std::string Name = "_GUID_" + Uuid.lower();
1280 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Weberc5f80462012-10-11 10:13:44 +00001281
1282 // Look for an existing global.
1283 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1284 return GV;
1285
Stephen Hines176edba2014-12-01 14:53:08 -08001286 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
Nico Weberc5f80462012-10-11 10:13:44 +00001287 assert(Init && "failed to initialize as constant");
1288
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001289 auto *GV = new llvm::GlobalVariable(
David Majnemer8effeda2013-08-15 19:59:14 +00001290 getModule(), Init->getType(),
Reid Klecknerdc1ac5e2013-09-03 21:49:32 +00001291 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001292 if (supportsCOMDAT())
1293 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Nico Weberc5f80462012-10-11 10:13:44 +00001294 return GV;
1295}
1296
Rafael Espindola6a836702010-03-04 18:17:24 +00001297llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1298 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1299 assert(AA && "No alias?");
1300
Chris Lattner2acc6e32011-07-18 04:24:23 +00001301 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola6a836702010-03-04 18:17:24 +00001302
Rafael Espindola6a836702010-03-04 18:17:24 +00001303 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +00001304 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001305 if (Entry) {
1306 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1307 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1308 }
Rafael Espindola6a836702010-03-04 18:17:24 +00001309
1310 llvm::Constant *Aliasee;
1311 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00001312 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1313 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001314 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +00001315 else
John McCallf746aa62010-03-19 23:29:14 +00001316 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001317 llvm::PointerType::getUnqual(DeclTy),
1318 nullptr);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001319
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001320 auto *F = cast<llvm::GlobalValue>(Aliasee);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001321 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1322 WeakRefReferences.insert(F);
Rafael Espindola6a836702010-03-04 18:17:24 +00001323
1324 return Aliasee;
1325}
1326
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001327void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001328 const auto *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Rafael Espindola6a836702010-03-04 18:17:24 +00001330 // Weak references don't produce any output by themselves.
1331 if (Global->hasAttr<WeakRefAttr>())
1332 return;
1333
Chris Lattnerbd532712009-03-22 21:47:11 +00001334 // If this is an alias definition (which otherwise looks like a declaration)
1335 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001336 if (Global->hasAttr<AliasAttr>())
Rafael Espindola87017a72013-10-22 14:23:09 +00001337 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +00001338
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001339 // If this is CUDA, be selective about which declarations we emit.
David Blaikie4e4d0842012-03-11 07:00:24 +00001340 if (LangOpts.CUDA) {
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001341 if (CodeGenOpts.CUDAIsDevice) {
1342 if (!Global->hasAttr<CUDADeviceAttr>() &&
1343 !Global->hasAttr<CUDAGlobalAttr>() &&
1344 !Global->hasAttr<CUDAConstantAttr>() &&
1345 !Global->hasAttr<CUDASharedAttr>())
1346 return;
1347 } else {
1348 if (!Global->hasAttr<CUDAHostAttr>() && (
1349 Global->hasAttr<CUDADeviceAttr>() ||
1350 Global->hasAttr<CUDAConstantAttr>() ||
1351 Global->hasAttr<CUDASharedAttr>()))
1352 return;
1353 }
1354 }
1355
Chris Lattner67b00522009-03-21 09:44:56 +00001356 // Ignore declarations, they will be emitted on their first use.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001357 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +00001358 // Forward declarations are emitted lazily on first use.
Nick Lewyckydce67a72011-07-18 05:26:13 +00001359 if (!FD->doesThisDeclarationHaveABody()) {
1360 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1361 return;
1362
Chris Lattner5f9e2722011-07-23 10:55:15 +00001363 StringRef MangledName = getMangledName(GD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001364
1365 // Compute the function info and LLVM type.
1366 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1367 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1368
1369 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1370 /*DontDefer=*/false);
Daniel Dunbar73241df2009-02-13 21:18:01 +00001371 return;
Nick Lewyckydce67a72011-07-18 05:26:13 +00001372 }
Daniel Dunbar02698712009-02-13 20:29:50 +00001373 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001374 const auto *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001375 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1376
Stephen Hines176edba2014-12-01 14:53:08 -08001377 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1378 !Context.isMSStaticDataMemberInlineDefinition(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00001379 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001380 }
1381
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001382 // Defer code generation to first use when possible, e.g. if this is an inline
1383 // function. If the global must always be emitted, do it eagerly if possible
1384 // to benefit from cache locality.
1385 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
Chris Lattner4357a822010-04-13 17:39:09 +00001386 // Emit the definition if it can't be deferred.
1387 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001388 return;
1389 }
John McCallbf40cb52010-07-15 23:40:35 +00001390
1391 // If we're deferring emission of a C++ variable with an
1392 // initializer, remember the order in which it appeared in the file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001393 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCallbf40cb52010-07-15 23:40:35 +00001394 cast<VarDecl>(Global)->hasInit()) {
1395 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001396 CXXGlobalInits.push_back(nullptr);
John McCallbf40cb52010-07-15 23:40:35 +00001397 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001398
Chris Lattner5f9e2722011-07-23 10:55:15 +00001399 StringRef MangledName = getMangledName(GD);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001400 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1401 // The value has already been used and should therefore be emitted.
Stephen Hines651f13c2014-04-23 16:59:28 -07001402 addDeferredDeclToEmit(GV, GD);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001403 } else if (MustBeEmitted(Global)) {
1404 // The value must be emitted, but cannot be emitted eagerly.
1405 assert(!MayBeEmittedEagerly(Global));
1406 addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1407 } else {
Chris Lattner4357a822010-04-13 17:39:09 +00001408 // Otherwise, remember that we saw a deferred decl with this name. The
1409 // first use of the mangled name will cause it to move into
1410 // DeferredDeclsToEmit.
1411 DeferredDecls[MangledName] = GD;
1412 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001413}
1414
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001415namespace {
1416 struct FunctionIsDirectlyRecursive :
1417 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1418 const StringRef Name;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001419 const Builtin::Context &BI;
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001420 bool Result;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001421 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1422 Name(N), BI(C), Result(false) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001423 }
1424 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1425
1426 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001427 const FunctionDecl *FD = E->getDirectCallee();
1428 if (!FD)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001429 return true;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001430 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1431 if (Attr && Name == Attr->getLabel()) {
1432 Result = true;
1433 return false;
1434 }
1435 unsigned BuiltinID = FD->getBuiltinID();
1436 if (!BuiltinID)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001437 return true;
Nick Lewyckyf6b56372012-01-18 03:41:19 +00001438 StringRef BuiltinName = BI.GetName(BuiltinID);
1439 if (BuiltinName.startswith("__builtin_") &&
1440 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001441 Result = true;
1442 return false;
1443 }
1444 return true;
1445 }
1446 };
1447}
1448
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001449// isTriviallyRecursive - Check if this function calls another
1450// decl that, because of the asm attribute or the other decl being a builtin,
1451// ends up pointing to itself.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001452bool
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001453CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1454 StringRef Name;
1455 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky22afacc2012-01-18 01:50:13 +00001456 // asm labels are a special kind of mangling we have to support.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001457 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1458 if (!Attr)
1459 return false;
1460 Name = Attr->getLabel();
1461 } else {
1462 Name = FD->getName();
1463 }
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001464
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001465 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1466 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001467 return Walker.Result;
1468}
1469
1470bool
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001471CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1472 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001473 return true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001474 const auto *F = cast<FunctionDecl>(GD.getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07001475 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001476 return false;
1477 // PR9614. Avoid cases where the source code is lying to us. An available
1478 // externally function should have an equivalent function somewhere else,
1479 // but a function that calls itself is clearly not equivalent to the real
1480 // implementation.
1481 // This happens in glibc's btowc and in some configure checks.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001482 return !isTriviallyRecursive(F);
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001483}
1484
Adrian Prantl0a050f72013-05-09 23:16:27 +00001485/// If the type for the method's class was generated by
1486/// CGDebugInfo::createContextChain(), the cache contains only a
1487/// limited DIType without any declarations. Since EmitFunctionStart()
1488/// needs to find the canonical declaration for each method, we need
1489/// to construct the complete type prior to emitting the method.
1490void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1491 if (!D->isInstance())
1492 return;
1493
1494 if (CGDebugInfo *DI = getModuleDebugInfo())
1495 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001496 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
Adrian Prantl0a050f72013-05-09 23:16:27 +00001497 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1498 }
1499}
1500
Stephen Hines651f13c2014-04-23 16:59:28 -07001501void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001502 const auto *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Dan Gohmancb421fa2010-04-19 16:39:44 +00001504 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +00001505 Context.getSourceManager(),
1506 "Generating code for declaration");
1507
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001508 if (isa<FunctionDecl>(D)) {
Douglas Gregor44eac332010-07-13 06:02:28 +00001509 // At -O0, don't generate IR for functions with available_externally
1510 // linkage.
Peter Collingbourne144a31f2013-06-05 17:49:37 +00001511 if (!shouldEmitFunction(GD))
Douglas Gregor44eac332010-07-13 06:02:28 +00001512 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +00001513
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001514 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
Adrian Prantl0a050f72013-05-09 23:16:27 +00001515 CompleteDIClassType(Method);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001516 // Make sure to emit the definition(s) before we emit the thunks.
1517 // This is necessary for the generation of certain thunks.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001518 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
Stephen Hines176edba2014-12-01 14:53:08 -08001519 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001520 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
Stephen Hines176edba2014-12-01 14:53:08 -08001521 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001522 else
Stephen Hines651f13c2014-04-23 16:59:28 -07001523 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001524
Douglas Gregor44eac332010-07-13 06:02:28 +00001525 if (Method->isVirtual())
1526 getVTables().EmitThunks(GD);
1527
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001528 return;
Douglas Gregor44eac332010-07-13 06:02:28 +00001529 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001530
Stephen Hines651f13c2014-04-23 16:59:28 -07001531 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregor44eac332010-07-13 06:02:28 +00001532 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001533
1534 if (const auto *VD = dyn_cast<VarDecl>(D))
Chris Lattnerb5e81562010-04-13 17:57:11 +00001535 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +00001536
David Blaikieb219cfc2011-09-23 05:06:16 +00001537 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001538}
1539
Chris Lattner74391b42009-03-22 21:03:39 +00001540/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1541/// module, create and return an llvm Function with the specified type. If there
1542/// is something in the module with the specified name, return it potentially
1543/// bitcasted to the right type.
1544///
1545/// If D is non-null, it specifies a decl that correspond to this. This is used
1546/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001547llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001548CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001549 llvm::Type *Ty,
Reid Kleckner73701ea2013-07-22 13:07:10 +00001550 GlobalDecl GD, bool ForVTable,
Stephen Hines176edba2014-12-01 14:53:08 -08001551 bool DontDefer, bool IsThunk,
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001552 llvm::AttributeSet ExtraAttrs) {
Reid Kleckner73701ea2013-07-22 13:07:10 +00001553 const Decl *D = GD.getDecl();
1554
Chris Lattner0558e792009-03-21 09:25:43 +00001555 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001556 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +00001557 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001558 if (WeakRefReferences.erase(Entry)) {
Reid Kleckner73701ea2013-07-22 13:07:10 +00001559 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola6a836702010-03-04 18:17:24 +00001560 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001561 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001562 }
1563
Stephen Hines176edba2014-12-01 14:53:08 -08001564 // Handle dropped DLL attributes.
1565 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1566 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1567
Chris Lattner0558e792009-03-21 09:25:43 +00001568 if (Entry->getType()->getElementType() == Ty)
1569 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001570
Chris Lattner0558e792009-03-21 09:25:43 +00001571 // Make sure the result is of the correct type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001572 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattner0558e792009-03-21 09:25:43 +00001573 }
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Eli Friedman654ad402009-11-09 05:07:37 +00001575 // This function doesn't have a complete type (for example, the return
1576 // type is an incomplete struct). Use a fake type instead, and make
1577 // sure not to try to set attributes.
1578 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +00001579
Chris Lattner2acc6e32011-07-18 04:24:23 +00001580 llvm::FunctionType *FTy;
John McCall784f2112010-04-28 00:00:30 +00001581 if (isa<llvm::FunctionType>(Ty)) {
1582 FTy = cast<llvm::FunctionType>(Ty);
1583 } else {
John McCall0774cb82011-05-15 01:53:33 +00001584 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +00001585 IsIncompleteFunction = true;
1586 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001587
John McCall784f2112010-04-28 00:00:30 +00001588 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +00001589 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001590 MangledName, &getModule());
1591 assert(F->getName() == MangledName && "name was uniqued!");
Reid Kleckner73701ea2013-07-22 13:07:10 +00001592 if (D)
Stephen Hines176edba2014-12-01 14:53:08 -08001593 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001594 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1595 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling909b6de2013-01-23 00:21:06 +00001596 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1597 llvm::AttributeSet::get(VMContext,
1598 llvm::AttributeSet::FunctionIndex,
1599 B));
1600 }
Eli Friedman654ad402009-11-09 05:07:37 +00001601
Stephen Hines651f13c2014-04-23 16:59:28 -07001602 if (!DontDefer) {
1603 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1604 // each other bottoming out with the base dtor. Therefore we emit non-base
1605 // dtors on usage, even if there is no dtor definition in the TU.
1606 if (D && isa<CXXDestructorDecl>(D) &&
1607 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1608 GD.getDtorType()))
1609 addDeferredDeclToEmit(F, GD);
John McCallbfdcdc82010-12-15 04:00:32 +00001610
Stephen Hines651f13c2014-04-23 16:59:28 -07001611 // This is the first use or definition of a mangled name. If there is a
1612 // deferred decl with this name, remember that we need to emit it at the end
1613 // of the file.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001614 auto DDI = DeferredDecls.find(MangledName);
Stephen Hines651f13c2014-04-23 16:59:28 -07001615 if (DDI != DeferredDecls.end()) {
1616 // Move the potentially referenced deferred decl to the
1617 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1618 // don't need it anymore).
1619 addDeferredDeclToEmit(F, DDI->second);
1620 DeferredDecls.erase(DDI);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001621
Stephen Hines651f13c2014-04-23 16:59:28 -07001622 // Otherwise, if this is a sized deallocation function, emit a weak
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001623 // definition for it at the end of the translation unit (if allowed),
1624 // unless the sized deallocation function is aliased.
1625 } else if (D &&
1626 cast<FunctionDecl>(D)
1627 ->getCorrespondingUnsizedGlobalDeallocationFunction() &&
1628 getLangOpts().DefineSizedDeallocation &&
1629 !D->hasAttr<AliasAttr>()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001630 addDeferredDeclToEmit(F, GD);
1631
1632 // Otherwise, there are cases we have to worry about where we're
1633 // using a declaration for which we must emit a definition but where
1634 // we might not find a top-level definition:
1635 // - member functions defined inline in their classes
1636 // - friend functions defined inline in some class
1637 // - special member functions with implicit definitions
1638 // If we ever change our AST traversal to walk into class methods,
1639 // this will be unnecessary.
1640 //
1641 // We also don't emit a definition for a function if it's going to be an
Stephen Hines176edba2014-12-01 14:53:08 -08001642 // entry in a vtable, unless it's already marked as used.
Stephen Hines651f13c2014-04-23 16:59:28 -07001643 } else if (getLangOpts().CPlusPlus && D) {
1644 // Look for a declaration that's lexically in a record.
Stephen Hines176edba2014-12-01 14:53:08 -08001645 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1646 FD = FD->getPreviousDecl()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001647 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Stephen Hines176edba2014-12-01 14:53:08 -08001648 if (FD->doesThisDeclarationHaveABody()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001649 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1650 break;
1651 }
John McCallbfdcdc82010-12-15 04:00:32 +00001652 }
Stephen Hines176edba2014-12-01 14:53:08 -08001653 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001654 }
Chris Lattner67b00522009-03-21 09:44:56 +00001655 }
Mike Stump1eb44332009-09-09 15:08:12 +00001656
John McCall784f2112010-04-28 00:00:30 +00001657 // Make sure the result is of the requested type.
1658 if (!IsIncompleteFunction) {
1659 assert(F->getType()->getElementType() == Ty);
1660 return F;
1661 }
1662
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001663 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCall784f2112010-04-28 00:00:30 +00001664 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +00001665}
1666
Chris Lattner74391b42009-03-22 21:03:39 +00001667/// GetAddrOfFunction - Return the address of the given function. If Ty is
1668/// non-null, then this function will use the specified type if it has to
1669/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001670llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001671 llvm::Type *Ty,
Stephen Hines651f13c2014-04-23 16:59:28 -07001672 bool ForVTable,
1673 bool DontDefer) {
Chris Lattner74391b42009-03-22 21:03:39 +00001674 // If there was no specific requested type, just convert it now.
1675 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001676 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001677
Chris Lattner5f9e2722011-07-23 10:55:15 +00001678 StringRef MangledName = getMangledName(GD);
Stephen Hines651f13c2014-04-23 16:59:28 -07001679 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
Chris Lattner74391b42009-03-22 21:03:39 +00001680}
Eli Friedman77ba7082008-05-30 19:50:47 +00001681
Chris Lattner74391b42009-03-22 21:03:39 +00001682/// CreateRuntimeFunction - Create a new runtime function with the specified
1683/// type and name.
1684llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001685CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001686 StringRef Name,
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001687 llvm::AttributeSet ExtraAttrs) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001688 llvm::Constant *C =
1689 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
Stephen Hines176edba2014-12-01 14:53:08 -08001690 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001691 if (auto *F = dyn_cast<llvm::Function>(C))
John McCallbd7370a2013-02-28 19:01:20 +00001692 if (F->empty())
1693 F->setCallingConv(getRuntimeCC());
1694 return C;
Chris Lattner74391b42009-03-22 21:03:39 +00001695}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001696
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001697/// CreateBuiltinFunction - Create a new builtin function with the specified
1698/// type and name.
1699llvm::Constant *
1700CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1701 StringRef Name,
1702 llvm::AttributeSet ExtraAttrs) {
1703 llvm::Constant *C =
1704 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1705 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1706 if (auto *F = dyn_cast<llvm::Function>(C))
1707 if (F->empty())
1708 F->setCallingConv(getBuiltinCC());
1709 return C;
1710}
1711
Richard Smitha9b21d22012-02-17 06:48:11 +00001712/// isTypeConstant - Determine whether an object of this type can be emitted
1713/// as a constant.
1714///
1715/// If ExcludeCtor is true, the duration when the object's constructor runs
1716/// will not be considered. The caller will need to verify that the object is
1717/// not written to during its construction.
1718bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1719 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +00001720 return false;
Richard Smitha9b21d22012-02-17 06:48:11 +00001721
David Blaikie4e4d0842012-03-11 07:00:24 +00001722 if (Context.getLangOpts().CPlusPlus) {
Richard Smitha9b21d22012-02-17 06:48:11 +00001723 if (const CXXRecordDecl *Record
1724 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1725 return ExcludeCtor && !Record->hasMutableFields() &&
1726 Record->hasTrivialDestructor();
Eli Friedman20e098b2009-12-11 21:23:03 +00001727 }
Richard Smitha9b21d22012-02-17 06:48:11 +00001728
Eli Friedman20e098b2009-12-11 21:23:03 +00001729 return true;
1730}
1731
Chris Lattner74391b42009-03-22 21:03:39 +00001732/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1733/// create and return an llvm GlobalVariable with the specified type. If there
1734/// is something in the module with the specified name, return it potentially
1735/// bitcasted to the right type.
1736///
1737/// If D is non-null, it specifies a decl that correspond to this. This is used
1738/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001739llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001740CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001741 llvm::PointerType *Ty,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001742 const VarDecl *D) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00001743 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001744 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00001745 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001746 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001747 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001748 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001749 }
1750
Stephen Hines176edba2014-12-01 14:53:08 -08001751 // Handle dropped DLL attributes.
1752 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1753 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1754
Chris Lattner74391b42009-03-22 21:03:39 +00001755 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00001756 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Chris Lattner99b53612009-03-21 08:03:33 +00001758 // Make sure the result is of the correct type.
Matt Arsenault54307da2013-11-15 02:19:52 +00001759 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1760 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1761
Owen Anderson3c4972d2009-07-29 18:54:39 +00001762 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001763 }
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Stephen Hines651f13c2014-04-23 16:59:28 -07001765 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001766 auto *GV = new llvm::GlobalVariable(
1767 getModule(), Ty->getElementType(), false,
1768 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
1769 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Stephen Hines651f13c2014-04-23 16:59:28 -07001770
Chris Lattner67b00522009-03-21 09:44:56 +00001771 // This is the first use or definition of a mangled name. If there is a
1772 // deferred decl with this name, remember that we need to emit it at the end
1773 // of the file.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001774 auto DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001775 if (DDI != DeferredDecls.end()) {
1776 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1777 // list, and remove it from DeferredDecls (since we don't need it anymore).
Stephen Hines651f13c2014-04-23 16:59:28 -07001778 addDeferredDeclToEmit(GV, DDI->second);
Chris Lattner67b00522009-03-21 09:44:56 +00001779 DeferredDecls.erase(DDI);
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Chris Lattner99b53612009-03-21 08:03:33 +00001782 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001783 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001784 // FIXME: This code is overly simple and should be merged with other global
1785 // handling.
Richard Smitha9b21d22012-02-17 06:48:11 +00001786 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner99b53612009-03-21 08:03:33 +00001787
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001788 setLinkageAndVisibilityForGV(GV, D);
Eli Friedman56ebe502009-04-19 21:05:03 +00001789
Richard Smithb80a16e2013-04-19 16:42:07 +00001790 if (D->getTLSKind()) {
Richard Smithdb4f61f2013-04-22 08:06:17 +00001791 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1792 CXXThreadLocals.push_back(std::make_pair(D, GV));
Hans Wennborgde981f32012-06-28 08:01:44 +00001793 setTLSMode(GV, *D);
Richard Smithb80a16e2013-04-19 16:42:07 +00001794 }
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00001795
1796 // If required by the ABI, treat declarations of static data members with
1797 // inline initializers as definitions.
Stephen Hines176edba2014-12-01 14:53:08 -08001798 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00001799 EmitGlobalVarDefinition(D);
Stephen Hines176edba2014-12-01 14:53:08 -08001800 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001801
1802 // Handle XCore specific ABI requirements.
1803 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1804 D->getLanguageLinkage() == CLanguageLinkage &&
1805 D->getType().isConstant(Context) &&
1806 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1807 GV->setSection(".cp.rodata");
Chris Lattner74391b42009-03-22 21:03:39 +00001808 }
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001810 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault54307da2013-11-15 02:19:52 +00001811 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1812
1813 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001814}
1815
Chris Lattner74391b42009-03-22 21:03:39 +00001816
Anders Carlsson3bd62022011-01-29 18:20:20 +00001817llvm::GlobalVariable *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001818CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001819 llvm::Type *Ty,
Anders Carlsson3bd62022011-01-29 18:20:20 +00001820 llvm::GlobalValue::LinkageTypes Linkage) {
1821 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001822 llvm::GlobalVariable *OldGV = nullptr;
Anders Carlsson3bd62022011-01-29 18:20:20 +00001823
Anders Carlsson3bd62022011-01-29 18:20:20 +00001824 if (GV) {
1825 // Check if the variable has the right type.
1826 if (GV->getType()->getElementType() == Ty)
1827 return GV;
1828
1829 // Because C++ name mangling, the only way we can end up with an already
1830 // existing global with the same name is if it has been declared extern "C".
Nico Weberc5f80462012-10-11 10:13:44 +00001831 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001832 OldGV = GV;
1833 }
1834
1835 // Create a new variable.
1836 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001837 Linkage, nullptr, Name);
1838
Anders Carlsson3bd62022011-01-29 18:20:20 +00001839 if (OldGV) {
1840 // Replace occurrences of the old variable if needed.
1841 GV->takeName(OldGV);
1842
1843 if (!OldGV->use_empty()) {
1844 llvm::Constant *NewPtrForOldDecl =
1845 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1846 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1847 }
1848
1849 OldGV->eraseFromParent();
1850 }
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001851
1852 if (supportsCOMDAT() && GV->isWeakForLinker())
1853 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1854
Anders Carlsson3bd62022011-01-29 18:20:20 +00001855 return GV;
1856}
1857
Chris Lattner74391b42009-03-22 21:03:39 +00001858/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1859/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher0ff258b2012-04-16 23:55:04 +00001860/// then it will be created with the specified type instead of whatever the
Chris Lattner74391b42009-03-22 21:03:39 +00001861/// normal requested type would be.
1862llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001863 llvm::Type *Ty) {
Chris Lattner74391b42009-03-22 21:03:39 +00001864 assert(D->hasGlobalStorage() && "Not a global variable");
1865 QualType ASTTy = D->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001866 if (!Ty)
Chris Lattner74391b42009-03-22 21:03:39 +00001867 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Chris Lattner2acc6e32011-07-18 04:24:23 +00001869 llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001870 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001871
Chris Lattner5f9e2722011-07-23 10:55:15 +00001872 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001873 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001874}
1875
1876/// CreateRuntimeVariable - Create a new runtime global variable with the
1877/// specified type and name.
1878llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001879CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001880 StringRef Name) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001881 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
Chris Lattner74391b42009-03-22 21:03:39 +00001882}
1883
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001884void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1885 assert(!D->getInit() && "Cannot emit definite definitions here!");
1886
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001887 if (!MustBeEmitted(D)) {
Douglas Gregor7520bd12009-04-21 19:28:58 +00001888 // If we have not seen a reference to this variable yet, place it
1889 // into the deferred declarations table to be emitted if needed
1890 // later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001891 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001892 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001893 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001894 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001895 }
1896 }
1897
1898 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001899 EmitGlobalVarDefinition(D);
1900}
1901
Chris Lattner2acc6e32011-07-18 04:24:23 +00001902CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001903 return Context.toCharUnitsFromBits(
Micah Villmow25a6a842012-10-08 16:25:52 +00001904 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001905}
1906
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001907unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1908 unsigned AddrSpace) {
1909 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1910 if (D->hasAttr<CUDAConstantAttr>())
1911 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1912 else if (D->hasAttr<CUDASharedAttr>())
1913 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1914 else
1915 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1916 }
1917
1918 return AddrSpace;
1919}
1920
Richard Smith00249372013-04-06 05:00:46 +00001921template<typename SomeDecl>
1922void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1923 llvm::GlobalValue *GV) {
1924 if (!getLangOpts().CPlusPlus)
1925 return;
1926
1927 // Must have 'used' attribute, or else inline assembly can't rely on
1928 // the name existing.
1929 if (!D->template hasAttr<UsedAttr>())
1930 return;
1931
1932 // Must have internal linkage and an ordinary name.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001933 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smith00249372013-04-06 05:00:46 +00001934 return;
1935
1936 // Must be in an extern "C" context. Entities declared directly within
1937 // a record are not extern "C" even if the record is in such a context.
Rafael Espindolabc650912013-10-17 15:37:26 +00001938 const SomeDecl *First = D->getFirstDecl();
Rafael Espindolad8ffd0b2013-05-05 20:15:21 +00001939 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smith00249372013-04-06 05:00:46 +00001940 return;
1941
1942 // OK, this is an internal linkage entity inside an extern "C" linkage
1943 // specification. Make a note of that so we can give it the "expected"
1944 // mangled name if nothing else is using that name.
Richard Smith67972042013-04-06 07:07:44 +00001945 std::pair<StaticExternCMap::iterator, bool> R =
1946 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smith00249372013-04-06 05:00:46 +00001947
1948 // If we have multiple internal linkage entities with the same name
1949 // in extern "C" regions, none of them gets that name.
Richard Smith67972042013-04-06 07:07:44 +00001950 if (!R.second)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001951 R.first->second = nullptr;
Richard Smith00249372013-04-06 05:00:46 +00001952}
1953
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001954static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
1955 if (!CGM.supportsCOMDAT())
1956 return false;
1957
1958 if (D.hasAttr<SelectAnyAttr>())
1959 return true;
1960
1961 GVALinkage Linkage;
1962 if (auto *VD = dyn_cast<VarDecl>(&D))
1963 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
1964 else
1965 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
1966
1967 switch (Linkage) {
1968 case GVA_Internal:
1969 case GVA_AvailableExternally:
1970 case GVA_StrongExternal:
1971 return false;
1972 case GVA_DiscardableODR:
1973 case GVA_StrongODR:
1974 return true;
1975 }
1976 llvm_unreachable("No such linkage");
1977}
1978
1979void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
1980 llvm::GlobalObject &GO) {
1981 if (!shouldBeInCOMDAT(*this, D))
1982 return;
1983 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
1984}
1985
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001986void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001987 llvm::Constant *Init = nullptr;
Eli Friedman77ba7082008-05-30 19:50:47 +00001988 QualType ASTTy = D->getType();
Richard Smith7ca48502012-02-13 22:16:19 +00001989 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1990 bool NeedsGlobalCtor = false;
1991 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Richard Smith2d6a5672012-01-14 04:30:29 +00001993 const VarDecl *InitDecl;
1994 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001995
Anders Carlsson3bb92692010-01-26 17:43:42 +00001996 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001997 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001998 // implicitly initialized with { 0 }.
1999 //
2000 // Note that tentative definitions are only emitted at the end of
2001 // a translation unit, so they should never have incomplete
2002 // type. In addition, EmitTentativeDefinition makes sure that we
2003 // never attempt to emit a tentative definition if a real one
2004 // exists. A use may still exists, however, so we still may need
2005 // to do a RAUW.
2006 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00002007 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00002008 } else {
Richard Smith7c3e6152013-06-12 22:31:48 +00002009 initializedGlobalDecl = GlobalDecl(D);
2010 Init = EmitConstantInit(*InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00002011
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00002012 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00002013 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00002014 if (D->getType()->isReferenceType())
2015 T = D->getType();
Richard Smith2d6a5672012-01-14 04:30:29 +00002016
David Blaikie4e4d0842012-03-11 07:00:24 +00002017 if (getLangOpts().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00002018 Init = EmitNullConstant(T);
Richard Smith7ca48502012-02-13 22:16:19 +00002019 NeedsGlobalCtor = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00002020 } else {
2021 ErrorUnsupported(D, "static initializer");
2022 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2023 }
John McCallbf40cb52010-07-15 23:40:35 +00002024 } else {
2025 // We don't need an initializer, so remove the entry for the delayed
Richard Smith7ca48502012-02-13 22:16:19 +00002026 // initializer position (just in case this entry was delayed) if we
2027 // also don't need to register a destructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00002028 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCallbf40cb52010-07-15 23:40:35 +00002029 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00002030 }
Eli Friedman77ba7082008-05-30 19:50:47 +00002031 }
Eli Friedman77ba7082008-05-30 19:50:47 +00002032
Chris Lattner2acc6e32011-07-18 04:24:23 +00002033 llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00002034 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Chris Lattner570585c2009-03-21 09:16:30 +00002036 // Strip off a bitcast if we got one back.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002037 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002038 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault54307da2013-11-15 02:19:52 +00002039 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2040 // All zero index gep.
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002041 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00002042 Entry = CE->getOperand(0);
2043 }
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Chris Lattner570585c2009-03-21 09:16:30 +00002045 // Entry is now either a Function or GlobalVariable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002046 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Chris Lattner570585c2009-03-21 09:16:30 +00002048 // We have a definition after a declaration with the wrong type.
2049 // We must make a new GlobalVariable* and update everything that used OldGV
2050 // (a declaration or tentative definition) with the new GlobalVariable*
2051 // (which will be a definition).
2052 //
2053 // This happens if there is a prototype for a global (e.g.
2054 // "extern int x[];") and then a definition of a different type (e.g.
2055 // "int x[10];"). This also happens when an initializer has a different type
2056 // from the type of the global (this happens with unions).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002057 if (!GV ||
Chris Lattner570585c2009-03-21 09:16:30 +00002058 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00002059 GV->getType()->getAddressSpace() !=
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00002060 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump1eb44332009-09-09 15:08:12 +00002061
John McCallf746aa62010-03-19 23:29:14 +00002062 // Move the old entry aside so that we'll create a new one.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002063 Entry->setName(StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00002064
Chris Lattner570585c2009-03-21 09:16:30 +00002065 // Make a new global with the correct type, this is now guaranteed to work.
2066 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00002067
Eli Friedman77ba7082008-05-30 19:50:47 +00002068 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00002069 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00002070 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00002071 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00002072
2073 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00002074 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00002075 }
Devang Patel8e53e722007-10-26 16:31:40 +00002076
Richard Smith00249372013-04-06 05:00:46 +00002077 MaybeHandleStaticInExternC(D, GV);
2078
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002079 if (D->hasAttr<AnnotateAttr>())
2080 AddGlobalAnnotations(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00002081
Chris Lattner88a69ad2007-07-13 05:13:43 +00002082 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00002083
2084 // If it is safe to mark the global 'constant', do so now.
Richard Smitha9b21d22012-02-17 06:48:11 +00002085 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2086 isTypeConstant(D->getType(), true));
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Stephen Hines176edba2014-12-01 14:53:08 -08002088 // If it is in a read-only section, mark it 'constant'.
2089 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2090 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2091 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2092 GV->setConstant(true);
2093 }
2094
Ken Dyck8b752f12010-01-27 17:10:57 +00002095 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smitha9b21d22012-02-17 06:48:11 +00002096
Chris Lattner88a69ad2007-07-13 05:13:43 +00002097 // Set the llvm linkage type as appropriate.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002098 llvm::GlobalValue::LinkageTypes Linkage =
2099 getLLVMLinkageVarDefinition(D, GV->isConstant());
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002100
2101 // On Darwin, the backing variable for a C++11 thread_local variable always
2102 // has internal linkage; all accesses should just be calls to the
2103 // Itanium-specified entry point, which has the normal linkage of the
2104 // variable.
Stephen Hines176edba2014-12-01 14:53:08 -08002105 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2106 Context.getTargetInfo().getTriple().isMacOSX())
2107 Linkage = llvm::GlobalValue::InternalLinkage;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002108
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002109 GV->setLinkage(Linkage);
Stephen Hines651f13c2014-04-23 16:59:28 -07002110 if (D->hasAttr<DLLImportAttr>())
2111 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2112 else if (D->hasAttr<DLLExportAttr>())
2113 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Stephen Hines176edba2014-12-01 14:53:08 -08002114 else
2115 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Bill Wendling0cbb3ed2013-11-21 05:19:27 +00002116
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002117 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00002118 // common vars aren't constant even if declared const.
2119 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00002120
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002121 setNonAliasAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00002122
Stephen Hines176edba2014-12-01 14:53:08 -08002123 if (D->getTLSKind() && !GV->isThreadLocal()) {
2124 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2125 CXXThreadLocals.push_back(std::make_pair(D, GV));
2126 setTLSMode(GV, *D);
2127 }
2128
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002129 maybeSetTrivialComdat(*D, *GV);
2130
John McCall3030eb82010-11-06 09:44:32 +00002131 // Emit the initializer function if necessary.
Richard Smith7ca48502012-02-13 22:16:19 +00002132 if (NeedsGlobalCtor || NeedsGlobalDtor)
2133 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCall3030eb82010-11-06 09:44:32 +00002134
Stephen Hines176edba2014-12-01 14:53:08 -08002135 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00002136
Sanjiv Gupta686226b2008-06-05 08:59:10 +00002137 // Emit global variable debug information.
Eric Christopher73fb3502011-10-13 21:45:18 +00002138 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregor4cdad312012-10-23 20:05:01 +00002139 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00002140 DI->EmitGlobalVariable(GV, D);
Chris Lattner88a69ad2007-07-13 05:13:43 +00002141}
Reid Spencer5f016e22007-07-11 17:01:13 +00002142
Stephen Hines176edba2014-12-01 14:53:08 -08002143static bool isVarDeclStrongDefinition(const ASTContext &Context,
2144 const VarDecl *D, bool NoCommon) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002145 // Don't give variables common linkage if -fno-common was specified unless it
2146 // was overridden by a NoCommon attribute.
2147 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2148 return true;
2149
2150 // C11 6.9.2/2:
2151 // A declaration of an identifier for an object that has file scope without
2152 // an initializer, and without a storage-class specifier or with the
2153 // storage-class specifier static, constitutes a tentative definition.
2154 if (D->getInit() || D->hasExternalStorage())
2155 return true;
2156
2157 // A variable cannot be both common and exist in a section.
2158 if (D->hasAttr<SectionAttr>())
2159 return true;
2160
2161 // Thread local vars aren't considered common linkage.
2162 if (D->getTLSKind())
2163 return true;
2164
2165 // Tentative definitions marked with WeakImportAttr are true definitions.
2166 if (D->hasAttr<WeakImportAttr>())
2167 return true;
2168
Stephen Hines176edba2014-12-01 14:53:08 -08002169 // Declarations with a required alignment do not have common linakge in MSVC
2170 // mode.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002171 if (Context.getLangOpts().MSVCCompat) {
2172 if (D->hasAttr<AlignedAttr>())
2173 return true;
2174 QualType VarType = D->getType();
2175 if (Context.isAlignmentRequired(VarType))
2176 return true;
2177
2178 if (const auto *RT = VarType->getAs<RecordType>()) {
2179 const RecordDecl *RD = RT->getDecl();
2180 for (const FieldDecl *FD : RD->fields()) {
2181 if (FD->isBitField())
2182 continue;
2183 if (FD->hasAttr<AlignedAttr>())
2184 return true;
2185 if (Context.isAlignmentRequired(FD->getType()))
2186 return true;
2187 }
2188 }
2189 }
Stephen Hines176edba2014-12-01 14:53:08 -08002190
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002191 return false;
2192}
2193
2194llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2195 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002196 if (Linkage == GVA_Internal)
2197 return llvm::Function::InternalLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002198
2199 if (D->hasAttr<WeakAttr>()) {
2200 if (IsConstantVariable)
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002201 return llvm::GlobalVariable::WeakODRLinkage;
2202 else
2203 return llvm::GlobalVariable::WeakAnyLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002204 }
2205
2206 // We are guaranteed to have a strong definition somewhere else,
2207 // so we can use available_externally linkage.
2208 if (Linkage == GVA_AvailableExternally)
2209 return llvm::Function::AvailableExternallyLinkage;
2210
2211 // Note that Apple's kernel linker doesn't support symbol
2212 // coalescing, so we need to avoid linkonce and weak linkages there.
2213 // Normally, this means we just map to internal, but for explicit
2214 // instantiations we'll map to external.
2215
2216 // In C++, the compiler has to emit a definition in every translation unit
2217 // that references the function. We should use linkonce_odr because
2218 // a) if all references in this translation unit are optimized away, we
2219 // don't need to codegen it. b) if the function persists, it needs to be
2220 // merged with other definitions. c) C++ has the ODR, so we know the
2221 // definition is dependable.
2222 if (Linkage == GVA_DiscardableODR)
2223 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2224 : llvm::Function::InternalLinkage;
2225
2226 // An explicit instantiation of a template has weak linkage, since
2227 // explicit instantiations can occur in multiple translation units
2228 // and must all be equivalent. However, we are not allowed to
2229 // throw away these explicit instantiations.
2230 if (Linkage == GVA_StrongODR)
2231 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2232 : llvm::Function::ExternalLinkage;
2233
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002234 // C++ doesn't have tentative definitions and thus cannot have common
2235 // linkage.
2236 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
Stephen Hines176edba2014-12-01 14:53:08 -08002237 !isVarDeclStrongDefinition(Context, cast<VarDecl>(D),
2238 CodeGenOpts.NoCommon))
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002239 return llvm::GlobalVariable::CommonLinkage;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002240
2241 // selectany symbols are externally visible, so use weak instead of
2242 // linkonce. MSVC optimizes away references to const selectany globals, so
2243 // all definitions should be the same and ODR linkage should be used.
2244 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2245 if (D->hasAttr<SelectAnyAttr>())
2246 return llvm::GlobalVariable::WeakODRLinkage;
2247
2248 // Otherwise, we have strong external linkage.
2249 assert(Linkage == GVA_StrongExternal);
Fariborz Jahanian354e7122010-10-27 16:21:54 +00002250 return llvm::GlobalVariable::ExternalLinkage;
2251}
2252
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002253llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2254 const VarDecl *VD, bool IsConstant) {
2255 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2256 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2257}
2258
John McCalla923c972012-12-12 22:21:47 +00002259/// Replace the uses of a function that was declared with a non-proto type.
2260/// We want to silently drop extra arguments from call sites
2261static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2262 llvm::Function *newFn) {
2263 // Fast path.
2264 if (old->use_empty()) return;
2265
2266 llvm::Type *newRetTy = newFn->getReturnType();
2267 SmallVector<llvm::Value*, 4> newArgs;
2268
2269 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2270 ui != ue; ) {
2271 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Stephen Hines651f13c2014-04-23 16:59:28 -07002272 llvm::User *user = use->getUser();
John McCalla923c972012-12-12 22:21:47 +00002273
2274 // Recognize and replace uses of bitcasts. Most calls to
2275 // unprototyped functions will use bitcasts.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002276 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
John McCalla923c972012-12-12 22:21:47 +00002277 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2278 replaceUsesOfNonProtoConstant(bitcast, newFn);
2279 continue;
2280 }
2281
2282 // Recognize calls to the function.
2283 llvm::CallSite callSite(user);
2284 if (!callSite) continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07002285 if (!callSite.isCallee(&*use)) continue;
John McCalla923c972012-12-12 22:21:47 +00002286
2287 // If the return types don't match exactly, then we can't
2288 // transform this call unless it's dead.
2289 if (callSite->getType() != newRetTy && !callSite->use_empty())
2290 continue;
2291
2292 // Get the call site's attribute list.
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002293 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCalla923c972012-12-12 22:21:47 +00002294 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2295
2296 // Collect any return attributes from the call.
Bill Wendlinga37ce612013-01-21 21:57:40 +00002297 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlinged01f842013-01-21 22:45:00 +00002298 newAttrs.push_back(
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002299 llvm::AttributeSet::get(newFn->getContext(),
2300 oldAttrs.getRetAttributes()));
John McCalla923c972012-12-12 22:21:47 +00002301
2302 // If the function was passed too few arguments, don't transform.
2303 unsigned newNumArgs = newFn->arg_size();
2304 if (callSite.arg_size() < newNumArgs) continue;
2305
2306 // If extra arguments were passed, we silently drop them.
2307 // If any of the types mismatch, we don't transform.
2308 unsigned argNo = 0;
2309 bool dontTransform = false;
2310 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2311 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2312 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2313 dontTransform = true;
2314 break;
2315 }
2316
2317 // Add any parameter attributes.
Bill Wendling89530e42013-01-23 06:15:10 +00002318 if (oldAttrs.hasAttributes(argNo + 1))
2319 newAttrs.
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002320 push_back(llvm::
2321 AttributeSet::get(newFn->getContext(),
2322 oldAttrs.getParamAttributes(argNo + 1)));
John McCalla923c972012-12-12 22:21:47 +00002323 }
2324 if (dontTransform)
2325 continue;
2326
Bill Wendlinge67e4c92013-01-18 21:26:07 +00002327 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendlingb263bdf2013-01-27 02:46:53 +00002328 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2329 oldAttrs.getFnAttributes()));
John McCalla923c972012-12-12 22:21:47 +00002330
2331 // Okay, we can transform this. Create the new call instruction and copy
2332 // over the required information.
2333 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2334
2335 llvm::CallSite newCall;
2336 if (callSite.isCall()) {
2337 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2338 callSite.getInstruction());
2339 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002340 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
John McCalla923c972012-12-12 22:21:47 +00002341 newCall = llvm::InvokeInst::Create(newFn,
2342 oldInvoke->getNormalDest(),
2343 oldInvoke->getUnwindDest(),
2344 newArgs, "",
2345 callSite.getInstruction());
2346 }
2347 newArgs.clear(); // for the next iteration
2348
2349 if (!newCall->getType()->isVoidTy())
2350 newCall->takeName(callSite.getInstruction());
2351 newCall.setAttributes(
2352 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2353 newCall.setCallingConv(callSite.getCallingConv());
2354
2355 // Finally, remove the old call, replacing any uses with the new one.
2356 if (!callSite->use_empty())
2357 callSite->replaceAllUsesWith(newCall.getInstruction());
2358
2359 // Copy debug location attached to CI.
2360 if (!callSite->getDebugLoc().isUnknown())
2361 newCall->setDebugLoc(callSite->getDebugLoc());
2362 callSite->eraseFromParent();
2363 }
2364}
2365
Chris Lattnerbdb01322009-05-05 06:16:31 +00002366/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2367/// implement a function with no prototype, e.g. "int foo() {}". If there are
2368/// existing call uses of the old function in the module, this adjusts them to
2369/// call the new function directly.
2370///
2371/// This is not just a cleanup: the always_inline pass requires direct calls to
2372/// functions to be able to inline them. If there is a bitcast in the way, it
2373/// won't inline them. Instcombine normally deletes these calls, but it isn't
2374/// run at -O0.
2375static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2376 llvm::Function *NewFn) {
2377 // If we're redefining a global as a function, don't transform it.
John McCalla923c972012-12-12 22:21:47 +00002378 if (!isa<llvm::Function>(Old)) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002379
John McCalla923c972012-12-12 22:21:47 +00002380 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattnerbdb01322009-05-05 06:16:31 +00002381}
2382
Rafael Espindola02503932012-03-08 15:51:03 +00002383void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2384 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2385 // If we have a definition, this might be a deferred decl. If the
2386 // instantiation is explicit, make sure we emit it at the end.
2387 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2388 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00002389
2390 EmitTopLevelDecl(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +00002391}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002392
Stephen Hines651f13c2014-04-23 16:59:28 -07002393void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2394 llvm::GlobalValue *GV) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002395 const auto *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00002396
John McCall1f6f9612011-03-09 08:12:35 +00002397 // Compute the function info and LLVM type.
John McCallde5d3c72012-02-17 03:33:10 +00002398 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2399 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalld26bc762011-03-09 04:27:21 +00002400
Chris Lattner9fa959d2009-05-12 20:58:15 +00002401 // Get or create the prototype for the function.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002402 if (!GV) {
2403 llvm::Constant *C =
2404 GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002406 // Strip off a bitcast if we got one back.
2407 if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2408 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2409 GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2410 } else {
2411 GV = cast<llvm::GlobalValue>(C);
2412 }
Chris Lattner0558e792009-03-21 09:25:43 +00002413 }
Mike Stump1eb44332009-09-09 15:08:12 +00002414
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002415 if (!GV->isDeclaration()) {
Bill Wendlinga36ef5b2013-11-25 07:42:52 +00002416 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
Stephen Hines176edba2014-12-01 14:53:08 -08002417 GlobalDecl OldGD = Manglings.lookup(GV->getName());
2418 if (auto *Prev = OldGD.getDecl())
2419 getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
Bill Wendlinga36ef5b2013-11-25 07:42:52 +00002420 return;
2421 }
Mike Stump1eb44332009-09-09 15:08:12 +00002422
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002423 if (GV->getType()->getElementType() != Ty) {
Daniel Dunbar42745812009-03-09 23:53:08 +00002424 // If the types mismatch then we have to rewrite the definition.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002425 assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00002426
Chris Lattner62b33ea2009-03-21 08:38:50 +00002427 // F is the Function* for the one with the wrong type, we must make a new
2428 // Function* and update everything that used F (a declaration) with the new
2429 // Function* (which will be a definition).
2430 //
2431 // This happens if there is a prototype for a function
2432 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00002433 // (e.g. "int f(int x)"). Move the old function aside so that it
2434 // doesn't interfere with GetAddrOfFunction.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002435 GV->setName(StringRef());
2436 auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00002437
John McCalla923c972012-12-12 22:21:47 +00002438 // This might be an implementation of a function without a
2439 // prototype, in which case, try to do special replacement of
2440 // calls which match the new prototype. The really key thing here
2441 // is that we also potentially drop arguments from the call site
2442 // so as to make a direct call, which makes the inliner happier
2443 // and suppresses a number of optimizer warnings (!) about
2444 // dropping arguments.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002445 if (!GV->use_empty()) {
2446 ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2447 GV->removeDeadConstantUsers();
Chris Lattner9fa959d2009-05-12 20:58:15 +00002448 }
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Chris Lattner62b33ea2009-03-21 08:38:50 +00002450 // Replace uses of F with the Function we will endow with a body.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002451 if (!GV->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002452 llvm::Constant *NewPtrForOldDecl =
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002453 llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2454 GV->replaceAllUsesWith(NewPtrForOldDecl);
Chris Lattnerbdb01322009-05-05 06:16:31 +00002455 }
Mike Stump1eb44332009-09-09 15:08:12 +00002456
Chris Lattner62b33ea2009-03-21 08:38:50 +00002457 // Ok, delete the old function now, which is dead.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002458 GV->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002459
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002460 GV = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002461 }
Mike Stump1eb44332009-09-09 15:08:12 +00002462
John McCall112c9672010-11-02 21:04:24 +00002463 // We need to set linkage and visibility on the function before
2464 // generating code for it because various parts of IR generation
2465 // want to propagate this information down (e.g. to local static
2466 // declarations).
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002467 auto *Fn = cast<llvm::Function>(GV);
Peter Collingbourne144a31f2013-06-05 17:49:37 +00002468 setFunctionLinkage(GD, Fn);
Stephen Hines176edba2014-12-01 14:53:08 -08002469 if (D->hasAttr<DLLImportAttr>())
2470 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2471 else if (D->hasAttr<DLLExportAttr>())
2472 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2473 else
2474 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002475
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002476 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00002477 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00002478
Richard Smith00249372013-04-06 05:00:46 +00002479 MaybeHandleStaticInExternC(D, Fn);
2480
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002481 maybeSetTrivialComdat(*D, *Fn);
2482
John McCalld26bc762011-03-09 04:27:21 +00002483 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00002484
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002485 setFunctionDefinitionAttributes(D, Fn);
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002486 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00002487
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002488 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002489 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002490 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002491 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002492 if (D->hasAttr<AnnotateAttr>())
2493 AddGlobalAnnotations(D, Fn);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002494}
Stephen Hines651f13c2014-04-23 16:59:28 -07002495
John McCallf746aa62010-03-19 23:29:14 +00002496void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002497 const auto *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002498 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00002499 assert(AA && "Not an alias?");
2500
Chris Lattner5f9e2722011-07-23 10:55:15 +00002501 StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00002502
John McCallf746aa62010-03-19 23:29:14 +00002503 // If there is a definition in the module, then it wins over the alias.
2504 // This is dubious, but allow it to be safe. Just ignore the alias.
2505 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2506 if (Entry && !Entry->isDeclaration())
2507 return;
2508
Rafael Espindolad2054982013-10-22 19:26:13 +00002509 Aliases.push_back(GD);
2510
Chris Lattner2acc6e32011-07-18 04:24:23 +00002511 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00002512
2513 // Create a reference to the named value. This ensures that it is emitted
2514 // if a deferred decl.
2515 llvm::Constant *Aliasee;
2516 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00002517 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00002518 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00002519 else
John McCallf746aa62010-03-19 23:29:14 +00002520 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002521 llvm::PointerType::getUnqual(DeclTy),
Stephen Hines176edba2014-12-01 14:53:08 -08002522 /*D=*/nullptr);
Chris Lattnerbd532712009-03-22 21:47:11 +00002523
2524 // Create the new alias itself, but don't set a name yet.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002525 auto *GA = llvm::GlobalAlias::create(
2526 cast<llvm::PointerType>(Aliasee->getType())->getElementType(), 0,
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002527 llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Chris Lattnerbd532712009-03-22 21:47:11 +00002529 if (Entry) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002530 if (GA->getAliasee() == Entry) {
2531 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2532 return;
2533 }
2534
John McCallf746aa62010-03-19 23:29:14 +00002535 assert(Entry->isDeclaration());
2536
Chris Lattnerbd532712009-03-22 21:47:11 +00002537 // If there is a declaration in the module, then we had an extern followed
2538 // by the alias, as in:
2539 // extern int test6();
2540 // ...
2541 // int test6() __attribute__((alias("test7")));
2542 //
2543 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00002544 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Owen Anderson3c4972d2009-07-29 18:54:39 +00002546 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00002547 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00002548 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00002549 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00002550 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00002551 }
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002553 // Set attributes which are particular to an alias; this is a
2554 // specialization of the attributes which may be set on a global
2555 // variable/function.
Stephen Hines176edba2014-12-01 14:53:08 -08002556 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2557 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002558 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2559 }
2560
Stephen Hines176edba2014-12-01 14:53:08 -08002561 if (const auto *VD = dyn_cast<VarDecl>(D))
2562 if (VD->getTLSKind())
2563 setTLSMode(GA, *VD);
2564
2565 setAliasAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00002566}
2567
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002568llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002569 ArrayRef<llvm::Type*> Tys) {
Jay Foaddf983a82011-07-12 14:06:48 +00002570 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002571 Tys);
Chris Lattner7acda7c2007-12-18 00:25:38 +00002572}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00002573
Daniel Dunbar1d552912009-07-23 22:52:48 +00002574static llvm::StringMapEntry<llvm::Constant*> &
2575GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2576 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002577 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00002578 bool &IsUTF16,
2579 unsigned &StringLength) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002580 StringRef String = Literal->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002581 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002582
Daniel Dunbarf015b032009-09-22 10:03:52 +00002583 // Check for simple case.
2584 if (!Literal->containsNonAsciiOrNull()) {
2585 StringLength = NumBytes;
Stephen Hines176edba2014-12-01 14:53:08 -08002586 return *Map.insert(std::make_pair(String, nullptr)).first;
Daniel Dunbarf015b032009-09-22 10:03:52 +00002587 }
2588
Bill Wendling84392d02012-03-30 00:26:17 +00002589 // Otherwise, convert the UTF8 literals into a string of shorts.
2590 IsUTF16 = true;
2591
2592 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divacky31ba6132012-09-06 15:59:27 +00002593 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002594 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00002595
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00002596 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2597 &ToPtr, ToPtr + NumBytes,
2598 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002600 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00002601 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002602
Bill Wendling84392d02012-03-30 00:26:17 +00002603 // Add an explicit null.
2604 *ToPtr = 0;
Stephen Hines176edba2014-12-01 14:53:08 -08002605 return *Map.insert(std::make_pair(
2606 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2607 (StringLength + 1) * 2),
2608 nullptr)).first;
Daniel Dunbar1d552912009-07-23 22:52:48 +00002609}
2610
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002611static llvm::StringMapEntry<llvm::Constant*> &
2612GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling8322c232012-03-29 22:12:09 +00002613 const StringLiteral *Literal,
2614 unsigned &StringLength) {
2615 StringRef String = Literal->getString();
2616 StringLength = String.size();
Stephen Hines176edba2014-12-01 14:53:08 -08002617 return *Map.insert(std::make_pair(String, nullptr)).first;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002618}
2619
Daniel Dunbar1d552912009-07-23 22:52:48 +00002620llvm::Constant *
2621CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2622 unsigned StringLength = 0;
2623 bool isUTF16 = false;
2624 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00002625 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmow25a6a842012-10-08 16:25:52 +00002626 getDataLayout().isLittleEndian(),
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002627 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Stephen Hines176edba2014-12-01 14:53:08 -08002629 if (auto *C = Entry.second)
Daniel Dunbar1d552912009-07-23 22:52:48 +00002630 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00002631
Chris Lattner8b418682012-02-07 00:39:47 +00002632 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002633 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002634 llvm::Value *V;
2635
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002636 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00002637 if (!CFConstantStringClassRef) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002638 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002639 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002640 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002641 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002642 // Decay array -> ptr
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002643 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2644 CFConstantStringClassRef = V;
Anders Carlssonc9e20912007-08-21 00:21:21 +00002645 }
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002646 else
2647 V = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Anders Carlssone3daa762008-11-15 18:54:24 +00002649 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002650
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002651 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
Anders Carlssone3daa762008-11-15 18:54:24 +00002652
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002653 llvm::Constant *Fields[4];
Douglas Gregor44b43212008-12-11 16:49:14 +00002654
Anders Carlssonc9e20912007-08-21 00:21:21 +00002655 // Class pointer.
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002656 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Anders Carlssonc9e20912007-08-21 00:21:21 +00002658 // Flags.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002659 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002660 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00002661 llvm::ConstantInt::get(Ty, 0x07C8);
2662
Anders Carlssonc9e20912007-08-21 00:21:21 +00002663 // String pointer.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002664 llvm::Constant *C = nullptr;
Bill Wendling84392d02012-03-30 00:26:17 +00002665 if (isUTF16) {
Stephen Hines176edba2014-12-01 14:53:08 -08002666 ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2667 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2668 Entry.first().size() / 2);
Bill Wendling84392d02012-03-30 00:26:17 +00002669 C = llvm::ConstantDataArray::get(VMContext, Arr);
2670 } else {
Stephen Hines176edba2014-12-01 14:53:08 -08002671 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
Bill Wendling84392d02012-03-30 00:26:17 +00002672 }
Daniel Dunbara9668e02009-04-03 00:57:44 +00002673
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002674 // Note: -fwritable-strings doesn't make the backing store strings of
2675 // CFStrings writable. (See <rdar://problem/10657500>)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002676 auto *GV =
Stephen Hines651f13c2014-04-23 16:59:28 -07002677 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2678 llvm::GlobalValue::PrivateLinkage, C, ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00002679 GV->setUnnamedAddr(true);
Ulrich Weigand6b203512013-05-06 16:23:57 +00002680 // Don't enforce the target's minimum global alignment, since the only use
2681 // of the string is via this class initializer.
Stephen Hines651f13c2014-04-23 16:59:28 -07002682 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2683 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2684 // that changes the section it ends in, which surprises ld64.
Daniel Dunbara9668e02009-04-03 00:57:44 +00002685 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00002686 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2687 GV->setAlignment(Align.getQuantity());
Stephen Hines651f13c2014-04-23 16:59:28 -07002688 GV->setSection("__TEXT,__ustring");
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00002689 } else {
2690 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2691 GV->setAlignment(Align.getQuantity());
Stephen Hines651f13c2014-04-23 16:59:28 -07002692 GV->setSection("__TEXT,__cstring,cstring_literals");
Daniel Dunbara9668e02009-04-03 00:57:44 +00002693 }
Bill Wendling84392d02012-03-30 00:26:17 +00002694
2695 // String.
Jay Foada5c04342011-07-21 14:31:17 +00002696 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson5add6832009-08-16 05:55:31 +00002697
Bill Wendling84392d02012-03-30 00:26:17 +00002698 if (isUTF16)
2699 // Cast the UTF16 string to the correct type.
2700 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2701
Anders Carlssonc9e20912007-08-21 00:21:21 +00002702 // String length.
2703 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00002704 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Anders Carlssonc9e20912007-08-21 00:21:21 +00002706 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00002707 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00002708 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2709 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00002710 "_unnamed_cfstring_");
Stephen Hines651f13c2014-04-23 16:59:28 -07002711 GV->setSection("__DATA,__cfstring");
Stephen Hines176edba2014-12-01 14:53:08 -08002712 Entry.second = GV;
Mike Stump1eb44332009-09-09 15:08:12 +00002713
Anders Carlsson0c678292007-11-01 00:41:52 +00002714 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00002715}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002716
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002717llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002718CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002719 unsigned StringLength = 0;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002720 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002721 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Stephen Hines176edba2014-12-01 14:53:08 -08002722
2723 if (auto *C = Entry.second)
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002724 return C;
2725
Chris Lattner812234b2012-02-06 22:47:00 +00002726 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002727 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002728 llvm::Value *V;
Fariborz Jahanianec951e02010-04-23 22:33:39 +00002729 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002730 if (!ConstantStringClassRef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002731 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002732 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002733 llvm::Constant *GV;
John McCall260611a2012-06-20 06:18:46 +00002734 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002735 std::string str =
2736 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2737 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002738 GV = getObjCRuntime().GetClassGlobal(str);
2739 // Make sure the result is of the correct type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002740 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002741 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2742 ConstantStringClassRef = V;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002743 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002744 std::string str =
2745 StringClass.empty() ? "_NSConstantStringClassReference"
2746 : "_" + StringClass + "ClassReference";
Chris Lattner2acc6e32011-07-18 04:24:23 +00002747 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002748 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002749 // Decay array -> ptr
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002750 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2751 ConstantStringClassRef = V;
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002752 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002753 }
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002754 else
2755 V = ConstantStringClassRef;
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002756
2757 if (!NSConstantStringType) {
2758 // Construct the type for a constant NSString.
Stephen Hines651f13c2014-04-23 16:59:28 -07002759 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002760 D->startDefinition();
2761
2762 QualType FieldTypes[3];
2763
2764 // const int *isa;
2765 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2766 // const char *str;
2767 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2768 // unsigned int length;
2769 FieldTypes[2] = Context.UnsignedIntTy;
2770
2771 // Create fields
2772 for (unsigned i = 0; i < 3; ++i) {
2773 FieldDecl *Field = FieldDecl::Create(Context, D,
2774 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002775 SourceLocation(), nullptr,
2776 FieldTypes[i], /*TInfo=*/nullptr,
2777 /*BitWidth=*/nullptr,
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002778 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002779 ICIS_NoInit);
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002780 Field->setAccess(AS_public);
2781 D->addDecl(Field);
2782 }
2783
2784 D->completeDefinition();
2785 QualType NSTy = Context.getTagDeclType(D);
2786 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2787 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002788
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002789 llvm::Constant *Fields[3];
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002790
2791 // Class pointer.
Fariborz Jahanian428edb72013-04-16 15:25:39 +00002792 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002793
2794 // String pointer.
Chris Lattner94010692012-02-05 02:30:40 +00002795 llvm::Constant *C =
Stephen Hines176edba2014-12-01 14:53:08 -08002796 llvm::ConstantDataArray::getString(VMContext, Entry.first());
2797
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002798 llvm::GlobalValue::LinkageTypes Linkage;
2799 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002800 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00002801 isConstant = !LangOpts.WritableStrings;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002802
2803 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2804 Linkage, C, ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00002805 GV->setUnnamedAddr(true);
Ulrich Weigand6b203512013-05-06 16:23:57 +00002806 // Don't enforce the target's minimum global alignment, since the only use
2807 // of the string is via this class initializer.
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002808 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2809 GV->setAlignment(Align.getQuantity());
Jay Foada5c04342011-07-21 14:31:17 +00002810 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002811
2812 // String length.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002813 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002814 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2815
2816 // The struct.
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002817 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002818 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2819 llvm::GlobalVariable::PrivateLinkage, C,
2820 "_unnamed_nsstring_");
Stephen Hines651f13c2014-04-23 16:59:28 -07002821 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2822 const char *NSStringNonFragileABISection =
2823 "__DATA,__objc_stringobj,regular,no_dead_strip";
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002824 // FIXME. Fix section.
Stephen Hines651f13c2014-04-23 16:59:28 -07002825 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2826 ? NSStringNonFragileABISection
2827 : NSStringSection);
Stephen Hines176edba2014-12-01 14:53:08 -08002828 Entry.second = GV;
2829
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002830 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002831}
2832
Douglas Gregor0815b572011-08-09 17:23:49 +00002833QualType CodeGenModule::getObjCFastEnumerationStateType() {
2834 if (ObjCFastEnumerationStateType.isNull()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002835 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor0815b572011-08-09 17:23:49 +00002836 D->startDefinition();
2837
2838 QualType FieldTypes[] = {
2839 Context.UnsignedLongTy,
2840 Context.getPointerType(Context.getObjCIdType()),
2841 Context.getPointerType(Context.UnsignedLongTy),
2842 Context.getConstantArrayType(Context.UnsignedLongTy,
2843 llvm::APInt(32, 5), ArrayType::Normal, 0)
2844 };
2845
2846 for (size_t i = 0; i < 4; ++i) {
2847 FieldDecl *Field = FieldDecl::Create(Context,
2848 D,
2849 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002850 SourceLocation(), nullptr,
2851 FieldTypes[i], /*TInfo=*/nullptr,
2852 /*BitWidth=*/nullptr,
Douglas Gregor0815b572011-08-09 17:23:49 +00002853 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002854 ICIS_NoInit);
Douglas Gregor0815b572011-08-09 17:23:49 +00002855 Field->setAccess(AS_public);
2856 D->addDecl(Field);
2857 }
2858
2859 D->completeDefinition();
2860 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2861 }
2862
2863 return ObjCFastEnumerationStateType;
2864}
2865
Eli Friedman64f45a22011-11-01 02:23:42 +00002866llvm::Constant *
2867CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2868 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2869
2870 // Don't emit it as the address of the string, emit the string data itself
2871 // as an inline array.
Chris Lattner812234b2012-02-06 22:47:00 +00002872 if (E->getCharByteWidth() == 1) {
2873 SmallString<64> Str(E->getString());
2874
2875 // Resize the string to the right size, which is indicated by its type.
2876 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2877 Str.resize(CAT->getSize().getZExtValue());
2878 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2879 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002880
2881 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
Chris Lattner94010692012-02-05 02:30:40 +00002882 llvm::Type *ElemTy = AType->getElementType();
2883 unsigned NumElements = AType->getNumElements();
Chris Lattnerd79ed432012-02-06 22:52:04 +00002884
2885 // Wide strings have either 2-byte or 4-byte elements.
2886 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2887 SmallVector<uint16_t, 32> Elements;
2888 Elements.reserve(NumElements);
2889
2890 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2891 Elements.push_back(E->getCodeUnit(i));
2892 Elements.resize(NumElements);
2893 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner94010692012-02-05 02:30:40 +00002894 }
2895
Chris Lattnerd79ed432012-02-06 22:52:04 +00002896 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2897 SmallVector<uint32_t, 32> Elements;
2898 Elements.reserve(NumElements);
2899
2900 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2901 Elements.push_back(E->getCodeUnit(i));
2902 Elements.resize(NumElements);
2903 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedman64f45a22011-11-01 02:23:42 +00002904}
2905
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002906static llvm::GlobalVariable *
2907GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
2908 CodeGenModule &CGM, StringRef GlobalName,
2909 unsigned Alignment) {
2910 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2911 unsigned AddrSpace = 0;
2912 if (CGM.getLangOpts().OpenCL)
2913 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2914
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002915 llvm::Module &M = CGM.getModule();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002916 // Create a global variable for this string
2917 auto *GV = new llvm::GlobalVariable(
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002918 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
2919 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002920 GV->setAlignment(Alignment);
2921 GV->setUnnamedAddr(true);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002922 if (GV->isWeakForLinker()) {
2923 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
2924 GV->setComdat(M.getOrInsertComdat(GV->getName()));
2925 }
2926
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002927 return GV;
2928}
2929
Daniel Dunbar61432932008-08-13 23:20:05 +00002930/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2931/// constant array for the given string literal.
Stephen Hines176edba2014-12-01 14:53:08 -08002932llvm::GlobalVariable *
2933CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
2934 StringRef Name) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002935 auto Alignment =
2936 getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
Stephen Hines651f13c2014-04-23 16:59:28 -07002937
Stephen Hines176edba2014-12-01 14:53:08 -08002938 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2939 llvm::GlobalVariable **Entry = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07002940 if (!LangOpts.WritableStrings) {
Stephen Hines176edba2014-12-01 14:53:08 -08002941 Entry = &ConstantStringMap[C];
2942 if (auto GV = *Entry) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002943 if (Alignment > GV->getAlignment())
2944 GV->setAlignment(Alignment);
2945 return GV;
Stephen Hines651f13c2014-04-23 16:59:28 -07002946 }
Eli Friedman7eb79c12009-11-16 05:55:46 +00002947 }
Eli Friedman64f45a22011-11-01 02:23:42 +00002948
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002949 SmallString<256> MangledNameBuffer;
2950 StringRef GlobalVariableName;
2951 llvm::GlobalValue::LinkageTypes LT;
Seth Cantrell7d6a7c02012-01-18 12:11:32 +00002952
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002953 // Mangle the string literal if the ABI allows for it. However, we cannot
2954 // do this if we are compiling with ASan or -fwritable-strings because they
2955 // rely on strings having normal linkage.
Stephen Hines176edba2014-12-01 14:53:08 -08002956 if (!LangOpts.WritableStrings &&
2957 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002958 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2959 llvm::raw_svector_ostream Out(MangledNameBuffer);
2960 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2961 Out.flush();
Stephen Hines651f13c2014-04-23 16:59:28 -07002962
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002963 LT = llvm::GlobalValue::LinkOnceODRLinkage;
2964 GlobalVariableName = MangledNameBuffer;
2965 } else {
2966 LT = llvm::GlobalValue::PrivateLinkage;
Stephen Hines176edba2014-12-01 14:53:08 -08002967 GlobalVariableName = Name;
Stephen Hines651f13c2014-04-23 16:59:28 -07002968 }
2969
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002970 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
2971 if (Entry)
Stephen Hines176edba2014-12-01 14:53:08 -08002972 *Entry = GV;
Stephen Hines651f13c2014-04-23 16:59:28 -07002973
Stephen Hines176edba2014-12-01 14:53:08 -08002974 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
2975 QualType());
Eli Friedman64f45a22011-11-01 02:23:42 +00002976 return GV;
Daniel Dunbar61432932008-08-13 23:20:05 +00002977}
2978
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002979/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2980/// array for the given ObjCEncodeExpr node.
Stephen Hines176edba2014-12-01 14:53:08 -08002981llvm::GlobalVariable *
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002982CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2983 std::string Str;
2984 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00002985
2986 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002987}
2988
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002989/// GetAddrOfConstantCString - Returns a pointer to a character array containing
2990/// the literal and a terminating '\0' character.
2991/// The result has pointer to array type.
Stephen Hines176edba2014-12-01 14:53:08 -08002992llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
2993 const std::string &Str, const char *GlobalName, unsigned Alignment) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002994 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002995 if (Alignment == 0) {
2996 Alignment = getContext()
2997 .getAlignOfGlobalVarInChars(getContext().CharTy)
2998 .getQuantity();
2999 }
3000
Stephen Hines176edba2014-12-01 14:53:08 -08003001 llvm::Constant *C =
3002 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3003
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003004 // Don't share any string literals if strings aren't constant.
Stephen Hines176edba2014-12-01 14:53:08 -08003005 llvm::GlobalVariable **Entry = nullptr;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003006 if (!LangOpts.WritableStrings) {
Stephen Hines176edba2014-12-01 14:53:08 -08003007 Entry = &ConstantStringMap[C];
3008 if (auto GV = *Entry) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003009 if (Alignment > GV->getAlignment())
3010 GV->setAlignment(Alignment);
3011 return GV;
3012 }
3013 }
3014
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003015 // Get the default prefix if a name wasn't specified.
3016 if (!GlobalName)
3017 GlobalName = ".str";
3018 // Create a global variable for this.
3019 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3020 GlobalName, Alignment);
3021 if (Entry)
Stephen Hines176edba2014-12-01 14:53:08 -08003022 *Entry = GV;
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003023 return GV;
Daniel Dunbar61432932008-08-13 23:20:05 +00003024}
Daniel Dunbar41071de2008-08-15 23:26:23 +00003025
Richard Smith211c8dd2013-06-05 00:46:14 +00003026llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smith3282b842013-06-14 03:07:01 +00003027 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smith211c8dd2013-06-05 00:46:14 +00003028 assert((E->getStorageDuration() == SD_Static ||
3029 E->getStorageDuration() == SD_Thread) && "not a global temporary");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003030 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
Richard Smith211c8dd2013-06-05 00:46:14 +00003031
3032 // If we're not materializing a subobject of the temporary, keep the
3033 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smith3282b842013-06-14 03:07:01 +00003034 QualType MaterializedType = Init->getType();
3035 if (Init == E->GetTemporaryExpr())
3036 MaterializedType = E->getType();
Richard Smith211c8dd2013-06-05 00:46:14 +00003037
3038 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
3039 if (Slot)
3040 return Slot;
3041
3042 // FIXME: If an externally-visible declaration extends multiple temporaries,
3043 // we need to give each temporary the same name in every translation unit (and
3044 // we also need to make the temporaries externally-visible).
3045 SmallString<256> Name;
3046 llvm::raw_svector_ostream Out(Name);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003047 getCXXABI().getMangleContext().mangleReferenceTemporary(
3048 VD, E->getManglingNumber(), Out);
Richard Smith211c8dd2013-06-05 00:46:14 +00003049 Out.flush();
3050
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003051 APValue *Value = nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00003052 if (E->getStorageDuration() == SD_Static) {
Richard Smith3282b842013-06-14 03:07:01 +00003053 // We might have a cached constant initializer for this temporary. Note
3054 // that this might have a different value from the value computed by
3055 // evaluating the initializer if the surrounding constant expression
3056 // modifies the temporary.
Richard Smith211c8dd2013-06-05 00:46:14 +00003057 Value = getContext().getMaterializedTemporaryValue(E, false);
3058 if (Value && Value->isUninit())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003059 Value = nullptr;
Richard Smith211c8dd2013-06-05 00:46:14 +00003060 }
3061
Richard Smith3282b842013-06-14 03:07:01 +00003062 // Try evaluating it now, it might have a constant initializer.
3063 Expr::EvalResult EvalResult;
3064 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3065 !EvalResult.hasSideEffects())
3066 Value = &EvalResult.Val;
3067
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003068 llvm::Constant *InitialValue = nullptr;
Richard Smith3282b842013-06-14 03:07:01 +00003069 bool Constant = false;
3070 llvm::Type *Type;
Richard Smith211c8dd2013-06-05 00:46:14 +00003071 if (Value) {
3072 // The temporary has a constant initializer, use it.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003073 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
Richard Smith3282b842013-06-14 03:07:01 +00003074 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3075 Type = InitialValue->getType();
Richard Smith211c8dd2013-06-05 00:46:14 +00003076 } else {
Richard Smith3282b842013-06-14 03:07:01 +00003077 // No initializer, the initialization will be provided when we
Richard Smith211c8dd2013-06-05 00:46:14 +00003078 // initialize the declaration which performed lifetime extension.
Richard Smith3282b842013-06-14 03:07:01 +00003079 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smith211c8dd2013-06-05 00:46:14 +00003080 }
3081
3082 // Create a global variable for this lifetime-extended temporary.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003083 llvm::GlobalValue::LinkageTypes Linkage =
3084 getLLVMLinkageVarDefinition(VD, Constant);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003085 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3086 const VarDecl *InitVD;
3087 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3088 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3089 // Temporaries defined inside a class get linkonce_odr linkage because the
3090 // class can be defined in multipe translation units.
3091 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3092 } else {
3093 // There is no need for this temporary to have external linkage if the
3094 // VarDecl has external linkage.
3095 Linkage = llvm::GlobalVariable::InternalLinkage;
3096 }
3097 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003098 unsigned AddrSpace = GetGlobalVarAddressSpace(
3099 VD, getContext().getTargetAddressSpace(MaterializedType));
3100 auto *GV = new llvm::GlobalVariable(
3101 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3102 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3103 AddrSpace);
3104 setGlobalVisibility(GV, VD);
Richard Smith211c8dd2013-06-05 00:46:14 +00003105 GV->setAlignment(
Richard Smith3282b842013-06-14 03:07:01 +00003106 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003107 if (supportsCOMDAT() && GV->isWeakForLinker())
3108 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
Richard Smith211c8dd2013-06-05 00:46:14 +00003109 if (VD->getTLSKind())
3110 setTLSMode(GV, *VD);
3111 Slot = GV;
3112 return GV;
3113}
3114
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003115/// EmitObjCPropertyImplementations - Emit information for synthesized
3116/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00003117void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003118 ObjCImplementationDecl *D) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003119 for (const auto *PID : D->property_impls()) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003120 // Dynamic is just for type-checking.
3121 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3122 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3123
3124 // Determine which methods need to be implemented, some may have
Jordan Rose1e4691b2012-10-10 16:42:25 +00003125 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003126 // we want, that just indicates if the decl came from a
3127 // property. What we want to know is if the method is defined in
3128 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003129 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00003130 CodeGenFunction(*this).GenerateObjCGetter(
3131 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003132 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003133 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00003134 CodeGenFunction(*this).GenerateObjCSetter(
3135 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003136 }
3137 }
3138}
3139
John McCalle81ac692011-03-22 07:05:39 +00003140static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00003141 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3142 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00003143 ivar; ivar = ivar->getNextIvar())
3144 if (ivar->getType().isDestructedType())
3145 return true;
3146
3147 return false;
3148}
3149
Stephen Hines176edba2014-12-01 14:53:08 -08003150static bool AllTrivialInitializers(CodeGenModule &CGM,
3151 ObjCImplementationDecl *D) {
3152 CodeGenFunction CGF(CGM);
3153 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3154 E = D->init_end(); B != E; ++B) {
3155 CXXCtorInitializer *CtorInitExp = *B;
3156 Expr *Init = CtorInitExp->getInit();
3157 if (!CGF.isTrivialInitializer(Init))
3158 return false;
3159 }
3160 return true;
3161}
3162
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003163/// EmitObjCIvarInitializations - Emit information for ivar initialization
3164/// for an implementation.
3165void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00003166 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3167 if (needsDestructMethod(D)) {
3168 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3169 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3170 ObjCMethodDecl *DTORMethod =
3171 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003172 cxxSelector, getContext().VoidTy, nullptr, D,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003173 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00003174 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003175 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCalle81ac692011-03-22 07:05:39 +00003176 D->addInstanceMethod(DTORMethod);
3177 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallb03527a2012-10-17 04:53:31 +00003178 D->setHasDestructors(true);
John McCalle81ac692011-03-22 07:05:39 +00003179 }
3180
3181 // If the implementation doesn't have any ivar initializers, we don't need
3182 // a .cxx_construct.
Stephen Hines176edba2014-12-01 14:53:08 -08003183 if (D->getNumIvarInitializers() == 0 ||
3184 AllTrivialInitializers(*this, D))
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003185 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003186
John McCalle81ac692011-03-22 07:05:39 +00003187 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3188 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003189 // The constructor returns 'self'.
3190 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3191 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00003192 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00003193 cxxSelector,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003194 getContext().getObjCIdType(),
3195 nullptr, D, /*isInstance=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003196 /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00003197 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00003198 /*isImplicitlyDeclared=*/true,
3199 /*isDefined=*/false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003200 ObjCMethodDecl::Required);
3201 D->addInstanceMethod(CTORMethod);
3202 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallb03527a2012-10-17 04:53:31 +00003203 D->setHasNonZeroConstructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003204}
3205
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003206/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00003207void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003208 for (auto *I : ND->decls()) {
3209 if (const auto *VD = dyn_cast<VarDecl>(I))
David Blaikie0d520f72013-09-04 21:07:37 +00003210 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3211 VD->getTemplateSpecializationKind() != TSK_Undeclared)
3212 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07003213 EmitTopLevelDecl(I);
David Blaikie0d520f72013-09-04 21:07:37 +00003214 }
Anders Carlsson984e0682009-04-01 00:58:25 +00003215}
3216
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003217// EmitLinkageSpec - Emit all declarations in a linkage spec.
3218void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00003219 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3220 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003221 ErrorUnsupported(LSD, "linkage spec");
3222 return;
3223 }
3224
Stephen Hines651f13c2014-04-23 16:59:28 -07003225 for (auto *I : LSD->decls()) {
Fariborz Jahanian107dae42012-10-26 22:20:25 +00003226 // Meta-data for ObjC class includes references to implemented methods.
3227 // Generate class's method definitions first.
Stephen Hines651f13c2014-04-23 16:59:28 -07003228 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3229 for (auto *M : OID->methods())
3230 EmitTopLevelDecl(M);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00003231 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003232 EmitTopLevelDecl(I);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00003233 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003234}
3235
Daniel Dunbar41071de2008-08-15 23:26:23 +00003236/// EmitTopLevelDecl - Emit code for a single top level declaration.
3237void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor16e8be22009-06-29 17:30:29 +00003238 // Ignore dependent declarations.
3239 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3240 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Daniel Dunbar41071de2008-08-15 23:26:23 +00003242 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00003243 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00003244 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00003245 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00003246 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00003247 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3248 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00003249 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003250
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003251 EmitGlobal(cast<FunctionDecl>(D));
Stephen Hines176edba2014-12-01 14:53:08 -08003252 // Always provide some coverage mapping
3253 // even for the functions that aren't emitted.
3254 AddDeferredUnusedCoverageMapping(D);
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003255 break;
Larisse Voufoef4579c2013-08-06 01:03:05 +00003256
Daniel Dunbar41071de2008-08-15 23:26:23 +00003257 case Decl::Var:
Larisse Voufoef4579c2013-08-06 01:03:05 +00003258 // Skip variable templates
3259 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3260 return;
3261 case Decl::VarTemplateSpecialization:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00003262 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003263 break;
3264
John McCall26fbc722011-04-12 01:01:22 +00003265 // Indirect fields from global anonymous structs and unions can be
3266 // ignored; only the actual variable requires IR gen support.
3267 case Decl::IndirectField:
3268 break;
3269
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003270 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00003271 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00003272 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003273 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003274 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00003275 case Decl::UsingShadow:
Douglas Gregor127102b2009-06-29 20:59:39 +00003276 case Decl::ClassTemplate:
Larisse Voufoef4579c2013-08-06 01:03:05 +00003277 case Decl::VarTemplate:
3278 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor127102b2009-06-29 20:59:39 +00003279 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00003280 case Decl::TypeAliasTemplate:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00003281 case Decl::Block:
Michael Han684aa732013-02-22 17:15:32 +00003282 case Decl::Empty:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00003283 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003284 case Decl::Using: // using X; [C++]
3285 if (CGDebugInfo *DI = getModuleDebugInfo())
3286 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3287 return;
David Blaikiefc46ebc2013-05-20 22:50:41 +00003288 case Decl::NamespaceAlias:
3289 if (CGDebugInfo *DI = getModuleDebugInfo())
3290 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3291 return;
David Blaikie1601a4a2013-04-26 05:41:06 +00003292 case Decl::UsingDirective: // using namespace X; [C++]
3293 if (CGDebugInfo *DI = getModuleDebugInfo())
3294 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3295 return;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003296 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00003297 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00003298 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3299 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00003300 return;
3301
Timur Iskhodzhanovbb1b7972013-08-04 17:30:04 +00003302 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003303 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00003304 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00003305 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3306 return;
Reid Klecknera4130ba2013-07-22 13:51:44 +00003307 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlsson27ae5362009-04-17 01:58:57 +00003308 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00003309
3310 case Decl::StaticAssert:
3311 // Nothing to do.
3312 break;
3313
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00003314 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00003315
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00003316 // Forward declarations, no (immediate) code generation.
Chris Lattner285d0db2009-04-01 02:36:43 +00003317 case Decl::ObjCInterface:
Eric Christopherffb0c3a2012-07-19 22:22:55 +00003318 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00003319 break;
3320
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003321 case Decl::ObjCProtocol: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003322 auto *Proto = cast<ObjCProtocolDecl>(D);
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003323 if (Proto->isThisDeclarationADefinition())
3324 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbar41071de2008-08-15 23:26:23 +00003325 break;
Douglas Gregorbd9482d2012-01-01 21:23:57 +00003326 }
3327
Daniel Dunbar41071de2008-08-15 23:26:23 +00003328 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003329 // Categories have properties but don't support synthesize so we
3330 // can ignore them here.
Peter Collingbournee9265232011-07-27 20:29:46 +00003331 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003332 break;
3333
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003334 case Decl::ObjCImplementation: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003335 auto *OMD = cast<ObjCImplementationDecl>(D);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00003336 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00003337 EmitObjCIvarInitializations(OMD);
Peter Collingbournee9265232011-07-27 20:29:46 +00003338 ObjCRuntime->GenerateClass(OMD);
Eric Christopherbe6c6862012-04-11 05:56:05 +00003339 // Emit global variable debug information.
3340 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov96a66392012-12-03 18:28:12 +00003341 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3342 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3343 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbar41071de2008-08-15 23:26:23 +00003344 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003345 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00003346 case Decl::ObjCMethod: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003347 auto *OMD = cast<ObjCMethodDecl>(D);
Daniel Dunbar41071de2008-08-15 23:26:23 +00003348 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003349 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00003350 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3351 break;
3352 }
Mike Stump1eb44332009-09-09 15:08:12 +00003353 case Decl::ObjCCompatibleAlias:
David Chisnall29254f42012-01-31 18:59:20 +00003354 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003355 break;
3356
Anders Carlsson91e20dd2009-04-02 05:55:18 +00003357 case Decl::LinkageSpec:
3358 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00003359 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00003360
3361 case Decl::FileScopeAsm: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003362 auto *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner5f9e2722011-07-23 10:55:15 +00003363 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Daniel Dunbar41071de2008-08-15 23:26:23 +00003365 const std::string &S = getModule().getModuleInlineAsm();
3366 if (S.empty())
3367 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8ce9cca2012-08-10 10:57:52 +00003368 else if (S.end()[-1] == '\n')
Chris Lattner9f5bff02011-07-23 20:04:25 +00003369 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00003370 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00003371 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00003372 break;
3373 }
Mike Stump1eb44332009-09-09 15:08:12 +00003374
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003375 case Decl::Import: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003376 auto *Import = cast<ImportDecl>(D);
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003377
3378 // Ignore import declarations that come from imported modules.
3379 if (clang::Module *Owner = Import->getOwningModule()) {
3380 if (getLangOpts().CurrentModule.empty() ||
3381 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3382 break;
3383 }
3384
Douglas Gregor858afb32013-01-14 20:53:57 +00003385 ImportedModules.insert(Import->getImportedModule());
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003386 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003387 }
3388
Stephen Hines176edba2014-12-01 14:53:08 -08003389 case Decl::OMPThreadPrivate:
3390 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3391 break;
3392
Stephen Hines651f13c2014-04-23 16:59:28 -07003393 case Decl::ClassTemplateSpecialization: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003394 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
Stephen Hines651f13c2014-04-23 16:59:28 -07003395 if (DebugInfo &&
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003396 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3397 Spec->hasDefinition())
Stephen Hines651f13c2014-04-23 16:59:28 -07003398 DebugInfo->completeTemplateDefinition(*Spec);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003399 break;
Stephen Hines651f13c2014-04-23 16:59:28 -07003400 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00003401
Mike Stump1eb44332009-09-09 15:08:12 +00003402 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00003403 // Make sure we handled everything we should, every other kind is a
3404 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3405 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00003406 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003407 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00003408 }
3409}
John McCall744016d2010-07-06 23:57:41 +00003410
Stephen Hines176edba2014-12-01 14:53:08 -08003411void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3412 // Do we need to generate coverage mapping?
3413 if (!CodeGenOpts.CoverageMapping)
3414 return;
3415 switch (D->getKind()) {
3416 case Decl::CXXConversion:
3417 case Decl::CXXMethod:
3418 case Decl::Function:
3419 case Decl::ObjCMethod:
3420 case Decl::CXXConstructor:
3421 case Decl::CXXDestructor: {
3422 if (!cast<FunctionDecl>(D)->hasBody())
3423 return;
3424 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3425 if (I == DeferredEmptyCoverageMappingDecls.end())
3426 DeferredEmptyCoverageMappingDecls[D] = true;
3427 break;
3428 }
3429 default:
3430 break;
3431 };
3432}
3433
3434void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3435 // Do we need to generate coverage mapping?
3436 if (!CodeGenOpts.CoverageMapping)
3437 return;
3438 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3439 if (Fn->isTemplateInstantiation())
3440 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3441 }
3442 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3443 if (I == DeferredEmptyCoverageMappingDecls.end())
3444 DeferredEmptyCoverageMappingDecls[D] = false;
3445 else
3446 I->second = false;
3447}
3448
3449void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3450 std::vector<const Decl *> DeferredDecls;
3451 for (const auto I : DeferredEmptyCoverageMappingDecls) {
3452 if (!I.second)
3453 continue;
3454 DeferredDecls.push_back(I.first);
3455 }
3456 // Sort the declarations by their location to make sure that the tests get a
3457 // predictable order for the coverage mapping for the unused declarations.
3458 if (CodeGenOpts.DumpCoverageMapping)
3459 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3460 [] (const Decl *LHS, const Decl *RHS) {
3461 return LHS->getLocStart() < RHS->getLocStart();
3462 });
3463 for (const auto *D : DeferredDecls) {
3464 switch (D->getKind()) {
3465 case Decl::CXXConversion:
3466 case Decl::CXXMethod:
3467 case Decl::Function:
3468 case Decl::ObjCMethod: {
3469 CodeGenPGO PGO(*this);
3470 GlobalDecl GD(cast<FunctionDecl>(D));
3471 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3472 getFunctionLinkage(GD));
3473 break;
3474 }
3475 case Decl::CXXConstructor: {
3476 CodeGenPGO PGO(*this);
3477 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3478 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3479 getFunctionLinkage(GD));
3480 break;
3481 }
3482 case Decl::CXXDestructor: {
3483 CodeGenPGO PGO(*this);
3484 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3485 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3486 getFunctionLinkage(GD));
3487 break;
3488 }
3489 default:
3490 break;
3491 };
3492 }
3493}
3494
John McCall744016d2010-07-06 23:57:41 +00003495/// Turns the given pointer into a constant.
3496static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3497 const void *Ptr) {
3498 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00003499 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall744016d2010-07-06 23:57:41 +00003500 return llvm::ConstantInt::get(i64, PtrInt);
3501}
3502
3503static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3504 llvm::NamedMDNode *&GlobalMetadata,
3505 GlobalDecl D,
3506 llvm::GlobalValue *Addr) {
3507 if (!GlobalMetadata)
3508 GlobalMetadata =
3509 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3510
3511 // TODO: should we report variant information for ctors/dtors?
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003512 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3513 llvm::ConstantAsMetadata::get(GetPointerConstant(
3514 CGM.getLLVMContext(), D.getDecl()))};
Jay Foad6f141652011-04-21 19:59:12 +00003515 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00003516}
3517
Richard Smith00249372013-04-06 05:00:46 +00003518/// For each function which is declared within an extern "C" region and marked
3519/// as 'used', but has internal linkage, create an alias from the unmangled
3520/// name to the mangled name if possible. People expect to be able to refer
3521/// to such functions with an unmangled name from inline assembly within the
3522/// same translation unit.
3523void CodeGenModule::EmitStaticExternCAliases() {
Richard Smith84083b72013-04-13 01:28:18 +00003524 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3525 E = StaticExternCValues.end();
3526 I != E; ++I) {
3527 IdentifierInfo *Name = I->first;
3528 llvm::GlobalValue *Val = I->second;
Richard Smith67972042013-04-06 07:07:44 +00003529 if (Val && !getModule().getNamedValue(Name->getName()))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003530 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
Richard Smith67972042013-04-06 07:07:44 +00003531 }
Richard Smith00249372013-04-06 05:00:46 +00003532}
3533
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003534bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3535 GlobalDecl &Result) const {
3536 auto Res = Manglings.find(MangledName);
3537 if (Res == Manglings.end())
3538 return false;
3539 Result = Res->getValue();
3540 return true;
3541}
3542
John McCall744016d2010-07-06 23:57:41 +00003543/// Emits metadata nodes associating all the global values in the
3544/// current module with the Decls they came from. This is useful for
3545/// projects using IR gen as a subroutine.
3546///
3547/// Since there's currently no way to associate an MDNode directly
3548/// with an llvm::GlobalValue, we create a global named metadata
3549/// with the name 'clang.global.decl.ptrs'.
3550void CodeGenModule::EmitDeclMetadata() {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003551 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall744016d2010-07-06 23:57:41 +00003552
3553 // StaticLocalDeclMap
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003554 for (auto &I : MangledDeclNames) {
3555 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3556 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
John McCall744016d2010-07-06 23:57:41 +00003557 }
3558}
3559
3560/// Emits metadata nodes for all the local variables in the current
3561/// function.
3562void CodeGenFunction::EmitDeclMetadata() {
3563 if (LocalDeclMap.empty()) return;
3564
3565 llvm::LLVMContext &Context = getLLVMContext();
3566
3567 // Find the unique metadata ID for this name.
3568 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3569
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003570 llvm::NamedMDNode *GlobalMetadata = nullptr;
John McCall744016d2010-07-06 23:57:41 +00003571
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003572 for (auto &I : LocalDeclMap) {
3573 const Decl *D = I.first;
3574 llvm::Value *Addr = I.second;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003575 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
John McCall744016d2010-07-06 23:57:41 +00003576 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003577 Alloca->setMetadata(
3578 DeclPtrKind, llvm::MDNode::get(
3579 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003580 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
John McCall744016d2010-07-06 23:57:41 +00003581 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3582 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3583 }
3584 }
3585}
Daniel Dunbar673431a2010-07-16 00:00:15 +00003586
Rafael Espindola9686f122013-10-16 19:28:50 +00003587void CodeGenModule::EmitVersionIdentMetadata() {
3588 llvm::NamedMDNode *IdentMetadata =
3589 TheModule.getOrInsertNamedMetadata("llvm.ident");
3590 std::string Version = getClangFullVersion();
3591 llvm::LLVMContext &Ctx = TheModule.getContext();
3592
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003593 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
Rafael Espindola9686f122013-10-16 19:28:50 +00003594 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3595}
3596
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003597void CodeGenModule::EmitTargetMetadata() {
Stephen Hines176edba2014-12-01 14:53:08 -08003598 // Warning, new MangledDeclNames may be appended within this loop.
3599 // We rely on MapVector insertions adding new elements to the end
3600 // of the container.
3601 // FIXME: Move this loop into the one target that needs it, and only
3602 // loop over those declarations for which we couldn't emit the target
3603 // metadata when we emitted the declaration.
3604 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3605 auto Val = *(MangledDeclNames.begin() + I);
3606 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3607 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003608 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3609 }
3610}
3611
Nick Lewycky3dc05412011-05-05 00:08:20 +00003612void CodeGenModule::EmitCoverageFile() {
3613 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00003614 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3615 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3616 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00003617 llvm::MDString *CoverageFile =
3618 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00003619 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3620 llvm::MDNode *CU = CUNode->getOperand(i);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003621 llvm::Metadata *Elts[] = {CoverageFile, CU};
3622 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
Nick Lewycky5ea4f442011-05-04 20:46:58 +00003623 }
3624 }
3625 }
3626}
Nico Weberc5f80462012-10-11 10:13:44 +00003627
Stephen Hines176edba2014-12-01 14:53:08 -08003628llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
Nico Weberc5f80462012-10-11 10:13:44 +00003629 // Sema has checked that all uuid strings are of the form
3630 // "12345678-1234-1234-1234-1234567890ab".
3631 assert(Uuid.size() == 36);
David Majnemer8effeda2013-08-15 19:59:14 +00003632 for (unsigned i = 0; i < 36; ++i) {
3633 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3634 else assert(isHexDigit(Uuid[i]));
Nico Weberc5f80462012-10-11 10:13:44 +00003635 }
Nico Weberc5f80462012-10-11 10:13:44 +00003636
Stephen Hines176edba2014-12-01 14:53:08 -08003637 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
David Majnemer8effeda2013-08-15 19:59:14 +00003638 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Weberc5f80462012-10-11 10:13:44 +00003639
David Majnemer8effeda2013-08-15 19:59:14 +00003640 llvm::Constant *Field3[8];
3641 for (unsigned Idx = 0; Idx < 8; ++Idx)
3642 Field3[Idx] = llvm::ConstantInt::get(
3643 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3644
3645 llvm::Constant *Fields[4] = {
3646 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3647 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3648 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3649 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3650 };
3651
3652 return llvm::ConstantStruct::getAnon(Fields);
Nico Weberc5f80462012-10-11 10:13:44 +00003653}
Stephen Hinesc568f1e2014-07-21 00:47:37 -07003654
3655llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3656 bool ForEH) {
3657 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3658 // FIXME: should we even be calling this method if RTTI is disabled
3659 // and it's not for EH?
3660 if (!ForEH && !getLangOpts().RTTI)
3661 return llvm::Constant::getNullValue(Int8PtrTy);
3662
3663 if (ForEH && Ty->isObjCObjectPointerType() &&
3664 LangOpts.ObjCRuntime.isGNUFamily())
3665 return ObjCRuntime->GetEHType(Ty);
3666
3667 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3668}
3669
Stephen Hines176edba2014-12-01 14:53:08 -08003670void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3671 for (auto RefExpr : D->varlists()) {
3672 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3673 bool PerformInit =
3674 VD->getAnyInitializer() &&
3675 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3676 /*ForRef=*/false);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003677 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
3678 VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
Stephen Hines176edba2014-12-01 14:53:08 -08003679 CXXGlobalInits.push_back(InitFunction);
3680 }
3681}
3682