blob: 98588a4122ef1d99bc5864abdf695a977518390a [file] [log] [blame]
Chris Lattnerbed31442007-05-28 01:07:47 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerbed31442007-05-28 01:07:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Peter Collingbournefe883422011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall5d865c322010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne2dbb7082011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenFunction.h"
Justin Bogneref512b92014-01-06 22:27:43 +000022#include "CodeGenPGO.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000023#include "CodeGenTBAA.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000024#include "TargetInfo.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000025#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000026#include "clang/AST/CharUnits.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000027#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/AST/DeclObjC.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000029#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000030#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000031#include "clang/AST/RecordLayout.h"
Rafael Espindolac5941352011-10-26 20:41:06 +000032#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindola4fdc1752011-12-19 14:41:01 +000033#include "clang/Basic/Builtins.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000034#include "clang/Basic/CharInfo.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000035#include "clang/Basic/Diagnostic.h"
Douglas Gregor6ddfca92013-01-14 17:21:00 +000036#include "clang/Basic/Module.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000037#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000038#include "clang/Basic/TargetInfo.h"
Rafael Espindola3bfa4682013-10-16 19:28:50 +000039#include "clang/Basic/Version.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "clang/Frontend/CodeGenOptions.h"
Rafael Espindola208b5c02013-10-22 19:26:13 +000041#include "clang/Sema/SemaDiagnostic.h"
Sebastian Redl4a7eab22012-02-25 20:51:20 +000042#include "llvm/ADT/APSInt.h"
John McCallbeec5a02010-03-06 00:35:14 +000043#include "llvm/ADT/Triple.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000044#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000045#include "llvm/IR/CallingConv.h"
46#include "llvm/IR/DataLayout.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/LLVMContext.h"
49#include "llvm/IR/Module.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000050#include "llvm/Support/ConvertUTF.h"
Chris Lattner15275e52009-11-07 09:22:46 +000051#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000052
Chris Lattnerbed31442007-05-28 01:07:47 +000053using namespace clang;
54using namespace CodeGen;
55
Julien Lerouge5a6b6982011-09-09 22:41:49 +000056static const char AnnotationSection[] = "llvm.metadata";
57
Alp Toker82862252013-12-28 21:58:40 +000058static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
John McCallc8e01702013-04-16 22:48:15 +000059 switch (CGM.getTarget().getCXXABI().getKind()) {
Tim Northover9bb857a2013-01-31 12:13:10 +000060 case TargetCXXABI::GenericAArch64:
John McCall57625922013-01-25 23:36:14 +000061 case TargetCXXABI::GenericARM:
62 case TargetCXXABI::iOS:
63 case TargetCXXABI::GenericItanium:
Alp Toker82862252013-12-28 21:58:40 +000064 return CreateItaniumCXXABI(CGM);
John McCall57625922013-01-25 23:36:14 +000065 case TargetCXXABI::Microsoft:
Alp Toker82862252013-12-28 21:58:40 +000066 return CreateMicrosoftCXXABI(CGM);
John McCall614dbdc2010-08-22 21:01:12 +000067 }
68
69 llvm_unreachable("invalid C++ ABI kind");
John McCall614dbdc2010-08-22 21:01:12 +000070}
71
Chandler Carruthbc55fe22009-11-12 17:24:48 +000072CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall568d4102013-04-16 22:48:20 +000073 llvm::Module &M, const llvm::DataLayout &TD,
David Blaikie9c902b52011-09-25 23:23:43 +000074 DiagnosticsEngine &diags)
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000075 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
76 Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
77 ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
78 TheTargetCodeGenInfo(0), Types(*this), VTables(*this), ObjCRuntime(0),
79 OpenCLRuntime(0), CUDARuntime(0), DebugInfo(0), ARCData(0),
Justin Bognerd66a17d2014-03-12 21:06:31 +000080 NoObjCARCExceptionsMetadata(0), RRData(0), PGOData(0),
Justin Bogneref512b92014-01-06 22:27:43 +000081 CFConstantStringClassRef(0),
Alexey Samsonovd6e043b2013-08-12 11:48:05 +000082 ConstantStringClassRef(0), NSConstantStringType(0),
83 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), BlockObjectAssign(0),
84 BlockObjectDispose(0), BlockDescriptorType(0), GenericBlockLiteralType(0),
85 LifetimeStartFn(0), LifetimeEndFn(0),
86 SanitizerBlacklist(
87 llvm::SpecialCaseList::createOrDie(CGO.SanitizerBlacklistFile)),
88 SanOpts(SanitizerBlacklist->isIn(M) ? SanitizerOptions::Disabled
89 : LangOpts.Sanitize) {
Will Dietzf54319c2013-01-18 11:30:38 +000090
Chris Lattnerece04092012-02-07 00:39:47 +000091 // Initialize the type cache.
92 llvm::LLVMContext &LLVMContext = M.getContext();
93 VoidTy = llvm::Type::getVoidTy(LLVMContext);
94 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
95 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
96 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
97 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
98 FloatTy = llvm::Type::getFloatTy(LLVMContext);
99 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
100 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
101 PointerAlignInBytes =
102 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
103 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
104 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
105 Int8PtrTy = Int8Ty->getPointerTo(0);
106 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
107
John McCall882987f2013-02-28 19:01:20 +0000108 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
109
David Blaikiebbafb8a2012-03-11 07:00:24 +0000110 if (LangOpts.ObjC1)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000111 createObjCRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000112 if (LangOpts.OpenCL)
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000113 createOpenCLRuntime();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000114 if (LangOpts.CUDA)
Peter Collingbournefe883422011-10-06 18:29:37 +0000115 createCUDARuntime();
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000116
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000117 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Will Dietzf54319c2013-01-18 11:30:38 +0000118 if (SanOpts.Thread ||
Kostya Serebryany5dd2cfc2012-04-24 06:57:01 +0000119 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
120 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Alp Toker82862252013-12-28 21:58:40 +0000121 getCXXABI().getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +0000122
Nick Lewycky207bce32011-04-21 23:44:07 +0000123 // If debug info or coverage generation is enabled, create the CGDebugInfo
124 // object.
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000125 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov486e1fe2012-04-27 07:24:20 +0000126 CodeGenOpts.EmitGcovArcs ||
Nick Lewycky207bce32011-04-21 23:44:07 +0000127 CodeGenOpts.EmitGcovNotes)
128 DebugInfo = new CGDebugInfo(*this);
John McCallad7c5c12011-02-08 08:22:06 +0000129
130 Block.GlobalUniqueCount = 0;
John McCalle3dc1702011-02-15 09:22:45 +0000131
David Blaikiebbafb8a2012-03-11 07:00:24 +0000132 if (C.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +0000133 ARCData = new ARCEntrypoints();
134 RRData = new RREntrypoints();
Justin Bogneref512b92014-01-06 22:27:43 +0000135
Justin Bognerd66a17d2014-03-12 21:06:31 +0000136 if (!CodeGenOpts.InstrProfileInput.empty())
137 PGOData = new PGOProfileData(*this, CodeGenOpts.InstrProfileInput);
Chris Lattnera087ff92008-03-01 08:45:05 +0000138}
139
140CodeGenModule::~CodeGenModule() {
Peter Collingbournee1d20992011-07-27 20:29:46 +0000141 delete ObjCRuntime;
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000142 delete OpenCLRuntime;
Peter Collingbournefe883422011-10-06 18:29:37 +0000143 delete CUDARuntime;
Ted Kremenekc168e502011-10-08 05:28:26 +0000144 delete TheTargetCodeGenInfo;
Dan Gohmand19ee8a2010-10-15 18:04:46 +0000145 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000146 delete DebugInfo;
John McCall31168b02011-06-15 23:02:42 +0000147 delete ARCData;
148 delete RRData;
Ted Kremenek2c674f62008-08-05 18:50:11 +0000149}
150
David Chisnall481e3a82010-01-23 02:40:42 +0000151void CodeGenModule::createObjCRuntime() {
John McCall5fb5df92012-06-20 06:18:46 +0000152 // This is just isGNUFamily(), but we want to force implementors of
153 // new ABIs to decide how best to do this.
154 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnallb601c962012-07-03 20:49:52 +0000155 case ObjCRuntime::GNUstep:
156 case ObjCRuntime::GCC:
John McCall775086e2012-07-12 02:07:58 +0000157 case ObjCRuntime::ObjFW:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000158 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000159 return;
160
161 case ObjCRuntime::FragileMacOSX:
162 case ObjCRuntime::MacOSX:
163 case ObjCRuntime::iOS:
Peter Collingbournee1d20992011-07-27 20:29:46 +0000164 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall5fb5df92012-06-20 06:18:46 +0000165 return;
166 }
167 llvm_unreachable("bad runtime kind");
David Chisnall481e3a82010-01-23 02:40:42 +0000168}
169
Peter Collingbourne2dbb7082011-09-19 21:14:35 +0000170void CodeGenModule::createOpenCLRuntime() {
171 OpenCLRuntime = new CGOpenCLRuntime(*this);
172}
173
Peter Collingbournefe883422011-10-06 18:29:37 +0000174void CodeGenModule::createCUDARuntime() {
175 CUDARuntime = CreateNVCUDARuntime(*this);
176}
177
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000178void CodeGenModule::applyReplacements() {
179 for (ReplacementsTy::iterator I = Replacements.begin(),
180 E = Replacements.end();
181 I != E; ++I) {
182 StringRef MangledName = I->first();
183 llvm::Constant *Replacement = I->second;
184 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
185 if (!Entry)
186 continue;
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000187 llvm::Function *OldF = cast<llvm::Function>(Entry);
188 llvm::Function *NewF = dyn_cast<llvm::Function>(Replacement);
189 if (!NewF) {
Reid Klecknerb78257d2014-02-03 18:54:51 +0000190 if (llvm::GlobalAlias *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
191 NewF = dyn_cast<llvm::Function>(Alias->getAliasedGlobal());
192 } else {
193 llvm::ConstantExpr *CE = cast<llvm::ConstantExpr>(Replacement);
194 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
195 CE->getOpcode() == llvm::Instruction::GetElementPtr);
196 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
197 }
Rafael Espindola0196a1d2013-11-12 04:53:19 +0000198 }
199
200 // Replace old with new, but keep the old order.
201 OldF->replaceAllUsesWith(Replacement);
202 if (NewF) {
203 NewF->removeFromParent();
204 OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
205 }
206 OldF->eraseFromParent();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000207 }
208}
209
Rafael Espindola208b5c02013-10-22 19:26:13 +0000210void CodeGenModule::checkAliases() {
211 bool Error = false;
212 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
213 E = Aliases.end(); I != E; ++I) {
214 const GlobalDecl &GD = *I;
215 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
216 const AliasAttr *AA = D->getAttr<AliasAttr>();
217 StringRef MangledName = getMangledName(GD);
218 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
219 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
Rafael Espindola93c7a652014-03-13 15:47:50 +0000220 llvm::GlobalValue *GV = Alias->resolveAliasedGlobal(/*stopOnWeak*/ false);
221 if (!GV) {
Rafael Espindola208b5c02013-10-22 19:26:13 +0000222 Error = true;
223 getDiags().Report(AA->getLocation(), diag::err_cyclic_alias);
Rafael Espindola93c7a652014-03-13 15:47:50 +0000224 } else if (GV->isDeclaration()) {
225 Error = true;
226 getDiags().Report(AA->getLocation(), diag::err_alias_to_undefined);
Rafael Espindola208b5c02013-10-22 19:26:13 +0000227 }
228 }
229 if (!Error)
230 return;
231
232 for (std::vector<GlobalDecl>::iterator I = Aliases.begin(),
233 E = Aliases.end(); I != E; ++I) {
234 const GlobalDecl &GD = *I;
235 StringRef MangledName = getMangledName(GD);
236 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
237 llvm::GlobalAlias *Alias = cast<llvm::GlobalAlias>(Entry);
238 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
239 Alias->eraseFromParent();
240 }
241}
242
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000243void CodeGenModule::clear() {
244 DeferredDeclsToEmit.clear();
245}
246
Ted Kremenek2c674f62008-08-05 18:50:11 +0000247void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000248 EmitDeferred();
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000249 applyReplacements();
Rafael Espindola208b5c02013-10-22 19:26:13 +0000250 checkAliases();
Eli Friedman5866fe32010-01-08 00:50:11 +0000251 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000252 EmitCXXGlobalDtorFunc();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000253 EmitCXXThreadLocalInitFunc();
Peter Collingbournee1d20992011-07-27 20:29:46 +0000254 if (ObjCRuntime)
255 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar8d480592008-08-11 18:12:00 +0000256 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000257 EmitCtorList(GlobalCtors, "llvm.global_ctors");
258 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000259 EmitGlobalAnnotations();
Richard Smithdf931ce2013-04-06 05:00:46 +0000260 EmitStaticExternCAliases();
Rafael Espindola060062a2014-03-06 22:15:10 +0000261 emitLLVMUsed();
Douglas Gregorc60437f2013-01-16 01:23:41 +0000262
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000263 if (CodeGenOpts.Autolink &&
264 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
Douglas Gregorc60437f2013-01-16 01:23:41 +0000265 EmitModuleLinkOptions();
266 }
Manman Ren9691f7f2013-06-19 01:46:49 +0000267 if (CodeGenOpts.DwarfVersion)
268 // We actually want the latest version when there are conflicts.
269 // We can change from Warning to Latest if such mode is supported.
270 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
271 CodeGenOpts.DwarfVersion);
Manman Ren4b7f23d2013-11-22 19:42:45 +0000272 if (DebugInfo)
273 // We support a single version in the linked module: error out when
Manman Renba2fa8b2013-12-02 19:37:35 +0000274 // modules do not have the same version. We are going to implement dropping
275 // debug info when the version number is not up-to-date. Once that is
276 // done, the bitcode linker is not going to see modules with different
277 // version numbers.
Manman Ren4b7f23d2013-11-22 19:42:45 +0000278 getModule().addModuleFlag(llvm::Module::Error, "Debug Info Version",
Manman Ren61fd5942013-12-02 20:10:37 +0000279 llvm::DEBUG_METADATA_VERSION);
Douglas Gregorea02f262013-01-14 18:28:43 +0000280
John McCall0bdb1fd2010-09-16 06:16:50 +0000281 SimplifyPersonality();
282
John McCall09ae0322010-07-06 23:57:41 +0000283 if (getCodeGenOpts().EmitDeclMetadata)
284 EmitDeclMetadata();
Nick Lewycky480cb992011-05-04 20:46:58 +0000285
286 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky85c011d2011-05-05 00:08:20 +0000287 EmitCoverageFile();
Devang Patelffa30ab2011-08-16 20:58:22 +0000288
289 if (DebugInfo)
290 DebugInfo->finalize();
Rafael Espindola3bfa4682013-10-16 19:28:50 +0000291
292 EmitVersionIdentMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000293}
294
Devang Patel945b8ae2011-03-23 16:29:39 +0000295void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
296 // Make sure that this type is translated.
297 Types.UpdateCompletedType(TD);
Devang Patel945b8ae2011-03-23 16:29:39 +0000298}
299
Dan Gohman947c9af2010-10-14 23:06:10 +0000300llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
301 if (!TBAA)
302 return 0;
303 return TBAA->getTBAAInfo(QTy);
304}
305
Kostya Serebryany141e46f2012-03-26 17:03:51 +0000306llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
307 if (!TBAA)
308 return 0;
309 return TBAA->getTBAAInfoForVTablePtr();
310}
311
Dan Gohman22695fc2012-09-28 21:58:29 +0000312llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
313 if (!TBAA)
314 return 0;
315 return TBAA->getTBAAStructInfo(QTy);
316}
317
Manman Renc451e572013-04-04 21:53:22 +0000318llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
319 if (!TBAA)
320 return 0;
321 return TBAA->getTBAAStructTypeInfo(QTy);
322}
323
324llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
325 llvm::MDNode *AccessN,
326 uint64_t O) {
327 if (!TBAA)
328 return 0;
329 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
330}
331
Manman Ren4f755de2013-10-08 00:08:49 +0000332/// Decorate the instruction with a TBAA tag. For both scalar TBAA
333/// and struct-path aware TBAA, the tag has the same format:
334/// base type, access type and offset.
Manman Rene1ad74e2013-04-11 23:02:56 +0000335/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
Dan Gohman947c9af2010-10-14 23:06:10 +0000336void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
Manman Rene1ad74e2013-04-11 23:02:56 +0000337 llvm::MDNode *TBAAInfo,
338 bool ConvertTypeToTag) {
Manman Ren4f755de2013-10-08 00:08:49 +0000339 if (ConvertTypeToTag && TBAA)
Manman Rene1ad74e2013-04-11 23:02:56 +0000340 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
341 TBAA->getTBAAScalarTagInfo(TBAAInfo));
342 else
343 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
Dan Gohman947c9af2010-10-14 23:06:10 +0000344}
345
Alp Toker29cb66b2014-01-26 06:17:37 +0000346void CodeGenModule::Error(SourceLocation loc, StringRef message) {
347 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
348 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
John McCall7ef5cb32011-03-18 02:56:14 +0000349}
350
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000351/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000352/// specified stmt yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000353void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000354 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000355 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000356 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000357 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
358 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000359}
Chris Lattner41af8182007-12-02 06:27:33 +0000360
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000361/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000362/// specified decl yet.
David Blaikie4a9ec7b2013-08-19 21:02:26 +0000363void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
David Blaikie9c902b52011-09-25 23:23:43 +0000364 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000365 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000366 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000367 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000368}
369
John McCall23c29fe2011-06-24 21:55:10 +0000370llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
371 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
372}
373
Mike Stump11289f42009-09-09 15:08:12 +0000374void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000375 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000376 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000377 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000378 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000379 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000380 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000381
John McCallc273f242010-10-30 11:50:40 +0000382 // Set visibility for definitions.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000383 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000384 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
385 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000386}
387
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000388static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
389 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
390 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
391 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
392 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
393 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
394}
395
396static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
397 CodeGenOptions::TLSModel M) {
398 switch (M) {
399 case CodeGenOptions::GeneralDynamicTLSModel:
400 return llvm::GlobalVariable::GeneralDynamicTLSModel;
401 case CodeGenOptions::LocalDynamicTLSModel:
402 return llvm::GlobalVariable::LocalDynamicTLSModel;
403 case CodeGenOptions::InitialExecTLSModel:
404 return llvm::GlobalVariable::InitialExecTLSModel;
405 case CodeGenOptions::LocalExecTLSModel:
406 return llvm::GlobalVariable::LocalExecTLSModel;
407 }
408 llvm_unreachable("Invalid TLS model!");
409}
410
411void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
412 const VarDecl &D) const {
Richard Smithfd3834f2013-04-13 02:43:54 +0000413 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000414
415 llvm::GlobalVariable::ThreadLocalMode TLM;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000416 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000417
418 // Override the TLS model if it is explicitly specified.
Aaron Ballmanc4327992013-12-19 03:09:10 +0000419 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
Hans Wennborgf60f6af2012-06-28 08:01:44 +0000420 TLM = GetLLVMTLSModel(Attr->getModel());
421 }
422
423 GV->setThreadLocalMode(TLM);
424}
425
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000426StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000427 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
428
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000429 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000430 if (!Str.empty())
431 return Str;
432
John McCall5d865c322010-08-31 07:33:07 +0000433 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000434 IdentifierInfo *II = ND->getIdentifier();
435 assert(II && "Attempt to mangle unnamed decl.");
436
437 Str = II->getName();
438 return Str;
439 }
440
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000441 SmallString<256> Buffer;
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000442 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000443 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000444 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000445 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000446 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000447 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000448 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000449
450 // Allocate space for the mangled name.
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000451 Out.flush();
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000452 size_t Length = Buffer.size();
453 char *Name = MangledNamesAllocator.Allocate<char>(Length);
454 std::copy(Buffer.begin(), Buffer.end(), Name);
455
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456 Str = StringRef(Name, Length);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000457
458 return Str;
459}
460
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000461void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
462 const BlockDecl *BD) {
463 MangleContext &MangleCtx = getCXXABI().getMangleContext();
464 const Decl *D = GD.getDecl();
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000465 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000466 if (D == 0)
Fariborz Jahanian63628032012-06-26 16:06:38 +0000467 MangleCtx.mangleGlobalBlock(BD,
468 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000469 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000470 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000471 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000472 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000473 else
Rafael Espindolaac00f5d2011-02-10 23:59:36 +0000474 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson635186a2010-06-09 02:36:32 +0000475}
476
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000477llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCall7ec50432010-03-19 23:29:14 +0000478 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000479}
480
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000481/// AddGlobalCtor - Add a function to the list that will be called before
482/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000483void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000484 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000485 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000486}
487
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000488/// AddGlobalDtor - Add a function to the list that will be called
489/// when the module is unloaded.
490void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000491 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000492 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
493}
494
495void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
496 // Ctor function type is void()*.
John McCall9dc0db22011-05-15 01:53:33 +0000497 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000498 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000499
500 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000501 llvm::StructType *CtorStructTy =
Chris Lattnerece04092012-02-07 00:39:47 +0000502 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000503
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000504 // Construct the constructor and destructor arrays.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000505 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000506 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner3def9ae2012-02-06 22:16:34 +0000507 llvm::Constant *S[] = {
508 llvm::ConstantInt::get(Int32Ty, I->second, false),
509 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
510 };
Owen Anderson0e0189d2009-07-27 22:29:56 +0000511 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000512 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000513
514 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000515 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000516 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000517 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000518 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000519 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000520 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000521}
522
John McCalld4324142010-02-19 01:32:20 +0000523llvm::GlobalValue::LinkageTypes
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000524CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
Eli Friedmanc48d31c2013-07-01 20:53:07 +0000525 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
Reid Klecknere7de47e2013-07-22 13:51:44 +0000526
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000527 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000528
Chris Lattner749b8ed2010-06-30 16:58:07 +0000529 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000530 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000531
532 if (D->hasAttr<DLLExportAttr>())
Nico Rieckbb0554f2014-01-14 15:23:53 +0000533 return llvm::Function::ExternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000534
535 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000536 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000537
538 // In C99 mode, 'inline' functions are guaranteed to have a strong
539 // definition somewhere else, so we can use available_externally linkage.
540 if (Linkage == GVA_C99Inline)
Fariborz Jahanian7cadb2f2011-02-04 00:08:13 +0000541 return llvm::Function::AvailableExternallyLinkage;
John McCall28a5b322011-09-19 18:05:26 +0000542
543 // Note that Apple's kernel linker doesn't support symbol
544 // coalescing, so we need to avoid linkonce and weak linkages there.
545 // Normally, this means we just map to internal, but for explicit
546 // instantiations we'll map to external.
547
Chris Lattner749b8ed2010-06-30 16:58:07 +0000548 // In C++, the compiler has to emit a definition in every translation unit
549 // that references the function. We should use linkonce_odr because
550 // a) if all references in this translation unit are optimized away, we
551 // don't need to codegen it. b) if the function persists, it needs to be
552 // merged with other definitions. c) C++ has the ODR, so we know the
553 // definition is dependable.
554 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000555 return !Context.getLangOpts().AppleKext
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000556 ? llvm::Function::LinkOnceODRLinkage
557 : llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000558
559 // An explicit instantiation of a template has weak linkage, since
560 // explicit instantiations can occur in multiple translation units
561 // and must all be equivalent. However, we are not allowed to
562 // throw away these explicit instantiations.
563 if (Linkage == GVA_ExplicitTemplateInstantiation)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000564 return !Context.getLangOpts().AppleKext
Fariborz Jahanianf7f04452011-02-04 00:01:24 +0000565 ? llvm::Function::WeakODRLinkage
John McCall28a5b322011-09-19 18:05:26 +0000566 : llvm::Function::ExternalLinkage;
Reid Klecknera12cd282013-12-11 19:21:27 +0000567
568 // Destructor variants in the Microsoft C++ ABI are always linkonce_odr thunks
569 // emitted on an as-needed basis.
570 if (isa<CXXDestructorDecl>(D) &&
571 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
572 GD.getDtorType()))
573 return llvm::Function::LinkOnceODRLinkage;
574
Chris Lattner749b8ed2010-06-30 16:58:07 +0000575 // Otherwise, we have strong external linkage.
576 assert(Linkage == GVA_StrongExternal);
577 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000578}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000579
John McCalld4324142010-02-19 01:32:20 +0000580
581/// SetFunctionDefinitionAttributes - Set attributes for a global.
582///
583/// FIXME: This is currently only done for aliases and functions, but not for
584/// variables (these details are set in EmitGlobalVarDefinition for variables).
585void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
586 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000587 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000588}
589
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000590void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000591 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000592 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000593 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000594 AttributeListType AttributeList;
Bill Wendlingf4d64cb2013-02-22 00:13:35 +0000595 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling3087d022012-12-07 23:17:26 +0000596 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000597 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000598}
599
John McCall9b0a7ce2011-10-02 01:16:38 +0000600/// Determines whether the language options require us to model
601/// unwind exceptions. We treat -fexceptions as mandating this
602/// except under the fragile ObjC ABI with only ObjC exceptions
603/// enabled. This means, for example, that C with -fexceptions
604/// enables this.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000605static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCall9b0a7ce2011-10-02 01:16:38 +0000606 // If exceptions are completely disabled, obviously this is false.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000607 if (!LangOpts.Exceptions) return false;
John McCall9b0a7ce2011-10-02 01:16:38 +0000608
609 // If C++ exceptions are enabled, this is true.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000610 if (LangOpts.CXXExceptions) return true;
John McCall9b0a7ce2011-10-02 01:16:38 +0000611
612 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000613 if (LangOpts.ObjCExceptions) {
David Chisnallb601c962012-07-03 20:49:52 +0000614 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCall9b0a7ce2011-10-02 01:16:38 +0000615 }
616
617 return true;
618}
619
Daniel Dunbar38932572009-04-14 08:05:55 +0000620void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
621 llvm::Function *F) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000622 llvm::AttrBuilder B;
623
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000624 if (CodeGenOpts.UnwindTables)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000625 B.addAttribute(llvm::Attribute::UWTable);
Rafael Espindolac1ee12c2011-05-25 03:44:55 +0000626
David Blaikiebbafb8a2012-03-11 07:00:24 +0000627 if (!hasUnwindExceptions(LangOpts))
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000628 B.addAttribute(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000629
Eli Friedmanc55efe42011-08-22 23:55:33 +0000630 if (D->hasAttr<NakedAttr>()) {
631 // Naked implies noinline: we should not be inlining such functions.
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000632 B.addAttribute(llvm::Attribute::Naked);
633 B.addAttribute(llvm::Attribute::NoInline);
Aaron Ballman7c19ab12014-02-22 16:59:24 +0000634 } else if (D->hasAttr<NoDuplicateAttr>()) {
635 B.addAttribute(llvm::Attribute::NoDuplicate);
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000636 } else if (D->hasAttr<NoInlineAttr>()) {
637 B.addAttribute(llvm::Attribute::NoInline);
David Majnemer67e541e1c2014-02-25 09:53:29 +0000638 } else if (D->hasAttr<AlwaysInlineAttr>() &&
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000639 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
640 llvm::Attribute::NoInline)) {
641 // (noinline wins over always_inline, and we can't specify both in IR)
642 B.addAttribute(llvm::Attribute::AlwaysInline);
Eli Friedmanc55efe42011-08-22 23:55:33 +0000643 }
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000644
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000645 if (D->hasAttr<ColdAttr>()) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000646 B.addAttribute(llvm::Attribute::OptimizeForSize);
Diego Novillo5f2b1ce2013-05-24 20:18:15 +0000647 B.addAttribute(llvm::Attribute::Cold);
648 }
Benjamin Kramer29c2b432012-05-12 21:10:52 +0000649
Quentin Colombet4e172062012-11-01 23:55:47 +0000650 if (D->hasAttr<MinSizeAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000651 B.addAttribute(llvm::Attribute::MinSize);
Richard Smithb555a762012-09-28 22:46:07 +0000652
David Blaikiebbafb8a2012-03-11 07:00:24 +0000653 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000654 B.addAttribute(llvm::Attribute::StackProtect);
Josh Mageee0fc1a82014-02-11 01:35:14 +0000655 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
656 B.addAttribute(llvm::Attribute::StackProtectStrong);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000657 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000658 B.addAttribute(llvm::Attribute::StackProtectReq);
Will Dietzf54319c2013-01-18 11:30:38 +0000659
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000660 // Add sanitizer attributes if function is not blacklisted.
Alexey Samsonovd6e043b2013-08-12 11:48:05 +0000661 if (!SanitizerBlacklist->isIn(*F)) {
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000662 // When AddressSanitizer is enabled, set SanitizeAddress attribute
663 // unless __attribute__((no_sanitize_address)) is used.
664 if (SanOpts.Address && !D->hasAttr<NoSanitizeAddressAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000665 B.addAttribute(llvm::Attribute::SanitizeAddress);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000666 // Same for ThreadSanitizer and __attribute__((no_sanitize_thread))
667 if (SanOpts.Thread && !D->hasAttr<NoSanitizeThreadAttr>()) {
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000668 B.addAttribute(llvm::Attribute::SanitizeThread);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000669 }
670 // Same for MemorySanitizer and __attribute__((no_sanitize_memory))
671 if (SanOpts.Memory && !D->hasAttr<NoSanitizeMemoryAttr>())
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000672 B.addAttribute(llvm::Attribute::SanitizeMemory);
Alexey Samsonova1c0a2a2013-03-06 10:54:18 +0000673 }
Alexander Potapenkoef41fd32012-02-02 11:49:28 +0000674
Benjamin Kramer2960dbd2013-05-11 12:45:37 +0000675 F->addAttributes(llvm::AttributeSet::FunctionIndex,
676 llvm::AttributeSet::get(
677 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
678
679 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
680 F->setUnnamedAddr(true);
681 else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
682 if (MD->isVirtual())
683 F->setUnnamedAddr(true);
684
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000685 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
686 if (alignment)
687 F->setAlignment(alignment);
688
Mike Stump3472ae52009-10-05 22:49:20 +0000689 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000690 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
691 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000692}
693
Mike Stump11289f42009-09-09 15:08:12 +0000694void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000695 llvm::GlobalValue *GV) {
Anders Carlsson072ef742011-01-29 19:41:00 +0000696 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
697 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000698 else
699 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000700
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000701 if (D->hasAttr<UsedAttr>())
Rafael Espindola060062a2014-03-06 22:15:10 +0000702 addUsedGlobal(GV);
Daniel Dunbar38932572009-04-14 08:05:55 +0000703
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000704 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000705 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000706
Rafael Espindola513499d2013-03-19 15:03:47 +0000707 // Alias cannot have attributes. Filter them here.
708 if (!isa<llvm::GlobalAlias>(GV))
709 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000710}
711
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000712void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
713 llvm::Function *F,
714 const CGFunctionInfo &FI) {
715 SetLLVMFunctionAttributes(D, FI, F);
716 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000717
718 F->setLinkage(llvm::Function::InternalLinkage);
719
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000720 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000721}
722
Anders Carlsson6710c532010-02-06 02:44:09 +0000723void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000724 llvm::Function *F,
725 bool IsIncompleteFunction) {
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000726 if (unsigned IID = F->getIntrinsicID()) {
727 // If this is an intrinsic function, set the function's attributes
728 // to the intrinsic's attributes.
Bill Wendling311c8322012-10-15 04:47:45 +0000729 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
730 (llvm::Intrinsic::ID)IID));
Peter Collingbourneeafa4e42011-04-06 12:29:04 +0000731 return;
732 }
733
Anders Carlsson6710c532010-02-06 02:44:09 +0000734 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
735
Eli Friedman895771a2009-05-26 01:22:57 +0000736 if (!IsIncompleteFunction)
John McCalla729c622012-02-17 03:33:10 +0000737 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000738
Stephen Lin9dc6eef2013-06-30 20:40:16 +0000739 if (getCXXABI().HasThisReturn(GD)) {
740 assert(!F->arg_empty() &&
741 F->arg_begin()->getType()
742 ->canLosslesslyBitCastTo(F->getReturnType()) &&
743 "unexpected this return");
744 F->addAttribute(1, llvm::Attribute::Returned);
745 }
746
Daniel Dunbar38932572009-04-14 08:05:55 +0000747 // Only a few attributes are set on declarations; these may later be
748 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000749
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000750 if (FD->hasAttr<DLLImportAttr>()) {
Nico Rieckbb0554f2014-01-14 15:23:53 +0000751 F->setLinkage(llvm::Function::ExternalLinkage);
752 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
Mike Stump11289f42009-09-09 15:08:12 +0000753 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000754 FD->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000755 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000756 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000757 F->setLinkage(llvm::Function::ExternalWeakLinkage);
758 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000759 F->setLinkage(llvm::Function::ExternalLinkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +0000760 if (FD->hasAttr<DLLExportAttr>())
761 F->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
John McCallc273f242010-10-30 11:50:40 +0000762
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +0000763 LinkageInfo LV = FD->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +0000764 if (LV.getLinkage() == ExternalLinkage && LV.isVisibilityExplicit()) {
765 F->setVisibility(GetLLVMVisibility(LV.getVisibility()));
John McCallc273f242010-10-30 11:50:40 +0000766 }
Daniel Dunbar38932572009-04-14 08:05:55 +0000767 }
768
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000769 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000770 F->setSection(SA->getName());
Richard Smith8d0dc312013-07-21 23:12:18 +0000771
772 // A replaceable global allocation function does not act like a builtin by
773 // default, only if it is invoked by a new-expression or delete-expression.
774 if (FD->isReplaceableGlobalAllocationFunction())
775 F->addAttribute(llvm::AttributeSet::FunctionIndex,
776 llvm::Attribute::NoBuiltin);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000777}
778
Rafael Espindola060062a2014-03-06 22:15:10 +0000779void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000780 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000781 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000782 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000783}
784
Rafael Espindola060062a2014-03-06 22:15:10 +0000785void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
786 assert(!GV->isDeclaration() &&
787 "Only globals with definition can force usage.");
788 LLVMCompilerUsed.push_back(GV);
789}
790
791static void emitUsed(CodeGenModule &CGM, StringRef Name,
792 std::vector<llvm::WeakVH> &List) {
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000793 // Don't create llvm.used if there is no need.
Rafael Espindola060062a2014-03-06 22:15:10 +0000794 if (List.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000795 return;
796
Rafael Espindola060062a2014-03-06 22:15:10 +0000797 // Convert List to what ConstantArray needs.
Chris Lattner3def9ae2012-02-06 22:16:34 +0000798 SmallVector<llvm::Constant*, 8> UsedArray;
Rafael Espindola060062a2014-03-06 22:15:10 +0000799 UsedArray.resize(List.size());
800 for (unsigned i = 0, e = List.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000801 UsedArray[i] =
Rafael Espindola060062a2014-03-06 22:15:10 +0000802 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*List[i]),
803 CGM.Int8PtrTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000804 }
Mike Stump11289f42009-09-09 15:08:12 +0000805
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000806 if (UsedArray.empty())
807 return;
Rafael Espindola060062a2014-03-06 22:15:10 +0000808 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000809
810 llvm::GlobalVariable *GV =
Rafael Espindola060062a2014-03-06 22:15:10 +0000811 new llvm::GlobalVariable(CGM.getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000812 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000813 llvm::ConstantArray::get(ATy, UsedArray),
Rafael Espindola060062a2014-03-06 22:15:10 +0000814 Name);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000815
816 GV->setSection("llvm.metadata");
817}
818
Rafael Espindola060062a2014-03-06 22:15:10 +0000819void CodeGenModule::emitLLVMUsed() {
820 emitUsed(*this, "llvm.used", LLVMUsed);
821 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
822}
823
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000824void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
825 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
826 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
827}
828
Aaron Ballman5d041be2013-06-04 02:07:14 +0000829void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
830 llvm::SmallString<32> Opt;
831 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
832 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
833 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
834}
835
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000836void CodeGenModule::AddDependentLib(StringRef Lib) {
837 llvm::SmallString<24> Opt;
838 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
839 llvm::Value *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
840 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
841}
842
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000843/// \brief Add link options implied by the given module, including modules
844/// it depends on, using a postorder walk.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000845static void addLinkOptionsPostorder(CodeGenModule &CGM,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000846 Module *Mod,
Daniel Dunbar69e47462013-01-17 01:35:06 +0000847 SmallVectorImpl<llvm::Value *> &Metadata,
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000848 llvm::SmallPtrSet<Module *, 16> &Visited) {
849 // Import this module's parent.
850 if (Mod->Parent && Visited.insert(Mod->Parent)) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000851 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000852 }
853
854 // Import this module's dependencies.
855 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
856 if (Visited.insert(Mod->Imports[I-1]))
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000857 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000858 }
859
860 // Add linker options to link against the libraries/frameworks
861 // described by this module.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000862 llvm::LLVMContext &Context = CGM.getLLVMContext();
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000863 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000864 // Link against a framework. Frameworks are currently Darwin only, so we
865 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000866 if (Mod->LinkLibraries[I-1].IsFramework) {
867 llvm::Value *Args[2] = {
868 llvm::MDString::get(Context, "-framework"),
869 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
870 };
871
872 Metadata.push_back(llvm::MDNode::get(Context, Args));
873 continue;
874 }
875
876 // Link against a library.
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000877 llvm::SmallString<24> Opt;
878 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
879 Mod->LinkLibraries[I-1].Library, Opt);
880 llvm::Value *OptString = llvm::MDString::get(Context, Opt);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000881 Metadata.push_back(llvm::MDNode::get(Context, OptString));
882 }
883}
884
885void CodeGenModule::EmitModuleLinkOptions() {
886 // Collect the set of all of the modules we want to visit to emit link
887 // options, which is essentially the imported modules and all of their
888 // non-explicit child modules.
889 llvm::SetVector<clang::Module *> LinkModules;
890 llvm::SmallPtrSet<clang::Module *, 16> Visited;
891 SmallVector<clang::Module *, 16> Stack;
892
893 // Seed the stack with imported modules.
894 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
895 MEnd = ImportedModules.end();
896 M != MEnd; ++M) {
897 if (Visited.insert(*M))
898 Stack.push_back(*M);
899 }
900
901 // Find all of the modules to import, making a little effort to prune
902 // non-leaf modules.
903 while (!Stack.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000904 clang::Module *Mod = Stack.pop_back_val();
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000905
906 bool AnyChildren = false;
907
908 // Visit the submodules of this module.
909 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
910 SubEnd = Mod->submodule_end();
911 Sub != SubEnd; ++Sub) {
912 // Skip explicit children; they need to be explicitly imported to be
913 // linked against.
914 if ((*Sub)->IsExplicit)
915 continue;
916
917 if (Visited.insert(*Sub)) {
918 Stack.push_back(*Sub);
919 AnyChildren = true;
920 }
921 }
922
923 // We didn't find any children, so add this module to the list of
924 // modules to link against.
925 if (!AnyChildren) {
926 LinkModules.insert(Mod);
927 }
928 }
929
930 // Add link options for all of the imported modules in reverse topological
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000931 // order. We don't do anything to try to order import link flags with respect
932 // to linker options inserted by things like #pragma comment().
Daniel Dunbar69e47462013-01-17 01:35:06 +0000933 SmallVector<llvm::Value *, 16> MetadataArgs;
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000934 Visited.clear();
935 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
936 MEnd = LinkModules.end();
937 M != MEnd; ++M) {
938 if (Visited.insert(*M))
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000939 addLinkOptionsPostorder(*this, *M, MetadataArgs, Visited);
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000940 }
Daniel Dunbar69e47462013-01-17 01:35:06 +0000941 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000942 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000943
Daniel Dunbar69e47462013-01-17 01:35:06 +0000944 // Add the linker options metadata flag.
945 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000946 llvm::MDNode::get(getLLVMContext(),
947 LinkerOptionsMetadata));
Douglas Gregorbc25ff42013-01-14 20:53:57 +0000948}
949
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000950void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000951 // Emit code for any potentially referenced deferred decls. Since a
952 // previously unused static decl may become used during the generation of code
Nick Lewycky26da4dd2011-07-18 05:26:13 +0000953 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000954
John McCall6bd2a892013-01-25 22:31:03 +0000955 while (true) {
Anders Carlsson11e51402010-04-17 20:15:18 +0000956 if (!DeferredVTables.empty()) {
John McCall6bd2a892013-01-25 22:31:03 +0000957 EmitDeferredVTables();
958
959 // Emitting a v-table doesn't directly cause more v-tables to
960 // become deferred, although it can cause functions to be
961 // emitted that then need those v-tables.
962 assert(DeferredVTables.empty());
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000963 }
964
John McCall6bd2a892013-01-25 22:31:03 +0000965 // Stop if we're out of both deferred v-tables and deferred declarations.
966 if (DeferredDeclsToEmit.empty()) break;
967
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000968 DeferredGlobal &G = DeferredDeclsToEmit.back();
969 GlobalDecl D = G.GD;
970 llvm::GlobalValue *GV = G.GV;
Chris Lattner45470942009-03-21 09:44:56 +0000971 DeferredDeclsToEmit.pop_back();
972
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000973 assert(GV == GetGlobalValue(getMangledName(D)));
John McCallc2af9392010-05-27 01:45:30 +0000974 // Check to see if we've already emitted this. This is necessary
975 // for a couple of reasons: first, decls can end up in the
976 // deferred-decls queue multiple times, and second, decls can end
977 // up with definitions in unusual ways (e.g. by an extern inline
978 // function acquiring a strong function redefinition). Just
979 // ignore these cases.
Rafael Espindolac0ff7442013-12-09 14:59:08 +0000980 if(!GV->isDeclaration())
Chris Lattner45470942009-03-21 09:44:56 +0000981 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000982
Chris Lattner45470942009-03-21 09:44:56 +0000983 // Otherwise, emit the definition and move on to the next one.
Rafael Espindolacd7743b2013-12-09 16:01:03 +0000984 EmitGlobalDefinition(D, GV);
Chris Lattner45470942009-03-21 09:44:56 +0000985 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000986}
Chris Lattner09153c02007-06-22 18:48:09 +0000987
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000988void CodeGenModule::EmitGlobalAnnotations() {
989 if (Annotations.empty())
990 return;
991
992 // Create a new global variable for the ConstantStruct in the Module.
993 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
994 Annotations[0]->getType(), Annotations.size()), Annotations);
995 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
996 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
997 "llvm.global.annotations");
998 gv->setSection(AnnotationSection);
999}
1000
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001001llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Benjamin Kramereed80612013-11-10 16:55:11 +00001002 llvm::Constant *&AStr = AnnotationStrings[Str];
1003 if (AStr)
1004 return AStr;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001005
1006 // Not found yet, create a new global.
Chris Lattner9c818332012-02-05 02:30:40 +00001007 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001008 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
1009 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
1010 gv->setSection(AnnotationSection);
1011 gv->setUnnamedAddr(true);
Benjamin Kramereed80612013-11-10 16:55:11 +00001012 AStr = gv;
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001013 return gv;
1014}
1015
1016llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1017 SourceManager &SM = getContext().getSourceManager();
1018 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1019 if (PLoc.isValid())
1020 return EmitAnnotationString(PLoc.getFilename());
1021 return EmitAnnotationString(SM.getBufferName(Loc));
1022}
1023
1024llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1025 SourceManager &SM = getContext().getSourceManager();
1026 PresumedLoc PLoc = SM.getPresumedLoc(L);
1027 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1028 SM.getExpansionLineNumber(L);
1029 return llvm::ConstantInt::get(Int32Ty, LineNo);
1030}
1031
Mike Stump11289f42009-09-09 15:08:12 +00001032llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +00001033 const AnnotateAttr *AA,
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001034 SourceLocation L) {
1035 // Get the globals for file name, annotation, and the line number.
1036 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1037 *UnitGV = EmitAnnotationUnit(L),
1038 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begemanfaae0812008-04-19 04:17:09 +00001039
Daniel Dunbar346892a2009-04-14 22:41:13 +00001040 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +00001041 llvm::Constant *Fields[4] = {
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001042 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1043 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1044 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1045 LineNoCst
Nate Begemanfaae0812008-04-19 04:17:09 +00001046 };
Chris Lattnere64d7ba2011-06-20 04:01:35 +00001047 return llvm::ConstantStruct::getAnon(Fields);
Nate Begemanfaae0812008-04-19 04:17:09 +00001048}
1049
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001050void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1051 llvm::GlobalValue *GV) {
1052 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1053 // Get the struct elements for these annotations.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001054 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1055 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001056}
1057
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +00001058bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +00001059 // Never defer when EmitAllDecls is specified.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001060 if (LangOpts.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001061 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001062
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +00001063 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001064}
1065
Nico Webercf4ff5862012-10-11 10:13:44 +00001066llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1067 const CXXUuidofExpr* E) {
1068 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1069 // well-formed.
David Majnemer8eaab6f2013-08-13 06:32:20 +00001070 StringRef Uuid = E->getUuidAsStringRef(Context);
David Majnemercf963ce2013-08-09 08:35:59 +00001071 std::string Name = "_GUID_" + Uuid.lower();
1072 std::replace(Name.begin(), Name.end(), '-', '_');
Nico Webercf4ff5862012-10-11 10:13:44 +00001073
1074 // Look for an existing global.
1075 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1076 return GV;
1077
1078 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
1079 assert(Init && "failed to initialize as constant");
1080
David Majnemerbbecd092013-08-15 19:59:14 +00001081 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
1082 getModule(), Init->getType(),
Reid Klecknerb9921df2013-09-03 21:49:32 +00001083 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
Nico Webercf4ff5862012-10-11 10:13:44 +00001084 return GV;
1085}
1086
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001087llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1088 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1089 assert(AA && "No alias?");
1090
Chris Lattner2192fe52011-07-18 04:24:23 +00001091 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001092
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001093 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +00001094 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001095 if (Entry) {
1096 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1097 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1098 }
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001099
1100 llvm::Constant *Aliasee;
1101 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00001102 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1103 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson3c239482011-02-05 04:35:53 +00001104 /*ForVTable=*/false);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001105 else
John McCall7ec50432010-03-19 23:29:14 +00001106 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001107 llvm::PointerType::getUnqual(DeclTy), 0);
Joerg Sonnenbergerde78bba2012-10-16 17:45:27 +00001108
1109 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1110 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1111 WeakRefReferences.insert(F);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001112
1113 return Aliasee;
1114}
1115
Chris Lattnere0be0df2009-05-12 21:21:08 +00001116void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +00001117 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001118
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001119 // Weak references don't produce any output by themselves.
1120 if (Global->hasAttr<WeakRefAttr>())
1121 return;
1122
Chris Lattner54041692009-03-22 21:47:11 +00001123 // If this is an alias definition (which otherwise looks like a declaration)
1124 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001125 if (Global->hasAttr<AliasAttr>())
Rafael Espindola6956d582013-10-22 14:23:09 +00001126 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001127
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001128 // If this is CUDA, be selective about which declarations we emit.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001129 if (LangOpts.CUDA) {
Peter Collingbournea9455ec2011-10-06 18:29:46 +00001130 if (CodeGenOpts.CUDAIsDevice) {
1131 if (!Global->hasAttr<CUDADeviceAttr>() &&
1132 !Global->hasAttr<CUDAGlobalAttr>() &&
1133 !Global->hasAttr<CUDAConstantAttr>() &&
1134 !Global->hasAttr<CUDASharedAttr>())
1135 return;
1136 } else {
1137 if (!Global->hasAttr<CUDAHostAttr>() && (
1138 Global->hasAttr<CUDADeviceAttr>() ||
1139 Global->hasAttr<CUDAConstantAttr>() ||
1140 Global->hasAttr<CUDASharedAttr>()))
1141 return;
1142 }
1143 }
1144
Chris Lattner45470942009-03-21 09:44:56 +00001145 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +00001146 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001147 // Forward declarations are emitted lazily on first use.
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001148 if (!FD->doesThisDeclarationHaveABody()) {
1149 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1150 return;
1151
1152 const FunctionDecl *InlineDefinition = 0;
1153 FD->getBody(InlineDefinition);
1154
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001155 StringRef MangledName = getMangledName(GD);
Benjamin Kramere894e092012-03-24 18:22:12 +00001156 DeferredDecls.erase(MangledName);
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001157 EmitGlobalDefinition(InlineDefinition);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +00001158 return;
Nick Lewycky26da4dd2011-07-18 05:26:13 +00001159 }
Daniel Dunbar08b26a02009-02-13 20:29:50 +00001160 } else {
1161 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001162 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1163
Douglas Gregor61f6db52010-02-06 05:15:45 +00001164 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +00001165 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +00001166 }
1167
Chris Lattner45470942009-03-21 09:44:56 +00001168 // Defer code generation when possible if this is a static definition, inline
1169 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001170 if (!MayDeferGeneration(Global)) {
1171 // Emit the definition if it can't be deferred.
1172 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001173 return;
1174 }
John McCall70013b62010-07-15 23:40:35 +00001175
1176 // If we're deferring emission of a C++ variable with an
1177 // initializer, remember the order in which it appeared in the file.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001178 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCall70013b62010-07-15 23:40:35 +00001179 cast<VarDecl>(Global)->hasInit()) {
1180 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1181 CXXGlobalInits.push_back(0);
1182 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001183
1184 // If the value has already been used, add it directly to the
1185 // DeferredDeclsToEmit list.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001186 StringRef MangledName = getMangledName(GD);
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001187 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName))
1188 addDeferredDeclToEmit(GV, GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001189 else {
1190 // Otherwise, remember that we saw a deferred decl with this name. The
1191 // first use of the mangled name will cause it to move into
1192 // DeferredDeclsToEmit.
1193 DeferredDecls[MangledName] = GD;
1194 }
Nate Begeman8e8d4982008-04-20 06:29:50 +00001195}
1196
Rafael Espindolac5941352011-10-26 20:41:06 +00001197namespace {
1198 struct FunctionIsDirectlyRecursive :
1199 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1200 const StringRef Name;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001201 const Builtin::Context &BI;
Rafael Espindolac5941352011-10-26 20:41:06 +00001202 bool Result;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001203 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1204 Name(N), BI(C), Result(false) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001205 }
1206 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1207
1208 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001209 const FunctionDecl *FD = E->getDirectCallee();
1210 if (!FD)
Rafael Espindolac5941352011-10-26 20:41:06 +00001211 return true;
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001212 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1213 if (Attr && Name == Attr->getLabel()) {
1214 Result = true;
1215 return false;
1216 }
1217 unsigned BuiltinID = FD->getBuiltinID();
1218 if (!BuiltinID)
Rafael Espindolac5941352011-10-26 20:41:06 +00001219 return true;
Nick Lewycky9ed5b152012-01-18 03:41:19 +00001220 StringRef BuiltinName = BI.GetName(BuiltinID);
1221 if (BuiltinName.startswith("__builtin_") &&
1222 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolac5941352011-10-26 20:41:06 +00001223 Result = true;
1224 return false;
1225 }
1226 return true;
1227 }
1228 };
1229}
1230
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001231// isTriviallyRecursive - Check if this function calls another
1232// decl that, because of the asm attribute or the other decl being a builtin,
1233// ends up pointing to itself.
Rafael Espindolac5941352011-10-26 20:41:06 +00001234bool
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001235CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1236 StringRef Name;
1237 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky72cd2292012-01-18 01:50:13 +00001238 // asm labels are a special kind of mangling we have to support.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001239 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1240 if (!Attr)
1241 return false;
1242 Name = Attr->getLabel();
1243 } else {
1244 Name = FD->getName();
1245 }
Rafael Espindolac5941352011-10-26 20:41:06 +00001246
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001247 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1248 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolac5941352011-10-26 20:41:06 +00001249 return Walker.Result;
1250}
1251
1252bool
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001253CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1254 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
Rafael Espindolac5941352011-10-26 20:41:06 +00001255 return true;
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001256 const FunctionDecl *F = cast<FunctionDecl>(GD.getDecl());
David Majnemer67e541e1c2014-02-25 09:53:29 +00001257 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
Rafael Espindolac5941352011-10-26 20:41:06 +00001258 return false;
1259 // PR9614. Avoid cases where the source code is lying to us. An available
1260 // externally function should have an equivalent function somewhere else,
1261 // but a function that calls itself is clearly not equivalent to the real
1262 // implementation.
1263 // This happens in glibc's btowc and in some configure checks.
Rafael Espindola4fdc1752011-12-19 14:41:01 +00001264 return !isTriviallyRecursive(F);
Rafael Espindolac5941352011-10-26 20:41:06 +00001265}
1266
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001267/// If the type for the method's class was generated by
1268/// CGDebugInfo::createContextChain(), the cache contains only a
1269/// limited DIType without any declarations. Since EmitFunctionStart()
1270/// needs to find the canonical declaration for each method, we need
1271/// to construct the complete type prior to emitting the method.
1272void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1273 if (!D->isInstance())
1274 return;
1275
1276 if (CGDebugInfo *DI = getModuleDebugInfo())
1277 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1278 const PointerType *ThisPtr =
1279 cast<PointerType>(D->getThisType(getContext()));
1280 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1281 }
1282}
1283
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001284void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
Anders Carlsson38988d72009-09-10 23:38:47 +00001285 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001286
Dan Gohman145f3f12010-04-19 16:39:44 +00001287 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +00001288 Context.getSourceManager(),
1289 "Generating code for declaration");
1290
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001291 if (isa<FunctionDecl>(D)) {
Douglas Gregora700f682010-07-13 06:02:28 +00001292 // At -O0, don't generate IR for functions with available_externally
1293 // linkage.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00001294 if (!shouldEmitFunction(GD))
Douglas Gregora700f682010-07-13 06:02:28 +00001295 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +00001296
Douglas Gregora700f682010-07-13 06:02:28 +00001297 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Adrian Prantlffcf4ba2013-05-09 23:16:27 +00001298 CompleteDIClassType(Method);
Eli Friedman49a94b12011-05-06 17:27:27 +00001299 // Make sure to emit the definition(s) before we emit the thunks.
1300 // This is necessary for the generation of certain thunks.
1301 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1302 EmitCXXConstructor(CD, GD.getCtorType());
1303 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1304 EmitCXXDestructor(DD, GD.getDtorType());
1305 else
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001306 EmitGlobalFunctionDefinition(GD, GV);
Eli Friedman49a94b12011-05-06 17:27:27 +00001307
Douglas Gregora700f682010-07-13 06:02:28 +00001308 if (Method->isVirtual())
1309 getVTables().EmitThunks(GD);
1310
Eli Friedman49a94b12011-05-06 17:27:27 +00001311 return;
Douglas Gregora700f682010-07-13 06:02:28 +00001312 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001313
Rafael Espindolacd7743b2013-12-09 16:01:03 +00001314 return EmitGlobalFunctionDefinition(GD, GV);
Douglas Gregora700f682010-07-13 06:02:28 +00001315 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +00001316
1317 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1318 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +00001319
David Blaikie83d382b2011-09-23 05:06:16 +00001320 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +00001321}
1322
Chris Lattnerd4808922009-03-22 21:03:39 +00001323/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1324/// module, create and return an llvm Function with the specified type. If there
1325/// is something in the module with the specified name, return it potentially
1326/// bitcasted to the right type.
1327///
1328/// If D is non-null, it specifies a decl that correspond to this. This is used
1329/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001330llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001331CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001332 llvm::Type *Ty,
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001333 GlobalDecl GD, bool ForVTable,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001334 bool DontDefer,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001335 llvm::AttributeSet ExtraAttrs) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001336 const Decl *D = GD.getDecl();
1337
Chris Lattnera85d68e2009-03-21 09:25:43 +00001338 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001339 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001340 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001341 if (WeakRefReferences.erase(Entry)) {
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001342 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001343 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001344 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001345 }
1346
Chris Lattnera85d68e2009-03-21 09:25:43 +00001347 if (Entry->getType()->getElementType() == Ty)
1348 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001349
Chris Lattnera85d68e2009-03-21 09:25:43 +00001350 // Make sure the result is of the correct type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00001351 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattnera85d68e2009-03-21 09:25:43 +00001352 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Eli Friedmancc522d92009-11-09 05:07:37 +00001354 // This function doesn't have a complete type (for example, the return
1355 // type is an incomplete struct). Use a fake type instead, and make
1356 // sure not to try to set attributes.
1357 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +00001358
Chris Lattner2192fe52011-07-18 04:24:23 +00001359 llvm::FunctionType *FTy;
John McCalld06fb862010-04-28 00:00:30 +00001360 if (isa<llvm::FunctionType>(Ty)) {
1361 FTy = cast<llvm::FunctionType>(Ty);
1362 } else {
John McCall9dc0db22011-05-15 01:53:33 +00001363 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedmancc522d92009-11-09 05:07:37 +00001364 IsIncompleteFunction = true;
1365 }
Chris Lattner5c740f12010-06-30 19:14:05 +00001366
John McCalld06fb862010-04-28 00:00:30 +00001367 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +00001368 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +00001369 MangledName, &getModule());
1370 assert(F->getName() == MangledName && "name was uniqued!");
Reid Klecknerf6ce2b52013-07-22 13:07:10 +00001371 if (D)
1372 SetFunctionAttributes(GD, F, IsIncompleteFunction);
Bill Wendling8594fcb2013-01-31 00:30:05 +00001373 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1374 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling9a677922013-01-23 00:21:06 +00001375 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1376 llvm::AttributeSet::get(VMContext,
1377 llvm::AttributeSet::FunctionIndex,
1378 B));
1379 }
Eli Friedmancc522d92009-11-09 05:07:37 +00001380
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001381 if (!DontDefer) {
1382 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1383 // each other bottoming out with the base dtor. Therefore we emit non-base
1384 // dtors on usage, even if there is no dtor definition in the TU.
1385 if (D && isa<CXXDestructorDecl>(D) &&
1386 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1387 GD.getDtorType()))
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001388 addDeferredDeclToEmit(F, GD);
John McCall357d0f32010-12-15 04:00:32 +00001389
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001390 // This is the first use or definition of a mangled name. If there is a
1391 // deferred decl with this name, remember that we need to emit it at the end
1392 // of the file.
1393 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
1394 if (DDI != DeferredDecls.end()) {
1395 // Move the potentially referenced deferred decl to the
1396 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1397 // don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001398 addDeferredDeclToEmit(F, DDI->second);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001399 DeferredDecls.erase(DDI);
Richard Smithb47c36f2013-11-05 09:12:18 +00001400
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001401 // Otherwise, if this is a sized deallocation function, emit a weak
1402 // definition
1403 // for it at the end of the translation unit.
1404 } else if (D && cast<FunctionDecl>(D)
1405 ->getCorrespondingUnsizedGlobalDeallocationFunction()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001406 addDeferredDeclToEmit(F, GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001407
1408 // Otherwise, there are cases we have to worry about where we're
1409 // using a declaration for which we must emit a definition but where
1410 // we might not find a top-level definition:
1411 // - member functions defined inline in their classes
1412 // - friend functions defined inline in some class
1413 // - special member functions with implicit definitions
1414 // If we ever change our AST traversal to walk into class methods,
1415 // this will be unnecessary.
1416 //
1417 // We also don't emit a definition for a function if it's going to be an
1418 // entry
1419 // in a vtable, unless it's already marked as used.
1420 } else if (getLangOpts().CPlusPlus && D) {
1421 // Look for a declaration that's lexically in a record.
1422 const FunctionDecl *FD = cast<FunctionDecl>(D);
1423 FD = FD->getMostRecentDecl();
1424 do {
1425 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1426 if (FD->isImplicit() && !ForVTable) {
1427 assert(FD->isUsed() &&
1428 "Sema didn't mark implicit function as used!");
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001429 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001430 break;
1431 } else if (FD->doesThisDeclarationHaveABody()) {
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001432 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001433 break;
1434 }
John McCall357d0f32010-12-15 04:00:32 +00001435 }
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001436 FD = FD->getPreviousDecl();
1437 } while (FD);
1438 }
Chris Lattner45470942009-03-21 09:44:56 +00001439 }
Mike Stump11289f42009-09-09 15:08:12 +00001440
John McCalld06fb862010-04-28 00:00:30 +00001441 // Make sure the result is of the requested type.
1442 if (!IsIncompleteFunction) {
1443 assert(F->getType()->getElementType() == Ty);
1444 return F;
1445 }
1446
Chris Lattnera5f58b02011-07-09 17:41:47 +00001447 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCalld06fb862010-04-28 00:00:30 +00001448 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +00001449}
1450
Chris Lattnerd4808922009-03-22 21:03:39 +00001451/// GetAddrOfFunction - Return the address of the given function. If Ty is
1452/// non-null, then this function will use the specified type if it has to
1453/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +00001454llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2192fe52011-07-18 04:24:23 +00001455 llvm::Type *Ty,
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001456 bool ForVTable,
1457 bool DontDefer) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001458 // If there was no specific requested type, just convert it now.
1459 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +00001460 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +00001461
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001462 StringRef MangledName = getMangledName(GD);
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001463 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
Chris Lattnerd4808922009-03-22 21:03:39 +00001464}
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001465
Chris Lattnerd4808922009-03-22 21:03:39 +00001466/// CreateRuntimeFunction - Create a new runtime function with the specified
1467/// type and name.
1468llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001469CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001470 StringRef Name,
Bill Wendling8594fcb2013-01-31 00:30:05 +00001471 llvm::AttributeSet ExtraAttrs) {
Rafael Espindola94abb8f2013-12-09 04:29:47 +00001472 llvm::Constant *C =
1473 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1474 /*DontDefer=*/false, ExtraAttrs);
John McCall882987f2013-02-28 19:01:20 +00001475 if (llvm::Function *F = dyn_cast<llvm::Function>(C))
1476 if (F->empty())
1477 F->setCallingConv(getRuntimeCC());
1478 return C;
Chris Lattnerd4808922009-03-22 21:03:39 +00001479}
Daniel Dunbar9c426522008-07-29 23:18:29 +00001480
Richard Smithe070fd22012-02-17 06:48:11 +00001481/// isTypeConstant - Determine whether an object of this type can be emitted
1482/// as a constant.
1483///
1484/// If ExcludeCtor is true, the duration when the object's constructor runs
1485/// will not be considered. The caller will need to verify that the object is
1486/// not written to during its construction.
1487bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1488 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +00001489 return false;
Richard Smithe070fd22012-02-17 06:48:11 +00001490
David Blaikiebbafb8a2012-03-11 07:00:24 +00001491 if (Context.getLangOpts().CPlusPlus) {
Richard Smithe070fd22012-02-17 06:48:11 +00001492 if (const CXXRecordDecl *Record
1493 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1494 return ExcludeCtor && !Record->hasMutableFields() &&
1495 Record->hasTrivialDestructor();
Eli Friedmanb095e152009-12-11 21:23:03 +00001496 }
Richard Smithe070fd22012-02-17 06:48:11 +00001497
Eli Friedmanb095e152009-12-11 21:23:03 +00001498 return true;
1499}
1500
Chris Lattnerd4808922009-03-22 21:03:39 +00001501/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1502/// create and return an llvm GlobalVariable with the specified type. If there
1503/// is something in the module with the specified name, return it potentially
1504/// bitcasted to the right type.
1505///
1506/// If D is non-null, it specifies a decl that correspond to this. This is used
1507/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +00001508llvm::Constant *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001509CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2192fe52011-07-18 04:24:23 +00001510 llvm::PointerType *Ty,
Rafael Espindolad661a852011-01-18 21:07:57 +00001511 const VarDecl *D,
1512 bool UnnamedAddr) {
Daniel Dunbar829e9882008-08-05 23:31:02 +00001513 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +00001514 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +00001515 if (Entry) {
Benjamin Kramerfc6eb7d2012-08-22 15:37:55 +00001516 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001517 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +00001518 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001519 }
1520
Rafael Espindolad661a852011-01-18 21:07:57 +00001521 if (UnnamedAddr)
1522 Entry->setUnnamedAddr(true);
1523
Chris Lattnerd4808922009-03-22 21:03:39 +00001524 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +00001525 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattner3bfce182009-03-21 08:03:33 +00001527 // Make sure the result is of the correct type.
Matt Arsenault00e65b22013-11-15 02:19:52 +00001528 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1529 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1530
Owen Andersonade90fd2009-07-29 18:54:39 +00001531 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +00001532 }
Mike Stump11289f42009-09-09 15:08:12 +00001533
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001534 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1535 llvm::GlobalVariable *GV =
1536 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
1537 llvm::GlobalValue::ExternalLinkage,
1538 0, MangledName, 0,
1539 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1540
Chris Lattner45470942009-03-21 09:44:56 +00001541 // This is the first use or definition of a mangled name. If there is a
1542 // deferred decl with this name, remember that we need to emit it at the end
1543 // of the file.
John McCall7ec50432010-03-19 23:29:14 +00001544 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +00001545 if (DDI != DeferredDecls.end()) {
1546 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1547 // list, and remove it from DeferredDecls (since we don't need it anymore).
Rafael Espindolac0ff7442013-12-09 14:59:08 +00001548 addDeferredDeclToEmit(GV, DDI->second);
Chris Lattner45470942009-03-21 09:44:56 +00001549 DeferredDecls.erase(DDI);
1550 }
Mike Stump11289f42009-09-09 15:08:12 +00001551
Chris Lattner3bfce182009-03-21 08:03:33 +00001552 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +00001553 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +00001554 // FIXME: This code is overly simple and should be merged with other global
1555 // handling.
Richard Smithe070fd22012-02-17 06:48:11 +00001556 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner3bfce182009-03-21 08:03:33 +00001557
John McCall37bb6c92010-10-29 22:22:43 +00001558 // Set linkage and visibility in case we never see a definition.
Rafael Espindolaa8fbdab2013-02-27 02:15:29 +00001559 LinkageInfo LV = D->getLinkageAndVisibility();
Rafael Espindola4a5da442013-02-27 02:56:45 +00001560 if (LV.getLinkage() != ExternalLinkage) {
John McCall83779672011-02-19 02:53:41 +00001561 // Don't set internal linkage on declarations.
John McCall37bb6c92010-10-29 22:22:43 +00001562 } else {
Nico Rieckbb0554f2014-01-14 15:23:53 +00001563 if (D->hasAttr<DLLImportAttr>()) {
1564 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1565 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1566 } else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall37bb6c92010-10-29 22:22:43 +00001567 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner3bfce182009-03-21 08:03:33 +00001568
John McCallc273f242010-10-30 11:50:40 +00001569 // Set visibility on a declaration only if it's explicit.
Rafael Espindola4a5da442013-02-27 02:56:45 +00001570 if (LV.isVisibilityExplicit())
1571 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
John McCall37bb6c92010-10-29 22:22:43 +00001572 }
Eli Friedman4f856742009-04-19 21:05:03 +00001573
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001574 if (D->getTLSKind()) {
Richard Smith1847baa2013-04-22 08:06:17 +00001575 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1576 CXXThreadLocals.push_back(std::make_pair(D, GV));
Hans Wennborgf60f6af2012-06-28 08:01:44 +00001577 setTLSMode(GV, *D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +00001578 }
Hans Wennborgfeedf852013-11-21 00:15:56 +00001579
1580 // If required by the ABI, treat declarations of static data members with
1581 // inline initializers as definitions.
1582 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1583 D->isStaticDataMember() && D->hasInit() &&
1584 !D->isThisDeclarationADefinition())
1585 EmitGlobalVarDefinition(D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001586 }
Mike Stump11289f42009-09-09 15:08:12 +00001587
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001588 if (AddrSpace != Ty->getAddressSpace())
Matt Arsenault00e65b22013-11-15 02:19:52 +00001589 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1590
Robert Lytton15abd182014-02-11 10:34:51 +00001591 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1592 D->getLanguageLinkage() == CLanguageLinkage &&
1593 D->getType().isConstant(Context) &&
1594 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1595 GV->setSection(".cp.rodata");
1596
Matt Arsenault00e65b22013-11-15 02:19:52 +00001597 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001598}
1599
Chris Lattnerd4808922009-03-22 21:03:39 +00001600
Anders Carlssonda80af32011-01-29 18:20:20 +00001601llvm::GlobalVariable *
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001602CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2192fe52011-07-18 04:24:23 +00001603 llvm::Type *Ty,
Anders Carlssonda80af32011-01-29 18:20:20 +00001604 llvm::GlobalValue::LinkageTypes Linkage) {
1605 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1606 llvm::GlobalVariable *OldGV = 0;
1607
1608
1609 if (GV) {
1610 // Check if the variable has the right type.
1611 if (GV->getType()->getElementType() == Ty)
1612 return GV;
1613
1614 // Because C++ name mangling, the only way we can end up with an already
1615 // existing global with the same name is if it has been declared extern "C".
Nico Webercf4ff5862012-10-11 10:13:44 +00001616 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001617 OldGV = GV;
1618 }
1619
1620 // Create a new variable.
1621 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1622 Linkage, 0, Name);
1623
1624 if (OldGV) {
1625 // Replace occurrences of the old variable if needed.
1626 GV->takeName(OldGV);
1627
1628 if (!OldGV->use_empty()) {
1629 llvm::Constant *NewPtrForOldDecl =
1630 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1631 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1632 }
1633
1634 OldGV->eraseFromParent();
1635 }
1636
1637 return GV;
1638}
1639
Chris Lattnerd4808922009-03-22 21:03:39 +00001640/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1641/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher365e3092012-04-16 23:55:04 +00001642/// then it will be created with the specified type instead of whatever the
Chris Lattnerd4808922009-03-22 21:03:39 +00001643/// normal requested type would be.
1644llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2192fe52011-07-18 04:24:23 +00001645 llvm::Type *Ty) {
Chris Lattnerd4808922009-03-22 21:03:39 +00001646 assert(D->hasGlobalStorage() && "Not a global variable");
1647 QualType ASTTy = D->getType();
1648 if (Ty == 0)
1649 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattner2192fe52011-07-18 04:24:23 +00001651 llvm::PointerType *PTy =
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001652 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCall7ec50432010-03-19 23:29:14 +00001653
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001654 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001655 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001656}
1657
1658/// CreateRuntimeVariable - Create a new runtime global variable with the
1659/// specified type and name.
1660llvm::Constant *
Chris Lattner2192fe52011-07-18 04:24:23 +00001661CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001662 StringRef Name) {
John McCall31996342011-04-07 08:22:57 +00001663 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolad661a852011-01-18 21:07:57 +00001664 true);
Chris Lattnerd4808922009-03-22 21:03:39 +00001665}
1666
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001667void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1668 assert(!D->getInit() && "Cannot emit definite definitions here!");
1669
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001670 if (MayDeferGeneration(D)) {
1671 // If we have not seen a reference to this variable yet, place it
1672 // into the deferred declarations table to be emitted if needed
1673 // later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001674 StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001675 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001676 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001677 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001678 }
1679 }
1680
1681 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001682 EmitGlobalVarDefinition(D);
1683}
1684
Chris Lattner2192fe52011-07-18 04:24:23 +00001685CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001686 return Context.toCharUnitsFromBits(
Micah Villmowdd31ca12012-10-08 16:25:52 +00001687 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001688}
1689
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001690unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1691 unsigned AddrSpace) {
1692 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1693 if (D->hasAttr<CUDAConstantAttr>())
1694 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1695 else if (D->hasAttr<CUDASharedAttr>())
1696 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1697 else
1698 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1699 }
1700
1701 return AddrSpace;
1702}
1703
Richard Smithdf931ce2013-04-06 05:00:46 +00001704template<typename SomeDecl>
1705void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1706 llvm::GlobalValue *GV) {
1707 if (!getLangOpts().CPlusPlus)
1708 return;
1709
1710 // Must have 'used' attribute, or else inline assembly can't rely on
1711 // the name existing.
1712 if (!D->template hasAttr<UsedAttr>())
1713 return;
1714
1715 // Must have internal linkage and an ordinary name.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001716 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
Richard Smithdf931ce2013-04-06 05:00:46 +00001717 return;
1718
1719 // Must be in an extern "C" context. Entities declared directly within
1720 // a record are not extern "C" even if the record is in such a context.
Rafael Espindola8db352d2013-10-17 15:37:26 +00001721 const SomeDecl *First = D->getFirstDecl();
Rafael Espindola593537a2013-05-05 20:15:21 +00001722 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
Richard Smithdf931ce2013-04-06 05:00:46 +00001723 return;
1724
1725 // OK, this is an internal linkage entity inside an extern "C" linkage
1726 // specification. Make a note of that so we can give it the "expected"
1727 // mangled name if nothing else is using that name.
Richard Smith85465e62013-04-06 07:07:44 +00001728 std::pair<StaticExternCMap::iterator, bool> R =
1729 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
Richard Smithdf931ce2013-04-06 05:00:46 +00001730
1731 // If we have multiple internal linkage entities with the same name
1732 // in extern "C" regions, none of them gets that name.
Richard Smith85465e62013-04-06 07:07:44 +00001733 if (!R.second)
1734 R.first->second = 0;
Richard Smithdf931ce2013-04-06 05:00:46 +00001735}
1736
Daniel Dunbar9c426522008-07-29 23:18:29 +00001737void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001738 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001739 QualType ASTTy = D->getType();
Richard Smith6331c402012-02-13 22:16:19 +00001740 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1741 bool NeedsGlobalCtor = false;
1742 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump11289f42009-09-09 15:08:12 +00001743
Richard Smithdafff942012-01-14 04:30:29 +00001744 const VarDecl *InitDecl;
1745 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001746
Anders Carlssonca4a5452010-01-26 17:43:42 +00001747 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001748 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001749 // implicitly initialized with { 0 }.
1750 //
1751 // Note that tentative definitions are only emitted at the end of
1752 // a translation unit, so they should never have incomplete
1753 // type. In addition, EmitTentativeDefinition makes sure that we
1754 // never attempt to emit a tentative definition if a real one
1755 // exists. A use may still exists, however, so we still may need
1756 // to do a RAUW.
1757 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001758 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001759 } else {
Richard Smithcc1b96d2013-06-12 22:31:48 +00001760 initializedGlobalDecl = GlobalDecl(D);
1761 Init = EmitConstantInit(*InitDecl);
Sebastian Redl4a7eab22012-02-25 20:51:20 +00001762
Fariborz Jahanian63628032012-06-26 16:06:38 +00001763 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001764 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001765 if (D->getType()->isReferenceType())
1766 T = D->getType();
Richard Smithdafff942012-01-14 04:30:29 +00001767
David Blaikiebbafb8a2012-03-11 07:00:24 +00001768 if (getLangOpts().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001769 Init = EmitNullConstant(T);
Richard Smith6331c402012-02-13 22:16:19 +00001770 NeedsGlobalCtor = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001771 } else {
1772 ErrorUnsupported(D, "static initializer");
1773 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1774 }
John McCall70013b62010-07-15 23:40:35 +00001775 } else {
1776 // We don't need an initializer, so remove the entry for the delayed
Richard Smith6331c402012-02-13 22:16:19 +00001777 // initializer position (just in case this entry was delayed) if we
1778 // also don't need to register a destructor.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001779 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCall70013b62010-07-15 23:40:35 +00001780 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001781 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001782 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001783
Chris Lattner2192fe52011-07-18 04:24:23 +00001784 llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001785 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001786
Chris Lattner149927c2009-03-21 09:16:30 +00001787 // Strip off a bitcast if we got one back.
1788 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001789 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
Matt Arsenault00e65b22013-11-15 02:19:52 +00001790 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
1791 // All zero index gep.
Chris Lattneraa64ca22009-07-16 16:48:25 +00001792 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001793 Entry = CE->getOperand(0);
1794 }
Mike Stump11289f42009-09-09 15:08:12 +00001795
Chris Lattner149927c2009-03-21 09:16:30 +00001796 // Entry is now either a Function or GlobalVariable.
1797 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001798
Chris Lattner149927c2009-03-21 09:16:30 +00001799 // We have a definition after a declaration with the wrong type.
1800 // We must make a new GlobalVariable* and update everything that used OldGV
1801 // (a declaration or tentative definition) with the new GlobalVariable*
1802 // (which will be a definition).
1803 //
1804 // This happens if there is a prototype for a global (e.g.
1805 // "extern int x[];") and then a definition of a different type (e.g.
1806 // "int x[10];"). This also happens when an initializer has a different type
1807 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001808 if (GV == 0 ||
1809 GV->getType()->getElementType() != InitType ||
Peter Collingbourne599cb8e2011-03-18 22:38:29 +00001810 GV->getType()->getAddressSpace() !=
Peter Collingbournef44bdf92012-05-20 21:08:35 +00001811 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump11289f42009-09-09 15:08:12 +00001812
John McCall7ec50432010-03-19 23:29:14 +00001813 // Move the old entry aside so that we'll create a new one.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001814 Entry->setName(StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001815
Chris Lattner149927c2009-03-21 09:16:30 +00001816 // Make a new global with the correct type, this is now guaranteed to work.
1817 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001818
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001819 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001820 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001821 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001822 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001823
1824 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001825 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001826 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001827
Richard Smithdf931ce2013-04-06 05:00:46 +00001828 MaybeHandleStaticInExternC(D, GV);
1829
Julien Lerouge5a6b6982011-09-09 22:41:49 +00001830 if (D->hasAttr<AnnotateAttr>())
1831 AddGlobalAnnotations(D, GV);
Nate Begemanfaae0812008-04-19 04:17:09 +00001832
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001833 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001834
1835 // If it is safe to mark the global 'constant', do so now.
Richard Smithe070fd22012-02-17 06:48:11 +00001836 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1837 isTypeConstant(D->getType(), true));
Mike Stump11289f42009-09-09 15:08:12 +00001838
Ken Dyck160146e2010-01-27 17:10:57 +00001839 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smithe070fd22012-02-17 06:48:11 +00001840
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001841 // Set the llvm linkage type as appropriate.
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001842 llvm::GlobalValue::LinkageTypes Linkage =
Eli Friedman7e346a82013-07-01 20:22:57 +00001843 GetLLVMLinkageVarDefinition(D, GV->isConstant());
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001844 GV->setLinkage(Linkage);
Nico Rieckbb0554f2014-01-14 15:23:53 +00001845 if (D->hasAttr<DLLImportAttr>())
1846 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
1847 else if (D->hasAttr<DLLExportAttr>())
1848 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
Hans Wennborgfeedf852013-11-21 00:15:56 +00001849
1850 // If required by the ABI, give definitions of static data members with inline
1851 // initializers linkonce_odr linkage.
1852 if (getCXXABI().isInlineInitializedStaticDataMemberLinkOnce() &&
1853 D->isStaticDataMember() && InitExpr &&
1854 !InitDecl->isThisDeclarationADefinition())
1855 GV->setLinkage(llvm::GlobalVariable::LinkOnceODRLinkage);
1856
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001857 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001858 // common vars aren't constant even if declared const.
1859 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001860
Daniel Dunbar38932572009-04-14 08:05:55 +00001861 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001862
John McCallcdf7ef52010-11-06 09:44:32 +00001863 // Emit the initializer function if necessary.
Richard Smith6331c402012-02-13 22:16:19 +00001864 if (NeedsGlobalCtor || NeedsGlobalDtor)
1865 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCallcdf7ef52010-11-06 09:44:32 +00001866
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001867 // If we are compiling with ASan, add metadata indicating dynamically
1868 // initialized globals.
Will Dietzf54319c2013-01-18 11:30:38 +00001869 if (SanOpts.Address && NeedsGlobalCtor) {
Kostya Serebryany28a26c82012-08-21 06:53:28 +00001870 llvm::Module &M = getModule();
1871
1872 llvm::NamedMDNode *DynamicInitializers =
1873 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1874 llvm::Value *GlobalToAdd[] = { GV };
1875 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1876 DynamicInitializers->addOperand(ThisGlobal);
1877 }
1878
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001879 // Emit global variable debug information.
Eric Christopher7cdf9482011-10-13 21:45:18 +00001880 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregorb0eea8b2012-10-23 20:05:01 +00001881 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonov74a38682012-05-04 07:39:27 +00001882 DI->EmitGlobalVariable(GV, D);
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001883}
Chris Lattner09153c02007-06-22 18:48:09 +00001884
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001885llvm::GlobalValue::LinkageTypes
Eli Friedman7e346a82013-07-01 20:22:57 +00001886CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, bool isConstant) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001887 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1888 if (Linkage == GVA_Internal)
1889 return llvm::Function::InternalLinkage;
1890 else if (D->hasAttr<DLLImportAttr>())
Nico Rieckbb0554f2014-01-14 15:23:53 +00001891 return llvm::Function::ExternalLinkage;
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001892 else if (D->hasAttr<DLLExportAttr>())
Nico Rieckbb0554f2014-01-14 15:23:53 +00001893 return llvm::Function::ExternalLinkage;
Reid Klecknerb144d362013-05-20 14:02:37 +00001894 else if (D->hasAttr<SelectAnyAttr>()) {
1895 // selectany symbols are externally visible, so use weak instead of
1896 // linkonce. MSVC optimizes away references to const selectany globals, so
1897 // all definitions should be the same and ODR linkage should be used.
1898 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
1899 return llvm::GlobalVariable::WeakODRLinkage;
1900 } else if (D->hasAttr<WeakAttr>()) {
Eli Friedman7e346a82013-07-01 20:22:57 +00001901 if (isConstant)
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001902 return llvm::GlobalVariable::WeakODRLinkage;
1903 else
1904 return llvm::GlobalVariable::WeakAnyLinkage;
1905 } else if (Linkage == GVA_TemplateInstantiation ||
1906 Linkage == GVA_ExplicitTemplateInstantiation)
John McCalla97f3292011-04-12 01:46:54 +00001907 return llvm::GlobalVariable::WeakODRLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001908 else if (!getLangOpts().CPlusPlus &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00001909 ((!CodeGenOpts.NoCommon && !D->hasAttr<NoCommonAttr>()) ||
1910 D->hasAttr<CommonAttr>()) &&
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001911 !D->hasExternalStorage() && !D->getInit() &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00001912 !D->hasAttr<SectionAttr>() && !D->getTLSKind() &&
1913 !D->hasAttr<WeakImportAttr>()) {
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001914 // Thread local vars aren't considered common linkage.
1915 return llvm::GlobalVariable::CommonLinkage;
Bill Wendling95cae882013-05-02 19:18:03 +00001916 } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
1917 getTarget().getTriple().isMacOSX())
1918 // On Darwin, the backing variable for a C++11 thread_local variable always
1919 // has internal linkage; all accesses should just be calls to the
1920 // Itanium-specified entry point, which has the normal linkage of the
1921 // variable.
1922 return llvm::GlobalValue::InternalLinkage;
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001923 return llvm::GlobalVariable::ExternalLinkage;
1924}
1925
John McCall49954ca2012-12-12 22:21:47 +00001926/// Replace the uses of a function that was declared with a non-proto type.
1927/// We want to silently drop extra arguments from call sites
1928static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1929 llvm::Function *newFn) {
1930 // Fast path.
1931 if (old->use_empty()) return;
1932
1933 llvm::Type *newRetTy = newFn->getReturnType();
1934 SmallVector<llvm::Value*, 4> newArgs;
1935
1936 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1937 ui != ue; ) {
1938 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001939 llvm::User *user = use->getUser();
John McCall49954ca2012-12-12 22:21:47 +00001940
1941 // Recognize and replace uses of bitcasts. Most calls to
1942 // unprototyped functions will use bitcasts.
1943 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1944 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1945 replaceUsesOfNonProtoConstant(bitcast, newFn);
1946 continue;
1947 }
1948
1949 // Recognize calls to the function.
1950 llvm::CallSite callSite(user);
1951 if (!callSite) continue;
Chandler Carruth4d01fff2014-03-09 03:16:50 +00001952 if (!callSite.isCallee(&*use)) continue;
John McCall49954ca2012-12-12 22:21:47 +00001953
1954 // If the return types don't match exactly, then we can't
1955 // transform this call unless it's dead.
1956 if (callSite->getType() != newRetTy && !callSite->use_empty())
1957 continue;
1958
1959 // Get the call site's attribute list.
Bill Wendling290d9522013-01-27 02:46:53 +00001960 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCall49954ca2012-12-12 22:21:47 +00001961 llvm::AttributeSet oldAttrs = callSite.getAttributes();
1962
1963 // Collect any return attributes from the call.
Bill Wendling304f6f02013-01-21 21:57:40 +00001964 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlingb7abb302013-01-21 22:45:00 +00001965 newAttrs.push_back(
Bill Wendling290d9522013-01-27 02:46:53 +00001966 llvm::AttributeSet::get(newFn->getContext(),
1967 oldAttrs.getRetAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00001968
1969 // If the function was passed too few arguments, don't transform.
1970 unsigned newNumArgs = newFn->arg_size();
1971 if (callSite.arg_size() < newNumArgs) continue;
1972
1973 // If extra arguments were passed, we silently drop them.
1974 // If any of the types mismatch, we don't transform.
1975 unsigned argNo = 0;
1976 bool dontTransform = false;
1977 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1978 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1979 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1980 dontTransform = true;
1981 break;
1982 }
1983
1984 // Add any parameter attributes.
Bill Wendlingce2f9c52013-01-23 06:15:10 +00001985 if (oldAttrs.hasAttributes(argNo + 1))
1986 newAttrs.
Bill Wendling290d9522013-01-27 02:46:53 +00001987 push_back(llvm::
1988 AttributeSet::get(newFn->getContext(),
1989 oldAttrs.getParamAttributes(argNo + 1)));
John McCall49954ca2012-12-12 22:21:47 +00001990 }
1991 if (dontTransform)
1992 continue;
1993
Bill Wendling63ffde52013-01-18 21:26:07 +00001994 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendling290d9522013-01-27 02:46:53 +00001995 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1996 oldAttrs.getFnAttributes()));
John McCall49954ca2012-12-12 22:21:47 +00001997
1998 // Okay, we can transform this. Create the new call instruction and copy
1999 // over the required information.
2000 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2001
2002 llvm::CallSite newCall;
2003 if (callSite.isCall()) {
2004 newCall = llvm::CallInst::Create(newFn, newArgs, "",
2005 callSite.getInstruction());
2006 } else {
2007 llvm::InvokeInst *oldInvoke =
2008 cast<llvm::InvokeInst>(callSite.getInstruction());
2009 newCall = llvm::InvokeInst::Create(newFn,
2010 oldInvoke->getNormalDest(),
2011 oldInvoke->getUnwindDest(),
2012 newArgs, "",
2013 callSite.getInstruction());
2014 }
2015 newArgs.clear(); // for the next iteration
2016
2017 if (!newCall->getType()->isVoidTy())
2018 newCall->takeName(callSite.getInstruction());
2019 newCall.setAttributes(
2020 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2021 newCall.setCallingConv(callSite.getCallingConv());
2022
2023 // Finally, remove the old call, replacing any uses with the new one.
2024 if (!callSite->use_empty())
2025 callSite->replaceAllUsesWith(newCall.getInstruction());
2026
2027 // Copy debug location attached to CI.
2028 if (!callSite->getDebugLoc().isUnknown())
2029 newCall->setDebugLoc(callSite->getDebugLoc());
2030 callSite->eraseFromParent();
2031 }
2032}
2033
Chris Lattner36797ab2009-05-05 06:16:31 +00002034/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2035/// implement a function with no prototype, e.g. "int foo() {}". If there are
2036/// existing call uses of the old function in the module, this adjusts them to
2037/// call the new function directly.
2038///
2039/// This is not just a cleanup: the always_inline pass requires direct calls to
2040/// functions to be able to inline them. If there is a bitcast in the way, it
2041/// won't inline them. Instcombine normally deletes these calls, but it isn't
2042/// run at -O0.
2043static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2044 llvm::Function *NewFn) {
2045 // If we're redefining a global as a function, don't transform it.
John McCall49954ca2012-12-12 22:21:47 +00002046 if (!isa<llvm::Function>(Old)) return;
Mike Stump11289f42009-09-09 15:08:12 +00002047
John McCall49954ca2012-12-12 22:21:47 +00002048 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattner36797ab2009-05-05 06:16:31 +00002049}
2050
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00002051void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2052 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2053 // If we have a definition, this might be a deferred decl. If the
2054 // instantiation is explicit, make sure we emit it at the end.
2055 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2056 GetAddrOfGlobalVar(VD);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00002057
2058 EmitTopLevelDecl(VD);
Rafael Espindola189fa742012-03-05 10:54:55 +00002059}
Daniel Dunbar9c426522008-07-29 23:18:29 +00002060
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002061void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2062 llvm::GlobalValue *GV) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00002063 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalla738c252011-03-09 04:27:21 +00002064
John McCall46288ef2011-03-09 08:12:35 +00002065 // Compute the function info and LLVM type.
John McCalla729c622012-02-17 03:33:10 +00002066 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2067 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalla738c252011-03-09 04:27:21 +00002068
Chris Lattnereb7466d2009-05-12 20:58:15 +00002069 // Get or create the prototype for the function.
Rafael Espindola94abb8f2013-12-09 04:29:47 +00002070 llvm::Constant *Entry =
Rafael Espindolacd7743b2013-12-09 16:01:03 +00002071 GV ? GV
2072 : GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002073
Chris Lattnera85d68e2009-03-21 09:25:43 +00002074 // Strip off a bitcast if we got one back.
2075 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2076 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2077 Entry = CE->getOperand(0);
2078 }
Mike Stump11289f42009-09-09 15:08:12 +00002079
Argyrios Kyrtzidisf405dd62013-11-23 18:41:35 +00002080 if (!cast<llvm::GlobalValue>(Entry)->isDeclaration()) {
2081 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2082 return;
2083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
Chris Lattnera85d68e2009-03-21 09:25:43 +00002085 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00002086 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002087
Daniel Dunbar99d28352009-03-09 23:53:08 +00002088 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00002089 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00002090 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00002091
Chris Lattner5eaee562009-03-21 08:38:50 +00002092 // F is the Function* for the one with the wrong type, we must make a new
2093 // Function* and update everything that used F (a declaration) with the new
2094 // Function* (which will be a definition).
2095 //
2096 // This happens if there is a prototype for a function
2097 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00002098 // (e.g. "int f(int x)"). Move the old function aside so that it
2099 // doesn't interfere with GetAddrOfFunction.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002100 OldFn->setName(StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00002101 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00002102
John McCall49954ca2012-12-12 22:21:47 +00002103 // This might be an implementation of a function without a
2104 // prototype, in which case, try to do special replacement of
2105 // calls which match the new prototype. The really key thing here
2106 // is that we also potentially drop arguments from the call site
2107 // so as to make a direct call, which makes the inliner happier
2108 // and suppresses a number of optimizer warnings (!) about
2109 // dropping arguments.
2110 if (!OldFn->use_empty()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00002111 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00002112 OldFn->removeDeadConstantUsers();
2113 }
Mike Stump11289f42009-09-09 15:08:12 +00002114
Chris Lattner5eaee562009-03-21 08:38:50 +00002115 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00002116 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00002117 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00002118 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00002119 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2120 }
Mike Stump11289f42009-09-09 15:08:12 +00002121
Chris Lattner5eaee562009-03-21 08:38:50 +00002122 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00002123 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00002124
Chris Lattnera85d68e2009-03-21 09:25:43 +00002125 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00002126 }
Mike Stump11289f42009-09-09 15:08:12 +00002127
John McCall8e7cb6d2010-11-02 21:04:24 +00002128 // We need to set linkage and visibility on the function before
2129 // generating code for it because various parts of IR generation
2130 // want to propagate this information down (e.g. to local static
2131 // declarations).
Chris Lattnera85d68e2009-03-21 09:25:43 +00002132 llvm::Function *Fn = cast<llvm::Function>(Entry);
Peter Collingbourne4d90dba2013-06-05 17:49:37 +00002133 setFunctionLinkage(GD, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002134
John McCall8e7cb6d2010-11-02 21:04:24 +00002135 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00002136 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00002137
Richard Smithdf931ce2013-04-06 05:00:46 +00002138 MaybeHandleStaticInExternC(D, Fn);
2139
John McCalla738c252011-03-09 04:27:21 +00002140 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00002141
Daniel Dunbar38932572009-04-14 08:05:55 +00002142 SetFunctionDefinitionAttributes(D, Fn);
2143 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00002144
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002145 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002146 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002147 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00002148 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002149 if (D->hasAttr<AnnotateAttr>())
2150 AddGlobalAnnotations(D, Fn);
Justin Bogneref512b92014-01-06 22:27:43 +00002151
2152 llvm::Function *PGOInit = CodeGenPGO::emitInitialization(*this);
2153 if (PGOInit)
2154 AddGlobalCtor(PGOInit, 0);
Daniel Dunbar9c426522008-07-29 23:18:29 +00002155}
2156
John McCall7ec50432010-03-19 23:29:14 +00002157void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2158 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002159 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00002160 assert(AA && "Not an alias?");
2161
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002162 StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00002163
John McCall7ec50432010-03-19 23:29:14 +00002164 // If there is a definition in the module, then it wins over the alias.
2165 // This is dubious, but allow it to be safe. Just ignore the alias.
2166 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2167 if (Entry && !Entry->isDeclaration())
2168 return;
2169
Rafael Espindola208b5c02013-10-22 19:26:13 +00002170 Aliases.push_back(GD);
2171
Chris Lattner2192fe52011-07-18 04:24:23 +00002172 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00002173
2174 // Create a reference to the named value. This ensures that it is emitted
2175 // if a deferred decl.
2176 llvm::Constant *Aliasee;
2177 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergba036122012-10-05 23:12:53 +00002178 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson3c239482011-02-05 04:35:53 +00002179 /*ForVTable=*/false);
Chris Lattner54041692009-03-22 21:47:11 +00002180 else
John McCall7ec50432010-03-19 23:29:14 +00002181 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00002182 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00002183
2184 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00002185 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00002186 new llvm::GlobalAlias(Aliasee->getType(),
2187 llvm::Function::ExternalLinkage,
2188 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00002189
Chris Lattner54041692009-03-22 21:47:11 +00002190 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00002191 assert(Entry->isDeclaration());
2192
Chris Lattner54041692009-03-22 21:47:11 +00002193 // If there is a declaration in the module, then we had an extern followed
2194 // by the alias, as in:
2195 // extern int test6();
2196 // ...
2197 // int test6() __attribute__((alias("test7")));
2198 //
2199 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00002200 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00002201
Owen Andersonade90fd2009-07-29 18:54:39 +00002202 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00002203 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00002204 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00002205 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00002206 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00002207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
Daniel Dunbar38932572009-04-14 08:05:55 +00002209 // Set attributes which are particular to an alias; this is a
2210 // specialization of the attributes which may be set on a global
2211 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00002212 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002213 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2214 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00002215 if (FD->hasBody())
Nico Rieckbb0554f2014-01-14 15:23:53 +00002216 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar38932572009-04-14 08:05:55 +00002217 } else {
Nico Rieckbb0554f2014-01-14 15:23:53 +00002218 GA->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
Daniel Dunbar38932572009-04-14 08:05:55 +00002219 }
Mike Stump11289f42009-09-09 15:08:12 +00002220 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00002221 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002222 D->isWeakImported()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00002223 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2224 }
2225
2226 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00002227}
2228
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002229llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner54b16772011-07-23 17:14:25 +00002230 ArrayRef<llvm::Type*> Tys) {
Jay Foadb804a2b2011-07-12 14:06:48 +00002231 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002232 Tys);
Chris Lattnerb8be97e2007-12-18 00:25:38 +00002233}
Chris Lattner1eec6602007-08-31 04:31:45 +00002234
Daniel Dunbar64509b22009-07-23 22:52:48 +00002235static llvm::StringMapEntry<llvm::Constant*> &
2236GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2237 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00002238 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00002239 bool &IsUTF16,
2240 unsigned &StringLength) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002241 StringRef String = Literal->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002242 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002243
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002244 // Check for simple case.
2245 if (!Literal->containsNonAsciiOrNull()) {
2246 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002247 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00002248 }
2249
Bill Wendling82b87f12012-03-30 00:26:17 +00002250 // Otherwise, convert the UTF8 literals into a string of shorts.
2251 IsUTF16 = true;
2252
2253 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divackye6377112012-09-06 15:59:27 +00002254 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00002255 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00002256
Fariborz Jahanian535618b2010-09-07 19:57:04 +00002257 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2258 &ToPtr, ToPtr + NumBytes,
2259 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00002260
Daniel Dunbar91ade142009-07-23 23:41:22 +00002261 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00002262 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00002263
Bill Wendling82b87f12012-03-30 00:26:17 +00002264 // Add an explicit null.
2265 *ToPtr = 0;
2266 return Map.
2267 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2268 (StringLength + 1) * 2));
Daniel Dunbar64509b22009-07-23 22:52:48 +00002269}
2270
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002271static llvm::StringMapEntry<llvm::Constant*> &
2272GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling07635cc2012-03-29 22:12:09 +00002273 const StringLiteral *Literal,
2274 unsigned &StringLength) {
2275 StringRef String = Literal->getString();
2276 StringLength = String.size();
2277 return Map.GetOrCreateValue(String);
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002278}
2279
Daniel Dunbar64509b22009-07-23 22:52:48 +00002280llvm::Constant *
2281CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2282 unsigned StringLength = 0;
2283 bool isUTF16 = false;
2284 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00002285 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002286 getDataLayout().isLittleEndian(),
Daniel Dunbar91ade142009-07-23 23:41:22 +00002287 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002288
Daniel Dunbar64509b22009-07-23 22:52:48 +00002289 if (llvm::Constant *C = Entry.getValue())
2290 return C;
Mike Stump11289f42009-09-09 15:08:12 +00002291
Chris Lattnerece04092012-02-07 00:39:47 +00002292 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbard644ad62008-08-23 18:37:06 +00002293 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002294 llvm::Value *V;
2295
Chris Lattneraa64ca22009-07-16 16:48:25 +00002296 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00002297 if (!CFConstantStringClassRef) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002298 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00002299 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00002300 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00002301 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00002302 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002303 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2304 CFConstantStringClassRef = V;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002305 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002306 else
2307 V = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00002308
Anders Carlssonc2480a52008-11-15 18:54:24 +00002309 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00002310
Chris Lattner2192fe52011-07-18 04:24:23 +00002311 llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00002312 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2313
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002314 llvm::Constant *Fields[4];
Douglas Gregor91f84212008-12-11 16:49:14 +00002315
Anders Carlssonb04ea612007-08-21 00:21:21 +00002316 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002317 Fields[0] = cast<llvm::ConstantExpr>(V);
Mike Stump11289f42009-09-09 15:08:12 +00002318
Anders Carlssonb04ea612007-08-21 00:21:21 +00002319 // Flags.
Chris Lattner2192fe52011-07-18 04:24:23 +00002320 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00002321 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00002322 llvm::ConstantInt::get(Ty, 0x07C8);
2323
Anders Carlssonb04ea612007-08-21 00:21:21 +00002324 // String pointer.
Bill Wendling82b87f12012-03-30 00:26:17 +00002325 llvm::Constant *C = 0;
2326 if (isUTF16) {
2327 ArrayRef<uint16_t> Arr =
David Greene0a528db2013-01-15 22:09:41 +00002328 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2329 const_cast<char *>(Entry.getKey().data())),
Bill Wendling82b87f12012-03-30 00:26:17 +00002330 Entry.getKey().size() / 2);
2331 C = llvm::ConstantDataArray::get(VMContext, Arr);
2332 } else {
2333 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2334 }
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002335
Bill Wendling86131f22012-01-10 08:46:39 +00002336 // Note: -fwritable-strings doesn't make the backing store strings of
2337 // CFStrings writable. (See <rdar://problem/10657500>)
Mike Stump11289f42009-09-09 15:08:12 +00002338 llvm::GlobalVariable *GV =
Rafael Espindolae1bd71f2014-01-21 02:57:56 +00002339 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2340 llvm::GlobalValue::PrivateLinkage, C, ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00002341 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002342 // Don't enforce the target's minimum global alignment, since the only use
2343 // of the string is via this class initializer.
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002344 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2345 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2346 // that changes the section it ends in, which surprises ld64.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002347 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00002348 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2349 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002350 GV->setSection("__TEXT,__ustring");
Daniel Dunbar9c8cd4c2011-04-12 23:30:52 +00002351 } else {
2352 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2353 GV->setAlignment(Align.getQuantity());
Rafael Espindolad19f80a2014-01-20 20:33:18 +00002354 GV->setSection("__TEXT,__cstring,cstring_literals");
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00002355 }
Bill Wendling82b87f12012-03-30 00:26:17 +00002356
2357 // String.
Jay Foaded8db7d2011-07-21 14:31:17 +00002358 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson157c3212009-08-16 05:55:31 +00002359
Bill Wendling82b87f12012-03-30 00:26:17 +00002360 if (isUTF16)
2361 // Cast the UTF16 string to the correct type.
2362 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2363
Anders Carlssonb04ea612007-08-21 00:21:21 +00002364 // String length.
2365 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00002366 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00002367
Anders Carlssonb04ea612007-08-21 00:21:21 +00002368 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00002369 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00002370 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2371 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00002372 "_unnamed_cfstring_");
Rafael Espindola8ff16102014-01-20 20:13:11 +00002373 GV->setSection("__DATA,__cfstring");
Daniel Dunbar64509b22009-07-23 22:52:48 +00002374 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00002375
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00002376 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00002377}
Chris Lattnerfb300092007-11-28 05:34:05 +00002378
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002379llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002380CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002381 unsigned StringLength = 0;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002382 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002383 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002384
2385 if (llvm::Constant *C = Entry.getValue())
2386 return C;
2387
Chris Lattner00a10ca2012-02-06 22:47:00 +00002388 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002389 llvm::Constant *Zeros[] = { Zero, Zero };
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002390 llvm::Value *V;
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00002391 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002392 if (!ConstantStringClassRef) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002393 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2192fe52011-07-18 04:24:23 +00002394 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002395 llvm::Constant *GV;
John McCall5fb5df92012-06-20 06:18:46 +00002396 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002397 std::string str =
2398 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2399 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002400 GV = getObjCRuntime().GetClassGlobal(str);
2401 // Make sure the result is of the correct type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002402 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002403 V = llvm::ConstantExpr::getBitCast(GV, PTy);
2404 ConstantStringClassRef = V;
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002405 } else {
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002406 std::string str =
2407 StringClass.empty() ? "_NSConstantStringClassReference"
2408 : "_" + StringClass + "ClassReference";
Chris Lattner2192fe52011-07-18 04:24:23 +00002409 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanianccdfa392011-05-17 22:46:11 +00002410 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian7bd3d1c2011-05-17 22:21:16 +00002411 // Decay array -> ptr
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002412 V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
2413 ConstantStringClassRef = V;
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00002414 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002415 }
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002416 else
2417 V = ConstantStringClassRef;
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002418
2419 if (!NSConstantStringType) {
2420 // Construct the type for a constant NSString.
Alp Toker2dea15b2013-12-17 01:22:38 +00002421 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002422 D->startDefinition();
2423
2424 QualType FieldTypes[3];
2425
2426 // const int *isa;
2427 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2428 // const char *str;
2429 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2430 // unsigned int length;
2431 FieldTypes[2] = Context.UnsignedIntTy;
2432
2433 // Create fields
2434 for (unsigned i = 0; i < 3; ++i) {
2435 FieldDecl *Field = FieldDecl::Create(Context, D,
2436 SourceLocation(),
2437 SourceLocation(), 0,
2438 FieldTypes[i], /*TInfo=*/0,
2439 /*BitWidth=*/0,
2440 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002441 ICIS_NoInit);
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002442 Field->setAccess(AS_public);
2443 D->addDecl(Field);
2444 }
2445
2446 D->completeDefinition();
2447 QualType NSTy = Context.getTagDeclType(D);
2448 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2449 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002450
Benjamin Kramer22d24c22011-10-15 12:20:02 +00002451 llvm::Constant *Fields[3];
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002452
2453 // Class pointer.
Fariborz Jahaniand1b67782013-04-16 15:25:39 +00002454 Fields[0] = cast<llvm::ConstantExpr>(V);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002455
2456 // String pointer.
Chris Lattner9c818332012-02-05 02:30:40 +00002457 llvm::Constant *C =
2458 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002459
2460 llvm::GlobalValue::LinkageTypes Linkage;
2461 bool isConstant;
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002462 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikiebbafb8a2012-03-11 07:00:24 +00002463 isConstant = !LangOpts.WritableStrings;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002464
2465 llvm::GlobalVariable *GV =
2466 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2467 ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00002468 GV->setUnnamedAddr(true);
Ulrich Weigandfa806422013-05-06 16:23:57 +00002469 // Don't enforce the target's minimum global alignment, since the only use
2470 // of the string is via this class initializer.
Fariborz Jahaniana52b1f72011-05-13 18:13:10 +00002471 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2472 GV->setAlignment(Align.getQuantity());
Jay Foaded8db7d2011-07-21 14:31:17 +00002473 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002474
2475 // String length.
Chris Lattner2192fe52011-07-18 04:24:23 +00002476 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002477 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2478
2479 // The struct.
Douglas Gregorabf4e0d2011-08-09 15:54:21 +00002480 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002481 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2482 llvm::GlobalVariable::PrivateLinkage, C,
2483 "_unnamed_nsstring_");
Rafael Espindola63582d62014-01-20 15:19:43 +00002484 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2485 const char *NSStringNonFragileABISection =
Rafael Espindola8ff16102014-01-20 20:13:11 +00002486 "__DATA,__objc_stringobj,regular,no_dead_strip";
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002487 // FIXME. Fix section.
Rafael Espindola8ff16102014-01-20 20:13:11 +00002488 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2489 ? NSStringNonFragileABISection
2490 : NSStringSection);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00002491 Entry.setValue(GV);
2492
2493 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00002494}
2495
Douglas Gregor636e2002011-08-09 17:23:49 +00002496QualType CodeGenModule::getObjCFastEnumerationStateType() {
2497 if (ObjCFastEnumerationStateType.isNull()) {
Alp Toker2dea15b2013-12-17 01:22:38 +00002498 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
Douglas Gregor636e2002011-08-09 17:23:49 +00002499 D->startDefinition();
2500
2501 QualType FieldTypes[] = {
2502 Context.UnsignedLongTy,
2503 Context.getPointerType(Context.getObjCIdType()),
2504 Context.getPointerType(Context.UnsignedLongTy),
2505 Context.getConstantArrayType(Context.UnsignedLongTy,
2506 llvm::APInt(32, 5), ArrayType::Normal, 0)
2507 };
2508
2509 for (size_t i = 0; i < 4; ++i) {
2510 FieldDecl *Field = FieldDecl::Create(Context,
2511 D,
2512 SourceLocation(),
2513 SourceLocation(), 0,
2514 FieldTypes[i], /*TInfo=*/0,
2515 /*BitWidth=*/0,
2516 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002517 ICIS_NoInit);
Douglas Gregor636e2002011-08-09 17:23:49 +00002518 Field->setAccess(AS_public);
2519 D->addDecl(Field);
2520 }
2521
2522 D->completeDefinition();
2523 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2524 }
2525
2526 return ObjCFastEnumerationStateType;
2527}
2528
Eli Friedmanfcec6302011-11-01 02:23:42 +00002529llvm::Constant *
2530CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2531 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2532
2533 // Don't emit it as the address of the string, emit the string data itself
2534 // as an inline array.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002535 if (E->getCharByteWidth() == 1) {
2536 SmallString<64> Str(E->getString());
2537
2538 // Resize the string to the right size, which is indicated by its type.
2539 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2540 Str.resize(CAT->getSize().getZExtValue());
2541 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2542 }
Chris Lattner9c818332012-02-05 02:30:40 +00002543
2544 llvm::ArrayType *AType =
2545 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2546 llvm::Type *ElemTy = AType->getElementType();
2547 unsigned NumElements = AType->getNumElements();
Chris Lattner02cb1712012-02-06 22:52:04 +00002548
2549 // Wide strings have either 2-byte or 4-byte elements.
2550 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2551 SmallVector<uint16_t, 32> Elements;
2552 Elements.reserve(NumElements);
2553
2554 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2555 Elements.push_back(E->getCodeUnit(i));
2556 Elements.resize(NumElements);
2557 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner9c818332012-02-05 02:30:40 +00002558 }
2559
Chris Lattner02cb1712012-02-06 22:52:04 +00002560 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2561 SmallVector<uint32_t, 32> Elements;
2562 Elements.reserve(NumElements);
2563
2564 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2565 Elements.push_back(E->getCodeUnit(i));
2566 Elements.resize(NumElements);
2567 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002568}
2569
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002570/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2571/// constant array for the given string literal.
2572llvm::Constant *
2573CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
Ulrich Weigandfa806422013-05-06 16:23:57 +00002574 CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
Eli Friedmanfcec6302011-11-01 02:23:42 +00002575 if (S->isAscii() || S->isUTF8()) {
Chris Lattner00a10ca2012-02-06 22:47:00 +00002576 SmallString<64> Str(S->getString());
2577
2578 // Resize the string to the right size, which is indicated by its type.
2579 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2580 Str.resize(CAT->getSize().getZExtValue());
2581 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
Eli Friedman49ddc5f2009-11-16 05:55:46 +00002582 }
Eli Friedmanfcec6302011-11-01 02:23:42 +00002583
Chris Lattner00a10ca2012-02-06 22:47:00 +00002584 // FIXME: the following does not memoize wide strings.
Eli Friedmanfcec6302011-11-01 02:23:42 +00002585 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2586 llvm::GlobalVariable *GV =
2587 new llvm::GlobalVariable(getModule(),C->getType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002588 !LangOpts.WritableStrings,
Eli Friedmanfcec6302011-11-01 02:23:42 +00002589 llvm::GlobalValue::PrivateLinkage,
2590 C,".str");
Seth Cantrellc9196652012-01-18 12:11:32 +00002591
Eli Friedmanfcec6302011-11-01 02:23:42 +00002592 GV->setAlignment(Align.getQuantity());
2593 GV->setUnnamedAddr(true);
Eli Friedmanfcec6302011-11-01 02:23:42 +00002594 return GV;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002595}
2596
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002597/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2598/// array for the given ObjCEncodeExpr node.
2599llvm::Constant *
2600CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2601 std::string Str;
2602 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00002603
2604 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002605}
2606
2607
Chris Lattner36fc8792008-02-11 00:02:17 +00002608/// GenerateWritableString -- Creates storage for a string literal.
John McCall9b24df42011-08-04 01:03:22 +00002609static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattnerfb300092007-11-28 05:34:05 +00002610 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00002611 CodeGenModule &CGM,
John McCall9b24df42011-08-04 01:03:22 +00002612 const char *GlobalName,
2613 unsigned Alignment) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002614 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00002615 llvm::Constant *C =
Chris Lattner9c818332012-02-05 02:30:40 +00002616 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00002617
Joey Gouly561bba22013-11-14 18:26:10 +00002618 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
2619 unsigned AddrSpace = 0;
2620 if (CGM.getLangOpts().OpenCL)
2621 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2622
Chris Lattnerfb300092007-11-28 05:34:05 +00002623 // Create a global variable for this string
Joey Gouly561bba22013-11-14 18:26:10 +00002624 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
2625 CGM.getModule(), C->getType(), constant,
2626 llvm::GlobalValue::PrivateLinkage, C, GlobalName, 0,
2627 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
John McCall9b24df42011-08-04 01:03:22 +00002628 GV->setAlignment(Alignment);
Rafael Espindolab7f60e32011-01-10 22:34:03 +00002629 GV->setUnnamedAddr(true);
2630 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002631}
2632
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002633/// GetAddrOfConstantString - Returns a pointer to a character array
2634/// containing the literal. This contents are exactly that of the
2635/// given string, i.e. it will not be null terminated automatically;
2636/// see GetAddrOfConstantCString. Note that whether the result is
2637/// actually a pointer to an LLVM constant depends on
2638/// Feature.WriteableStrings.
2639///
2640/// The result has pointer to array type.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002641llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCall9b24df42011-08-04 01:03:22 +00002642 const char *GlobalName,
2643 unsigned Alignment) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002644 // Get the default prefix if a name wasn't specified.
2645 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00002646 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002647
Ulrich Weigandfa806422013-05-06 16:23:57 +00002648 if (Alignment == 0)
2649 Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
2650 .getQuantity();
2651
Daniel Dunbar08b216a2009-03-31 23:42:16 +00002652 // Don't share any string literals if strings aren't constant.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002653 if (LangOpts.WritableStrings)
John McCall9b24df42011-08-04 01:03:22 +00002654 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump11289f42009-09-09 15:08:12 +00002655
John McCall9b24df42011-08-04 01:03:22 +00002656 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002657 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattnerfb300092007-11-28 05:34:05 +00002658
John McCall9b24df42011-08-04 01:03:22 +00002659 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2660 if (Alignment > GV->getAlignment()) {
2661 GV->setAlignment(Alignment);
2662 }
2663 return GV;
2664 }
Chris Lattnerfb300092007-11-28 05:34:05 +00002665
2666 // Create a global variable for this.
Chris Lattner00a10ca2012-02-06 22:47:00 +00002667 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2668 Alignment);
John McCall9b24df42011-08-04 01:03:22 +00002669 Entry.setValue(GV);
2670 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00002671}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002672
2673/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002674/// array containing the literal and a terminating '\0'
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002675/// character. The result has pointer to array type.
Benjamin Kramer0cd19fb2011-03-05 13:45:23 +00002676llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCall9b24df42011-08-04 01:03:22 +00002677 const char *GlobalName,
2678 unsigned Alignment) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002679 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCall9b24df42011-08-04 01:03:22 +00002680 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00002681}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002682
Richard Smithe6c01442013-06-05 00:46:14 +00002683llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
Richard Smitha509f2f2013-06-14 03:07:01 +00002684 const MaterializeTemporaryExpr *E, const Expr *Init) {
Richard Smithe6c01442013-06-05 00:46:14 +00002685 assert((E->getStorageDuration() == SD_Static ||
2686 E->getStorageDuration() == SD_Thread) && "not a global temporary");
2687 const VarDecl *VD = cast<VarDecl>(E->getExtendingDecl());
2688
2689 // If we're not materializing a subobject of the temporary, keep the
2690 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
Richard Smitha509f2f2013-06-14 03:07:01 +00002691 QualType MaterializedType = Init->getType();
2692 if (Init == E->GetTemporaryExpr())
2693 MaterializedType = E->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00002694
2695 llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
2696 if (Slot)
2697 return Slot;
2698
2699 // FIXME: If an externally-visible declaration extends multiple temporaries,
2700 // we need to give each temporary the same name in every translation unit (and
2701 // we also need to make the temporaries externally-visible).
2702 SmallString<256> Name;
2703 llvm::raw_svector_ostream Out(Name);
2704 getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
2705 Out.flush();
2706
Richard Smithe6c01442013-06-05 00:46:14 +00002707 APValue *Value = 0;
2708 if (E->getStorageDuration() == SD_Static) {
Richard Smitha509f2f2013-06-14 03:07:01 +00002709 // We might have a cached constant initializer for this temporary. Note
2710 // that this might have a different value from the value computed by
2711 // evaluating the initializer if the surrounding constant expression
2712 // modifies the temporary.
Richard Smithe6c01442013-06-05 00:46:14 +00002713 Value = getContext().getMaterializedTemporaryValue(E, false);
2714 if (Value && Value->isUninit())
2715 Value = 0;
2716 }
2717
Richard Smitha509f2f2013-06-14 03:07:01 +00002718 // Try evaluating it now, it might have a constant initializer.
2719 Expr::EvalResult EvalResult;
2720 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
2721 !EvalResult.hasSideEffects())
2722 Value = &EvalResult.Val;
2723
2724 llvm::Constant *InitialValue = 0;
2725 bool Constant = false;
2726 llvm::Type *Type;
Richard Smithe6c01442013-06-05 00:46:14 +00002727 if (Value) {
2728 // The temporary has a constant initializer, use it.
Richard Smitha509f2f2013-06-14 03:07:01 +00002729 InitialValue = EmitConstantValue(*Value, MaterializedType, 0);
2730 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
2731 Type = InitialValue->getType();
Richard Smithe6c01442013-06-05 00:46:14 +00002732 } else {
Richard Smitha509f2f2013-06-14 03:07:01 +00002733 // No initializer, the initialization will be provided when we
Richard Smithe6c01442013-06-05 00:46:14 +00002734 // initialize the declaration which performed lifetime extension.
Richard Smitha509f2f2013-06-14 03:07:01 +00002735 Type = getTypes().ConvertTypeForMem(MaterializedType);
Richard Smithe6c01442013-06-05 00:46:14 +00002736 }
2737
2738 // Create a global variable for this lifetime-extended temporary.
2739 llvm::GlobalVariable *GV =
Richard Smitha509f2f2013-06-14 03:07:01 +00002740 new llvm::GlobalVariable(getModule(), Type, Constant,
2741 llvm::GlobalValue::PrivateLinkage,
2742 InitialValue, Name.c_str());
Richard Smithe6c01442013-06-05 00:46:14 +00002743 GV->setAlignment(
Richard Smitha509f2f2013-06-14 03:07:01 +00002744 getContext().getTypeAlignInChars(MaterializedType).getQuantity());
Richard Smithe6c01442013-06-05 00:46:14 +00002745 if (VD->getTLSKind())
2746 setTLSMode(GV, *VD);
2747 Slot = GV;
2748 return GV;
2749}
2750
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002751/// EmitObjCPropertyImplementations - Emit information for synthesized
2752/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00002753void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002754 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00002755 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002756 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002757 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00002758
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002759 // Dynamic is just for type-checking.
2760 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2761 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2762
2763 // Determine which methods need to be implemented, some may have
Jordan Rosed01e83a2012-10-10 16:42:25 +00002764 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002765 // we want, that just indicates if the decl came from a
2766 // property. What we want to know is if the method is defined in
2767 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002768 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002769 CodeGenFunction(*this).GenerateObjCGetter(
2770 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002771 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002772 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00002773 CodeGenFunction(*this).GenerateObjCSetter(
2774 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002775 }
2776 }
2777}
2778
John McCall6a4fa522011-03-22 07:05:39 +00002779static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosea91768e2011-07-22 02:08:32 +00002780 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2781 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00002782 ivar; ivar = ivar->getNextIvar())
2783 if (ivar->getType().isDestructedType())
2784 return true;
2785
2786 return false;
2787}
2788
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002789/// EmitObjCIvarInitializations - Emit information for ivar initialization
2790/// for an implementation.
2791void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCall6a4fa522011-03-22 07:05:39 +00002792 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2793 if (needsDestructMethod(D)) {
2794 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2795 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2796 ObjCMethodDecl *DTORMethod =
2797 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002798 cxxSelector, getContext().VoidTy, 0, D,
2799 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002800 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002801 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCall6a4fa522011-03-22 07:05:39 +00002802 D->addInstanceMethod(DTORMethod);
2803 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCall0d54a172012-10-17 04:53:31 +00002804 D->setHasDestructors(true);
John McCall6a4fa522011-03-22 07:05:39 +00002805 }
2806
2807 // If the implementation doesn't have any ivar initializers, we don't need
2808 // a .cxx_construct.
David Chisnalla9e54602011-03-17 14:19:08 +00002809 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002810 return;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002811
John McCall6a4fa522011-03-22 07:05:39 +00002812 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2813 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002814 // The constructor returns 'self'.
2815 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2816 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002817 D->getLocation(),
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00002818 cxxSelector,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002819 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002820 D, /*isInstance=*/true,
2821 /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +00002822 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis004df6e2011-08-17 19:25:08 +00002823 /*isImplicitlyDeclared=*/true,
2824 /*isDefined=*/false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002825 ObjCMethodDecl::Required);
2826 D->addInstanceMethod(CTORMethod);
2827 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCall0d54a172012-10-17 04:53:31 +00002828 D->setHasNonZeroConstructors(true);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002829}
2830
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002831/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00002832void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Aaron Ballman629afae2014-03-07 19:56:05 +00002833 for (auto *I : ND->decls()) {
2834 if (const auto *VD = dyn_cast<VarDecl>(I))
David Blaikieb00f3602013-09-04 21:07:37 +00002835 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2836 VD->getTemplateSpecializationKind() != TSK_Undeclared)
2837 continue;
Aaron Ballman629afae2014-03-07 19:56:05 +00002838 EmitTopLevelDecl(I);
David Blaikieb00f3602013-09-04 21:07:37 +00002839 }
Anders Carlsson237f3492009-04-01 00:58:25 +00002840}
2841
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002842// EmitLinkageSpec - Emit all declarations in a linkage spec.
2843void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00002844 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2845 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002846 ErrorUnsupported(LSD, "linkage spec");
2847 return;
2848 }
2849
Aaron Ballman629afae2014-03-07 19:56:05 +00002850 for (auto *I : LSD->decls()) {
Fariborz Jahanian9dd2e082012-10-26 22:20:25 +00002851 // Meta-data for ObjC class includes references to implemented methods.
2852 // Generate class's method definitions first.
Aaron Ballman629afae2014-03-07 19:56:05 +00002853 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
Aaron Ballmanaff18c02014-03-13 19:03:34 +00002854 for (auto *M : OID->methods())
2855 EmitTopLevelDecl(M);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00002856 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002857 EmitTopLevelDecl(I);
Fariborz Jahanian2d26c292012-10-26 20:22:11 +00002858 }
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002859}
2860
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002861/// EmitTopLevelDecl - Emit code for a single top level declaration.
2862void CodeGenModule::EmitTopLevelDecl(Decl *D) {
Douglas Gregor70d83e22009-06-29 17:30:29 +00002863 // Ignore dependent declarations.
2864 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2865 return;
Mike Stump11289f42009-09-09 15:08:12 +00002866
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002867 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00002868 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00002869 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002870 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00002871 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00002872 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2873 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor70d83e22009-06-29 17:30:29 +00002874 return;
Mike Stump11289f42009-09-09 15:08:12 +00002875
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002876 EmitGlobal(cast<FunctionDecl>(D));
2877 break;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002878
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002879 case Decl::Var:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002880 // Skip variable templates
2881 if (cast<VarDecl>(D)->getDescribedVarTemplate())
2882 return;
2883 case Decl::VarTemplateSpecialization:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00002884 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002885 break;
2886
John McCall32f44bd2011-04-12 01:01:22 +00002887 // Indirect fields from global anonymous structs and unions can be
2888 // ignored; only the actual variable requires IR gen support.
2889 case Decl::IndirectField:
2890 break;
2891
Anders Carlssonf7475242009-04-15 15:55:24 +00002892 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002893 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00002894 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002895 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00002896 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00002897 case Decl::UsingShadow:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002898 case Decl::ClassTemplate:
Larisse Voufo39a1e502013-08-06 01:03:05 +00002899 case Decl::VarTemplate:
2900 case Decl::VarTemplatePartialSpecialization:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00002901 case Decl::FunctionTemplate:
Richard Smith3f1b5d02011-05-05 21:57:07 +00002902 case Decl::TypeAliasTemplate:
Douglas Gregor0aa91e02011-06-05 05:04:23 +00002903 case Decl::Block:
Michael Han84324352013-02-22 17:15:32 +00002904 case Decl::Empty:
Douglas Gregorfec52632009-06-20 00:51:54 +00002905 break;
David Blaikie3e65d36a2014-02-15 21:03:07 +00002906 case Decl::Using: // using X; [C++]
2907 if (CGDebugInfo *DI = getModuleDebugInfo())
2908 DI->EmitUsingDecl(cast<UsingDecl>(*D));
2909 return;
David Blaikief121b932013-05-20 22:50:41 +00002910 case Decl::NamespaceAlias:
2911 if (CGDebugInfo *DI = getModuleDebugInfo())
2912 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
2913 return;
David Blaikie60a9fbf2013-04-26 05:41:06 +00002914 case Decl::UsingDirective: // using namespace X; [C++]
2915 if (CGDebugInfo *DI = getModuleDebugInfo())
2916 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
2917 return;
Anders Carlssonf7475242009-04-15 15:55:24 +00002918 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00002919 // Skip function templates
Francois Pichet1c229c02011-04-22 22:18:13 +00002920 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2921 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson0ade9712009-11-24 05:16:24 +00002922 return;
2923
Timur Iskhodzhanov40f2fa92013-08-04 17:30:04 +00002924 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
Anders Carlssonf7475242009-04-15 15:55:24 +00002925 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00002926 case Decl::CXXDestructor:
Francois Pichet1c229c02011-04-22 22:18:13 +00002927 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2928 return;
Reid Klecknere7de47e2013-07-22 13:51:44 +00002929 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
Anders Carlssoneaa28f72009-04-17 01:58:57 +00002930 break;
Anders Carlsson87835432009-06-11 21:22:55 +00002931
2932 case Decl::StaticAssert:
2933 // Nothing to do.
2934 break;
2935
Anders Carlssonf7475242009-04-15 15:55:24 +00002936 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00002937
Fariborz Jahanian3654e652009-03-18 22:33:24 +00002938 // Forward declarations, no (immediate) code generation.
Chris Lattnerd18136a2009-04-01 02:36:43 +00002939 case Decl::ObjCInterface:
Eric Christopherf8378ca2012-07-19 22:22:55 +00002940 case Decl::ObjCCategory:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002941 break;
2942
Douglas Gregorf6102672012-01-01 21:23:57 +00002943 case Decl::ObjCProtocol: {
2944 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2945 if (Proto->isThisDeclarationADefinition())
2946 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002947 break;
Douglas Gregorf6102672012-01-01 21:23:57 +00002948 }
2949
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002950 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002951 // Categories have properties but don't support synthesize so we
2952 // can ignore them here.
Peter Collingbournee1d20992011-07-27 20:29:46 +00002953 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002954 break;
2955
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002956 case Decl::ObjCImplementation: {
2957 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2958 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002959 EmitObjCIvarInitializations(OMD);
Peter Collingbournee1d20992011-07-27 20:29:46 +00002960 ObjCRuntime->GenerateClass(OMD);
Eric Christopher3d19de92012-04-11 05:56:05 +00002961 // Emit global variable debug information.
2962 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov9c1b9f62012-12-03 18:28:12 +00002963 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2964 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2965 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002966 break;
Mike Stump11289f42009-09-09 15:08:12 +00002967 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002968 case Decl::ObjCMethod: {
2969 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2970 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002971 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002972 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2973 break;
2974 }
Mike Stump11289f42009-09-09 15:08:12 +00002975 case Decl::ObjCCompatibleAlias:
David Chisnall92d436b2012-01-31 18:59:20 +00002976 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002977 break;
2978
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002979 case Decl::LinkageSpec:
2980 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002981 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002982
2983 case Decl::FileScopeAsm: {
2984 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002985 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00002986
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002987 const std::string &S = getModule().getModuleInlineAsm();
2988 if (S.empty())
2989 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8c02a242012-08-10 10:57:52 +00002990 else if (S.end()[-1] == '\n')
Chris Lattner84037d32011-07-23 20:04:25 +00002991 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002992 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002993 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002994 break;
2995 }
Mike Stump11289f42009-09-09 15:08:12 +00002996
Douglas Gregor6ddfca92013-01-14 17:21:00 +00002997 case Decl::Import: {
2998 ImportDecl *Import = cast<ImportDecl>(D);
2999
3000 // Ignore import declarations that come from imported modules.
3001 if (clang::Module *Owner = Import->getOwningModule()) {
3002 if (getLangOpts().CurrentModule.empty() ||
3003 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3004 break;
3005 }
3006
Douglas Gregorbc25ff42013-01-14 20:53:57 +00003007 ImportedModules.insert(Import->getImportedModule());
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003008 break;
David Blaikie0e716b42014-03-03 23:48:23 +00003009 }
3010
3011 case Decl::ClassTemplateSpecialization: {
3012 const ClassTemplateSpecializationDecl *Spec =
3013 cast<ClassTemplateSpecializationDecl>(D);
3014 if (DebugInfo &&
3015 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition)
3016 DebugInfo->completeTemplateDefinition(*Spec);
3017 }
Douglas Gregor6ddfca92013-01-14 17:21:00 +00003018
Mike Stump11289f42009-09-09 15:08:12 +00003019 default:
Mike Stump18bb9282009-05-16 07:57:57 +00003020 // Make sure we handled everything we should, every other kind is a
3021 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3022 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00003023 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3024 }
3025}
John McCall09ae0322010-07-06 23:57:41 +00003026
3027/// Turns the given pointer into a constant.
3028static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3029 const void *Ptr) {
3030 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2192fe52011-07-18 04:24:23 +00003031 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall09ae0322010-07-06 23:57:41 +00003032 return llvm::ConstantInt::get(i64, PtrInt);
3033}
3034
3035static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3036 llvm::NamedMDNode *&GlobalMetadata,
3037 GlobalDecl D,
3038 llvm::GlobalValue *Addr) {
3039 if (!GlobalMetadata)
3040 GlobalMetadata =
3041 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3042
3043 // TODO: should we report variant information for ctors/dtors?
3044 llvm::Value *Ops[] = {
3045 Addr,
3046 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
3047 };
Jay Foadea324f12011-04-21 19:59:12 +00003048 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall09ae0322010-07-06 23:57:41 +00003049}
3050
Richard Smithdf931ce2013-04-06 05:00:46 +00003051/// For each function which is declared within an extern "C" region and marked
3052/// as 'used', but has internal linkage, create an alias from the unmangled
3053/// name to the mangled name if possible. People expect to be able to refer
3054/// to such functions with an unmangled name from inline assembly within the
3055/// same translation unit.
3056void CodeGenModule::EmitStaticExternCAliases() {
Richard Smithf21c9612013-04-13 01:28:18 +00003057 for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
3058 E = StaticExternCValues.end();
3059 I != E; ++I) {
3060 IdentifierInfo *Name = I->first;
3061 llvm::GlobalValue *Val = I->second;
Richard Smith85465e62013-04-06 07:07:44 +00003062 if (Val && !getModule().getNamedValue(Name->getName()))
Rafael Espindola060062a2014-03-06 22:15:10 +00003063 addUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
Richard Smith85465e62013-04-06 07:07:44 +00003064 Name->getName(), Val, &getModule()));
3065 }
Richard Smithdf931ce2013-04-06 05:00:46 +00003066}
3067
John McCall09ae0322010-07-06 23:57:41 +00003068/// Emits metadata nodes associating all the global values in the
3069/// current module with the Decls they came from. This is useful for
3070/// projects using IR gen as a subroutine.
3071///
3072/// Since there's currently no way to associate an MDNode directly
3073/// with an llvm::GlobalValue, we create a global named metadata
3074/// with the name 'clang.global.decl.ptrs'.
3075void CodeGenModule::EmitDeclMetadata() {
3076 llvm::NamedMDNode *GlobalMetadata = 0;
3077
3078 // StaticLocalDeclMap
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003079 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall09ae0322010-07-06 23:57:41 +00003080 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
3081 I != E; ++I) {
3082 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
3083 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
3084 }
3085}
3086
3087/// Emits metadata nodes for all the local variables in the current
3088/// function.
3089void CodeGenFunction::EmitDeclMetadata() {
3090 if (LocalDeclMap.empty()) return;
3091
3092 llvm::LLVMContext &Context = getLLVMContext();
3093
3094 // Find the unique metadata ID for this name.
3095 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3096
3097 llvm::NamedMDNode *GlobalMetadata = 0;
3098
3099 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
3100 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
3101 const Decl *D = I->first;
3102 llvm::Value *Addr = I->second;
3103
3104 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3105 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foadea324f12011-04-21 19:59:12 +00003106 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall09ae0322010-07-06 23:57:41 +00003107 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3108 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3109 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3110 }
3111 }
3112}
Daniel Dunbar900546d2010-07-16 00:00:15 +00003113
Rafael Espindola3bfa4682013-10-16 19:28:50 +00003114void CodeGenModule::EmitVersionIdentMetadata() {
3115 llvm::NamedMDNode *IdentMetadata =
3116 TheModule.getOrInsertNamedMetadata("llvm.ident");
3117 std::string Version = getClangFullVersion();
3118 llvm::LLVMContext &Ctx = TheModule.getContext();
3119
3120 llvm::Value *IdentNode[] = {
3121 llvm::MDString::get(Ctx, Version)
3122 };
3123 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3124}
3125
Nick Lewycky85c011d2011-05-05 00:08:20 +00003126void CodeGenModule::EmitCoverageFile() {
3127 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky480cb992011-05-04 20:46:58 +00003128 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3129 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3130 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky85c011d2011-05-05 00:08:20 +00003131 llvm::MDString *CoverageFile =
3132 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky480cb992011-05-04 20:46:58 +00003133 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3134 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky85c011d2011-05-05 00:08:20 +00003135 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky480cb992011-05-04 20:46:58 +00003136 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
3137 GCov->addOperand(N);
3138 }
3139 }
3140 }
3141}
Nico Webercf4ff5862012-10-11 10:13:44 +00003142
3143llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
3144 QualType GuidType) {
3145 // Sema has checked that all uuid strings are of the form
3146 // "12345678-1234-1234-1234-1234567890ab".
3147 assert(Uuid.size() == 36);
David Majnemerbbecd092013-08-15 19:59:14 +00003148 for (unsigned i = 0; i < 36; ++i) {
3149 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3150 else assert(isHexDigit(Uuid[i]));
Nico Webercf4ff5862012-10-11 10:13:44 +00003151 }
Nico Webercf4ff5862012-10-11 10:13:44 +00003152
David Majnemerbbecd092013-08-15 19:59:14 +00003153 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Webercf4ff5862012-10-11 10:13:44 +00003154
David Majnemerbbecd092013-08-15 19:59:14 +00003155 llvm::Constant *Field3[8];
3156 for (unsigned Idx = 0; Idx < 8; ++Idx)
3157 Field3[Idx] = llvm::ConstantInt::get(
3158 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3159
3160 llvm::Constant *Fields[4] = {
3161 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3162 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3163 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3164 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3165 };
3166
3167 return llvm::ConstantStruct::getAnon(Fields);
Nico Webercf4ff5862012-10-11 10:13:44 +00003168}