blob: 88de91afec73ecc789bec090a13ec74b39884316 [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"
Chris Lattner984fac52009-03-26 05:00:52 +000015#include "CGDebugInfo.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000016#include "CodeGenFunction.h"
Dan Gohman947c9af2010-10-14 23:06:10 +000017#include "CodeGenTBAA.h"
Daniel Dunbar3d7c90b2008-09-08 21:33:45 +000018#include "CGCall.h"
John McCall5d865c322010-08-31 07:33:07 +000019#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000020#include "CGObjCRuntime.h"
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000021#include "TargetInfo.h"
Chandler Carruth85098242010-06-15 23:19:56 +000022#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner2ccb73b2007-06-16 00:16:26 +000023#include "clang/AST/ASTContext.h"
Ken Dyck98ca7942010-01-26 13:48:07 +000024#include "clang/AST/CharUnits.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000025#include "clang/AST/DeclObjC.h"
Chris Lattnerb8c18fa2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Douglas Gregor5dd34742010-06-21 18:41:26 +000027#include "clang/AST/DeclTemplate.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000028#include "clang/AST/Mangle.h"
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +000029#include "clang/AST/RecordLayout.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000030#include "clang/Basic/Builtins.h"
Chris Lattnerd45aa2a2007-12-02 07:19:18 +000031#include "clang/Basic/Diagnostic.h"
Nate Begemanfaae0812008-04-19 04:17:09 +000032#include "clang/Basic/SourceManager.h"
Chris Lattner09153c02007-06-22 18:48:09 +000033#include "clang/Basic/TargetInfo.h"
Steve Naroff29cae662009-04-01 15:50:34 +000034#include "clang/Basic/ConvertUTF.h"
Nate Begemanaca747a2008-03-09 03:09:36 +000035#include "llvm/CallingConv.h"
Chris Lattner1eec6602007-08-31 04:31:45 +000036#include "llvm/Module.h"
Chris Lattner09153c02007-06-22 18:48:09 +000037#include "llvm/Intrinsics.h"
Chris Lattner5e124bf2009-12-28 21:44:41 +000038#include "llvm/LLVMContext.h"
John McCallbeec5a02010-03-06 00:35:14 +000039#include "llvm/ADT/Triple.h"
Anton Korobeynikov1200aca2008-06-01 14:13:53 +000040#include "llvm/Target/TargetData.h"
Gabor Greifd0ef1342010-04-10 02:56:12 +000041#include "llvm/Support/CallSite.h"
Chris Lattner15275e52009-11-07 09:22:46 +000042#include "llvm/Support/ErrorHandling.h"
Chris Lattnerbed31442007-05-28 01:07:47 +000043using namespace clang;
44using namespace CodeGen;
45
John McCall614dbdc2010-08-22 21:01:12 +000046static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
47 switch (CGM.getContext().Target.getCXXABI()) {
48 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
49 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
50 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
51 }
52
53 llvm_unreachable("invalid C++ ABI kind");
54 return *CreateItaniumCXXABI(CGM);
55}
56
Chris Lattnerbed31442007-05-28 01:07:47 +000057
Chandler Carruthbc55fe22009-11-12 17:24:48 +000058CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
John McCall731be662010-03-04 04:29:44 +000059 llvm::Module &M, const llvm::TargetData &TD,
60 Diagnostic &diags)
Chris Lattner984fac52009-03-26 05:00:52 +000061 : BlockModule(C, M, TD, Types, *this), Context(C),
Chandler Carruthbc55fe22009-11-12 17:24:48 +000062 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
John McCall731be662010-03-04 04:29:44 +000063 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCall614dbdc2010-08-22 21:01:12 +000064 ABI(createCXXABI(*this)),
65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI),
Dan Gohman947c9af2010-10-14 23:06:10 +000066 TBAA(0),
John McCall614dbdc2010-08-22 21:01:12 +000067 VTables(*this), Runtime(0),
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000068 CFConstantStringClassRef(0), ConstantStringClassRef(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000069 VMContext(M.getContext()),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000070 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000071 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
Daniel Dunbar3348e2d2010-07-16 00:00:19 +000072 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0),
Daniel Dunbar900546d2010-07-16 00:00:15 +000073 BlockObjectAssign(0), BlockObjectDispose(0){
Daniel Dunbar8d480592008-08-11 18:12:00 +000074
Chris Lattner36376522009-03-21 07:12:05 +000075 if (!Features.ObjC1)
76 Runtime = 0;
77 else if (!Features.NeXTRuntime)
78 Runtime = CreateGNUObjCRuntime(*this);
79 else if (Features.ObjCNonFragileABI)
80 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
81 else
82 Runtime = CreateMacObjCRuntime(*this);
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000083
Dan Gohman947c9af2010-10-14 23:06:10 +000084 // Enable TBAA unless it's suppressed.
85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)
Dan Gohman2e29eb52010-10-15 20:23:12 +000086 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions(),
87 ABI.getMangleContext());
Dan Gohman947c9af2010-10-14 23:06:10 +000088
Sanjiv Gupta15cb6692008-05-08 08:54:20 +000089 // If debug info generation is enabled, create the CGDebugInfo object.
Anders Carlsson3efc6e62009-12-06 18:00:51 +000090 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
Chris Lattnera087ff92008-03-01 08:45:05 +000091}
92
93CodeGenModule::~CodeGenModule() {
Ted Kremenek2c674f62008-08-05 18:50:11 +000094 delete Runtime;
John McCall614dbdc2010-08-22 21:01:12 +000095 delete &ABI;
Dan Gohmand19ee8a2010-10-15 18:04:46 +000096 delete TBAA;
Ted Kremenek2c674f62008-08-05 18:50:11 +000097 delete DebugInfo;
98}
99
David Chisnall481e3a82010-01-23 02:40:42 +0000100void CodeGenModule::createObjCRuntime() {
101 if (!Features.NeXTRuntime)
102 Runtime = CreateGNUObjCRuntime(*this);
103 else if (Features.ObjCNonFragileABI)
104 Runtime = CreateMacNonFragileABIObjCRuntime(*this);
105 else
106 Runtime = CreateMacObjCRuntime(*this);
107}
108
Ted Kremenek2c674f62008-08-05 18:50:11 +0000109void CodeGenModule::Release() {
Chris Lattnera5ae54a2009-03-22 21:21:57 +0000110 EmitDeferred();
Eli Friedman5866fe32010-01-08 00:50:11 +0000111 EmitCXXGlobalInitFunc();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000112 EmitCXXGlobalDtorFunc();
Daniel Dunbar8d480592008-08-11 18:12:00 +0000113 if (Runtime)
114 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
115 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000116 EmitCtorList(GlobalCtors, "llvm.global_ctors");
117 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Nate Begeman7fab5782008-04-18 23:43:57 +0000118 EmitAnnotations();
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000119 EmitLLVMUsed();
John McCall09ae0322010-07-06 23:57:41 +0000120
John McCall0bdb1fd2010-09-16 06:16:50 +0000121 SimplifyPersonality();
122
John McCall09ae0322010-07-06 23:57:41 +0000123 if (getCodeGenOpts().EmitDeclMetadata)
124 EmitDeclMetadata();
Daniel Dunbar23fd4622008-10-01 00:49:24 +0000125}
126
Dan Gohman947c9af2010-10-14 23:06:10 +0000127llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
128 if (!TBAA)
129 return 0;
130 return TBAA->getTBAAInfo(QTy);
131}
132
133void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
134 llvm::MDNode *TBAAInfo) {
135 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
136}
137
John McCallbeec5a02010-03-06 00:35:14 +0000138bool CodeGenModule::isTargetDarwin() const {
139 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
140}
141
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000142/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000143/// specified stmt yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000144void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
145 bool OmitOnError) {
146 if (OmitOnError && getDiags().hasErrorOccurred())
147 return;
Mike Stump11289f42009-09-09 15:08:12 +0000148 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000149 "cannot compile this %0 yet");
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000150 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000151 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
152 << Msg << S->getSourceRange();
Chris Lattnerd45aa2a2007-12-02 07:19:18 +0000153}
Chris Lattner41af8182007-12-02 06:27:33 +0000154
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000155/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner38376f12008-01-12 07:05:38 +0000156/// specified decl yet.
Daniel Dunbarf2cf6d12008-09-04 03:43:08 +0000157void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
158 bool OmitOnError) {
159 if (OmitOnError && getDiags().hasErrorOccurred())
160 return;
Mike Stump11289f42009-09-09 15:08:12 +0000161 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
Daniel Dunbarfe2fb0a2009-02-06 19:18:03 +0000162 "cannot compile this %0 yet");
Chris Lattner38376f12008-01-12 07:05:38 +0000163 std::string Msg = Type;
Chris Lattner8488c822008-11-18 07:04:44 +0000164 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattner38376f12008-01-12 07:05:38 +0000165}
166
John McCall37bb6c92010-10-29 22:22:43 +0000167static llvm::GlobalValue::VisibilityTypes GetLLVMVisibility(Visibility V) {
168 switch (V) {
169 case DefaultVisibility: return llvm::GlobalValue::DefaultVisibility;
170 case HiddenVisibility: return llvm::GlobalValue::HiddenVisibility;
171 case ProtectedVisibility: return llvm::GlobalValue::ProtectedVisibility;
172 }
173 llvm_unreachable("unknown visibility!");
174 return llvm::GlobalValue::DefaultVisibility;
175}
176
177
Mike Stump11289f42009-09-09 15:08:12 +0000178void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlssonc6a47892011-01-29 19:39:23 +0000179 const NamedDecl *D) const {
Daniel Dunbarf5f359f2009-04-14 06:00:08 +0000180 // Internal definitions always have default visibility.
Chris Lattner6a0f9072009-04-14 05:27:13 +0000181 if (GV->hasLocalLinkage()) {
Daniel Dunbard272cca2009-04-10 20:26:50 +0000182 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar15894b72009-04-07 05:48:37 +0000183 return;
Daniel Dunbard272cca2009-04-10 20:26:50 +0000184 }
Daniel Dunbar15894b72009-04-07 05:48:37 +0000185
John McCallc273f242010-10-30 11:50:40 +0000186 // Set visibility for definitions.
187 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Anders Carlssonc6a47892011-01-29 19:39:23 +0000188 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
John McCallc273f242010-10-30 11:50:40 +0000189 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman75d69da2008-05-22 00:50:06 +0000190}
191
John McCalle16adc22010-08-04 08:34:44 +0000192/// Set the symbol visibility of type information (vtable and RTTI)
193/// associated with the given type.
194void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
195 const CXXRecordDecl *RD,
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000196 TypeVisibilityKind TVK) const {
Anders Carlssonc6a47892011-01-29 19:39:23 +0000197 setGlobalVisibility(GV, RD);
John McCalle16adc22010-08-04 08:34:44 +0000198
John McCallb3732bb2010-08-12 23:36:15 +0000199 if (!CodeGenOpts.HiddenWeakVTables)
200 return;
201
John McCalle16adc22010-08-04 08:34:44 +0000202 // We want to drop the visibility to hidden for weak type symbols.
203 // This isn't possible if there might be unresolved references
204 // elsewhere that rely on this symbol being visible.
205
John McCall5513fce92010-08-05 20:39:18 +0000206 // This should be kept roughly in sync with setThunkVisibility
207 // in CGVTables.cpp.
208
John McCalle16adc22010-08-04 08:34:44 +0000209 // Preconditions.
Anders Carlsson571e2ad2011-01-24 00:46:19 +0000210 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCalle16adc22010-08-04 08:34:44 +0000211 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
212 return;
213
214 // Don't override an explicit visibility attribute.
215 if (RD->hasAttr<VisibilityAttr>())
216 return;
217
218 switch (RD->getTemplateSpecializationKind()) {
219 // We have to disable the optimization if this is an EI definition
220 // because there might be EI declarations in other shared objects.
221 case TSK_ExplicitInstantiationDefinition:
222 case TSK_ExplicitInstantiationDeclaration:
223 return;
224
John McCall5513fce92010-08-05 20:39:18 +0000225 // Every use of a non-template class's type information has to emit it.
John McCalle16adc22010-08-04 08:34:44 +0000226 case TSK_Undeclared:
227 break;
228
John McCall5513fce92010-08-05 20:39:18 +0000229 // In theory, implicit instantiations can ignore the possibility of
230 // an explicit instantiation declaration because there necessarily
231 // must be an EI definition somewhere with default visibility. In
232 // practice, it's possible to have an explicit instantiation for
233 // an arbitrary template class, and linkers aren't necessarily able
234 // to deal with mixed-visibility symbols.
235 case TSK_ExplicitSpecialization:
John McCalle16adc22010-08-04 08:34:44 +0000236 case TSK_ImplicitInstantiation:
John McCallb3732bb2010-08-12 23:36:15 +0000237 if (!CodeGenOpts.HiddenWeakTemplateVTables)
John McCall5513fce92010-08-05 20:39:18 +0000238 return;
John McCalle16adc22010-08-04 08:34:44 +0000239 break;
240 }
241
242 // If there's a key function, there may be translation units
243 // that don't have the key function's definition. But ignore
244 // this if we're emitting RTTI under -fno-rtti.
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000245 if (!(TVK != TVK_ForRTTI) || Features.RTTI) {
John McCalle16adc22010-08-04 08:34:44 +0000246 if (Context.getKeyFunction(RD))
247 return;
Anders Carlsson265aa7c2011-01-29 20:24:48 +0000248 }
John McCalle16adc22010-08-04 08:34:44 +0000249
250 // Otherwise, drop the visibility to hidden.
251 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1e879c2011-01-11 21:44:37 +0000252 GV->setUnnamedAddr(true);
John McCalle16adc22010-08-04 08:34:44 +0000253}
254
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000255llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
256 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
257
258 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
259 if (!Str.empty())
260 return Str;
261
John McCall5d865c322010-08-31 07:33:07 +0000262 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000263 IdentifierInfo *II = ND->getIdentifier();
264 assert(II && "Attempt to mangle unnamed decl.");
265
266 Str = II->getName();
267 return Str;
268 }
269
270 llvm::SmallString<256> Buffer;
271 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000272 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000273 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
John McCall5d865c322010-08-31 07:33:07 +0000274 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000275 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000276 getCXXABI().getMangleContext().mangleBlock(BD, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000277 else
John McCall5d865c322010-08-31 07:33:07 +0000278 getCXXABI().getMangleContext().mangleName(ND, Buffer);
Anders Carlsson2e2f4d22010-06-22 16:05:32 +0000279
280 // Allocate space for the mangled name.
281 size_t Length = Buffer.size();
282 char *Name = MangledNamesAllocator.Allocate<char>(Length);
283 std::copy(Buffer.begin(), Buffer.end(), Name);
284
285 Str = llvm::StringRef(Name, Length);
286
287 return Str;
288}
289
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000290void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
291 const BlockDecl *BD) {
292 MangleContext &MangleCtx = getCXXABI().getMangleContext();
293 const Decl *D = GD.getDecl();
294 if (D == 0)
295 MangleCtx.mangleGlobalBlock(BD, Buffer.getBuffer());
296 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
297 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Buffer.getBuffer());
298 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
299 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Buffer.getBuffer());
300 else
301 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Buffer.getBuffer());
Anders Carlsson635186a2010-06-09 02:36:32 +0000302}
303
John McCall7ec50432010-03-19 23:29:14 +0000304llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
305 return getModule().getNamedValue(Name);
Douglas Gregor5fec5b02009-02-13 00:10:09 +0000306}
307
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000308/// AddGlobalCtor - Add a function to the list that will be called before
309/// main() runs.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000310void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000311 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000312 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000313}
314
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000315/// AddGlobalDtor - Add a function to the list that will be called
316/// when the module is unloaded.
317void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbardec798b2009-01-13 02:25:00 +0000318 // FIXME: Type coercion of void()* types.
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000319 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
320}
321
322void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
323 // Ctor function type is void()*.
324 llvm::FunctionType* CtorFTy =
Benjamin Kramer1e188892011-01-22 12:15:57 +0000325 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000326 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000327
328 // Get the type of a ctor entry, { i32, void ()* }.
Mike Stump11289f42009-09-09 15:08:12 +0000329 llvm::StructType* CtorStructTy =
330 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
Owen Anderson9793f0e2009-07-29 22:16:19 +0000331 llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000332
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000333 // Construct the constructor and destructor arrays.
334 std::vector<llvm::Constant*> Ctors;
335 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
336 std::vector<llvm::Constant*> S;
Mike Stump11289f42009-09-09 15:08:12 +0000337 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
Owen Anderson41a75022009-08-13 21:57:51 +0000338 I->second, false));
Owen Andersonade90fd2009-07-29 18:54:39 +0000339 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
Owen Anderson0e0189d2009-07-27 22:29:56 +0000340 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000341 }
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000342
343 if (!Ctors.empty()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +0000344 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Andersonc10c8d32009-07-08 19:05:04 +0000345 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000346 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000347 llvm::ConstantArray::get(AT, Ctors),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000348 GlobalName);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +0000349 }
Chris Lattner5ff2d5d2008-03-14 17:18:18 +0000350}
351
Nate Begeman7fab5782008-04-18 23:43:57 +0000352void CodeGenModule::EmitAnnotations() {
353 if (Annotations.empty())
354 return;
355
356 // Create a new global variable for the ConstantStruct in the Module.
357 llvm::Constant *Array =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000358 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
Nate Begeman7fab5782008-04-18 23:43:57 +0000359 Annotations.size()),
360 Annotations);
Mike Stump11289f42009-09-09 15:08:12 +0000361 llvm::GlobalValue *gv =
362 new llvm::GlobalVariable(TheModule, Array->getType(), false,
363 llvm::GlobalValue::AppendingLinkage, Array,
Owen Andersonc10c8d32009-07-08 19:05:04 +0000364 "llvm.global.annotations");
Nate Begeman7fab5782008-04-18 23:43:57 +0000365 gv->setSection("llvm.metadata");
366}
367
John McCalld4324142010-02-19 01:32:20 +0000368llvm::GlobalValue::LinkageTypes
369CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000370 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar38932572009-04-14 08:05:55 +0000371
Chris Lattner749b8ed2010-06-30 16:58:07 +0000372 if (Linkage == GVA_Internal)
John McCalld4324142010-02-19 01:32:20 +0000373 return llvm::Function::InternalLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000374
375 if (D->hasAttr<DLLExportAttr>())
John McCalld4324142010-02-19 01:32:20 +0000376 return llvm::Function::DLLExportLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000377
378 if (D->hasAttr<WeakAttr>())
John McCalld4324142010-02-19 01:32:20 +0000379 return llvm::Function::WeakAnyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000380
381 // In C99 mode, 'inline' functions are guaranteed to have a strong
382 // definition somewhere else, so we can use available_externally linkage.
383 if (Linkage == GVA_C99Inline)
John McCalld4324142010-02-19 01:32:20 +0000384 return llvm::Function::AvailableExternallyLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000385
386 // In C++, the compiler has to emit a definition in every translation unit
387 // that references the function. We should use linkonce_odr because
388 // a) if all references in this translation unit are optimized away, we
389 // don't need to codegen it. b) if the function persists, it needs to be
390 // merged with other definitions. c) C++ has the ODR, so we know the
391 // definition is dependable.
392 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
John McCalld4324142010-02-19 01:32:20 +0000393 return llvm::Function::LinkOnceODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000394
395 // An explicit instantiation of a template has weak linkage, since
396 // explicit instantiations can occur in multiple translation units
397 // and must all be equivalent. However, we are not allowed to
398 // throw away these explicit instantiations.
399 if (Linkage == GVA_ExplicitTemplateInstantiation)
Douglas Gregorb14d1232010-03-13 18:23:07 +0000400 return llvm::Function::WeakODRLinkage;
Chris Lattner749b8ed2010-06-30 16:58:07 +0000401
402 // Otherwise, we have strong external linkage.
403 assert(Linkage == GVA_StrongExternal);
404 return llvm::Function::ExternalLinkage;
John McCalld4324142010-02-19 01:32:20 +0000405}
Nuno Lopesb6f79532008-06-08 15:45:52 +0000406
John McCalld4324142010-02-19 01:32:20 +0000407
408/// SetFunctionDefinitionAttributes - Set attributes for a global.
409///
410/// FIXME: This is currently only done for aliases and functions, but not for
411/// variables (these details are set in EmitGlobalVarDefinition for variables).
412void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
413 llvm::GlobalValue *GV) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000414 SetCommonAttributes(D, GV);
Nuno Lopesb6f79532008-06-08 15:45:52 +0000415}
416
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000417void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump11289f42009-09-09 15:08:12 +0000418 const CGFunctionInfo &Info,
Daniel Dunbaraeddffc2009-04-14 07:08:30 +0000419 llvm::Function *F) {
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000420 unsigned CallingConv;
Devang Patel322300d2008-09-25 21:02:23 +0000421 AttributeListType AttributeList;
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000422 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Devang Patel322300d2008-09-25 21:02:23 +0000423 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
Daniel Dunbar0ef34792009-09-12 00:59:20 +0000424 AttributeList.size()));
425 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbar449a3392008-09-04 23:41:35 +0000426}
427
Daniel Dunbar38932572009-04-14 08:05:55 +0000428void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
429 llvm::Function *F) {
Daniel Dunbar0f3403c2009-03-02 04:58:03 +0000430 if (!Features.Exceptions && !Features.ObjCNonFragileABI)
Mike Stump11289f42009-09-09 15:08:12 +0000431 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbar03a38442008-10-28 00:17:57 +0000432
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000433 if (D->hasAttr<AlwaysInlineAttr>())
Daniel Dunbar03a38442008-10-28 00:17:57 +0000434 F->addFnAttr(llvm::Attribute::AlwaysInline);
Mike Stump11289f42009-09-09 15:08:12 +0000435
Daniel Dunbar8caf6412010-09-29 18:20:25 +0000436 if (D->hasAttr<NakedAttr>())
437 F->addFnAttr(llvm::Attribute::Naked);
438
Mike Stump3722f582009-08-26 22:31:08 +0000439 if (D->hasAttr<NoInlineAttr>())
Anders Carlssonf96954c2009-02-19 19:22:11 +0000440 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpc5e153c2009-10-05 21:58:44 +0000441
Rafael Espindola0ee986c1f2011-01-11 00:26:26 +0000442 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
443 F->setUnnamedAddr(true);
444
Anders Carlsson0d82fa62009-11-16 16:56:03 +0000445 if (Features.getStackProtectorMode() == LangOptions::SSPOn)
446 F->addFnAttr(llvm::Attribute::StackProtect);
447 else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
448 F->addFnAttr(llvm::Attribute::StackProtectReq);
449
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000450 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
451 if (alignment)
452 F->setAlignment(alignment);
453
Mike Stump3472ae52009-10-05 22:49:20 +0000454 // C++ ABI requires 2-byte alignment for member functions.
Mike Stump916c0062009-10-05 23:08:21 +0000455 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
456 F->setAlignment(2);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000457}
458
Mike Stump11289f42009-09-09 15:08:12 +0000459void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar38932572009-04-14 08:05:55 +0000460 llvm::GlobalValue *GV) {
Anders Carlsson072ef742011-01-29 19:41:00 +0000461 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
462 setGlobalVisibility(GV, ND);
John McCall457a04e2010-10-22 21:05:15 +0000463 else
464 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar38932572009-04-14 08:05:55 +0000465
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000466 if (D->hasAttr<UsedAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000467 AddUsedGlobal(GV);
468
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000469 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000470 GV->setSection(SA->getName());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000471
472 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar38932572009-04-14 08:05:55 +0000473}
474
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000475void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
476 llvm::Function *F,
477 const CGFunctionInfo &FI) {
478 SetLLVMFunctionAttributes(D, FI, F);
479 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar38932572009-04-14 08:05:55 +0000480
481 F->setLinkage(llvm::Function::InternalLinkage);
482
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000483 SetCommonAttributes(D, F);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000484}
485
Anders Carlsson6710c532010-02-06 02:44:09 +0000486void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedman895771a2009-05-26 01:22:57 +0000487 llvm::Function *F,
488 bool IsIncompleteFunction) {
Anders Carlsson6710c532010-02-06 02:44:09 +0000489 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
490
Eli Friedman895771a2009-05-26 01:22:57 +0000491 if (!IsIncompleteFunction)
Anders Carlsson6710c532010-02-06 02:44:09 +0000492 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
Mike Stump11289f42009-09-09 15:08:12 +0000493
Daniel Dunbar38932572009-04-14 08:05:55 +0000494 // Only a few attributes are set on declarations; these may later be
495 // overridden by a definition.
Mike Stump11289f42009-09-09 15:08:12 +0000496
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000497 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000498 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump11289f42009-09-09 15:08:12 +0000499 } else if (FD->hasAttr<WeakAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000500 FD->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +0000501 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump11289f42009-09-09 15:08:12 +0000502 // separate linkage types for this.
Daniel Dunbar38932572009-04-14 08:05:55 +0000503 F->setLinkage(llvm::Function::ExternalWeakLinkage);
504 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000505 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallc273f242010-10-30 11:50:40 +0000506
507 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
508 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
509 F->setVisibility(GetLLVMVisibility(LV.visibility()));
510 }
Daniel Dunbar38932572009-04-14 08:05:55 +0000511 }
512
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000513 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar38932572009-04-14 08:05:55 +0000514 F->setSection(SA->getName());
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000515}
516
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000517void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump11289f42009-09-09 15:08:12 +0000518 assert(!GV->isDeclaration() &&
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000519 "Only globals with definition can force usage.");
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000520 LLVMUsed.push_back(GV);
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000521}
522
523void CodeGenModule::EmitLLVMUsed() {
524 // Don't create llvm.used if there is no need.
Chris Lattnerf56501c2009-07-17 23:57:13 +0000525 if (LLVMUsed.empty())
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000526 return;
527
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000528 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000529
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000530 // Convert LLVMUsed to what ConstantArray needs.
531 std::vector<llvm::Constant*> UsedArray;
532 UsedArray.resize(LLVMUsed.size());
533 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +0000534 UsedArray[i] =
535 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Owen Anderson170229f2009-07-14 23:10:40 +0000536 i8PTy);
Chris Lattnerf41e87f2009-03-31 22:37:52 +0000537 }
Mike Stump11289f42009-09-09 15:08:12 +0000538
Fariborz Jahanian248c7192009-06-23 21:47:46 +0000539 if (UsedArray.empty())
540 return;
Owen Anderson9793f0e2009-07-29 22:16:19 +0000541 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
Mike Stump11289f42009-09-09 15:08:12 +0000542
543 llvm::GlobalVariable *GV =
544 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000545 llvm::GlobalValue::AppendingLinkage,
Owen Anderson47034e12009-07-28 18:33:04 +0000546 llvm::ConstantArray::get(ATy, UsedArray),
Owen Andersonc10c8d32009-07-08 19:05:04 +0000547 "llvm.used");
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000548
549 GV->setSection("llvm.metadata");
550}
551
552void CodeGenModule::EmitDeferred() {
Chris Lattner45470942009-03-21 09:44:56 +0000553 // Emit code for any potentially referenced deferred decls. Since a
554 // previously unused static decl may become used during the generation of code
555 // for a static function, iterate until no changes are made.
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000556
Anders Carlsson11e51402010-04-17 20:15:18 +0000557 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
558 if (!DeferredVTables.empty()) {
559 const CXXRecordDecl *RD = DeferredVTables.back();
560 DeferredVTables.pop_back();
561 getVTables().GenerateClassData(getVTableLinkage(RD), RD);
Rafael Espindolae7113ca2010-03-10 02:19:29 +0000562 continue;
563 }
564
Anders Carlssondae1abc2009-05-05 04:44:02 +0000565 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner45470942009-03-21 09:44:56 +0000566 DeferredDeclsToEmit.pop_back();
567
John McCallc2af9392010-05-27 01:45:30 +0000568 // Check to see if we've already emitted this. This is necessary
569 // for a couple of reasons: first, decls can end up in the
570 // deferred-decls queue multiple times, and second, decls can end
571 // up with definitions in unusual ways (e.g. by an extern inline
572 // function acquiring a strong function redefinition). Just
573 // ignore these cases.
574 //
575 // TODO: That said, looking this up multiple times is very wasteful.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000576 llvm::StringRef Name = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +0000577 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner45470942009-03-21 09:44:56 +0000578 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump11289f42009-09-09 15:08:12 +0000579
Chris Lattner45470942009-03-21 09:44:56 +0000580 if (!CGRef->isDeclaration())
581 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000582
John McCallc2af9392010-05-27 01:45:30 +0000583 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
584 // purposes an alias counts as a definition.
585 if (isa<llvm::GlobalAlias>(CGRef))
586 continue;
587
Chris Lattner45470942009-03-21 09:44:56 +0000588 // Otherwise, emit the definition and move on to the next one.
589 EmitGlobalDefinition(D);
590 }
Chris Lattnerbed31442007-05-28 01:07:47 +0000591}
Chris Lattner09153c02007-06-22 18:48:09 +0000592
Mike Stump11289f42009-09-09 15:08:12 +0000593/// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
Nate Begemanfaae0812008-04-19 04:17:09 +0000594/// annotation information for a given GlobalValue. The annotation struct is
Mike Stump11289f42009-09-09 15:08:12 +0000595/// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the
596/// GlobalValue being annotated. The second field is the constant string
597/// created from the AnnotateAttr's annotation. The third field is a constant
Nate Begemanfaae0812008-04-19 04:17:09 +0000598/// string containing the name of the translation unit. The fourth field is
599/// the line number in the file of the annotated value declaration.
600///
601/// FIXME: this does not unique the annotation string constants, as llvm-gcc
602/// appears to.
603///
Mike Stump11289f42009-09-09 15:08:12 +0000604llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begemanfaae0812008-04-19 04:17:09 +0000605 const AnnotateAttr *AA,
606 unsigned LineNo) {
607 llvm::Module *M = &getModule();
608
609 // get [N x i8] constants for the annotation string, and the filename string
610 // which are the 2nd and 3rd elements of the global annotation structure.
Benjamin Kramerabd5b902009-10-13 10:07:13 +0000611 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
Mike Stump11289f42009-09-09 15:08:12 +0000612 llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
Owen Anderson41a75022009-08-13 21:57:51 +0000613 AA->getAnnotation(), true);
614 llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
615 M->getModuleIdentifier(),
Nate Begemanfaae0812008-04-19 04:17:09 +0000616 true);
617
618 // Get the two global values corresponding to the ConstantArrays we just
619 // created to hold the bytes of the strings.
Mike Stump11289f42009-09-09 15:08:12 +0000620 llvm::GlobalValue *annoGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000621 new llvm::GlobalVariable(*M, anno->getType(), false,
622 llvm::GlobalValue::PrivateLinkage, anno,
623 GV->getName());
Nate Begemanfaae0812008-04-19 04:17:09 +0000624 // translation unit name string, emitted into the llvm.metadata section.
625 llvm::GlobalValue *unitGV =
Chris Lattner3afa3e12009-07-16 05:03:48 +0000626 new llvm::GlobalVariable(*M, unit->getType(), false,
Mike Stump11289f42009-09-09 15:08:12 +0000627 llvm::GlobalValue::PrivateLinkage, unit,
Chris Lattner3afa3e12009-07-16 05:03:48 +0000628 ".str");
Rafael Espindola2e217d62011-01-17 22:22:52 +0000629 unitGV->setUnnamedAddr(true);
Nate Begemanfaae0812008-04-19 04:17:09 +0000630
Daniel Dunbar346892a2009-04-14 22:41:13 +0000631 // Create the ConstantStruct for the global annotation.
Nate Begemanfaae0812008-04-19 04:17:09 +0000632 llvm::Constant *Fields[4] = {
Owen Andersonade90fd2009-07-29 18:54:39 +0000633 llvm::ConstantExpr::getBitCast(GV, SBP),
634 llvm::ConstantExpr::getBitCast(annoGV, SBP),
635 llvm::ConstantExpr::getBitCast(unitGV, SBP),
Owen Anderson41a75022009-08-13 21:57:51 +0000636 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
Nate Begemanfaae0812008-04-19 04:17:09 +0000637 };
Owen Anderson758428f2009-08-05 23:18:46 +0000638 return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
Nate Begemanfaae0812008-04-19 04:17:09 +0000639}
640
Argyrios Kyrtzidisc0279a92010-07-27 22:37:14 +0000641bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidisc81af032010-07-29 18:15:58 +0000642 // Never defer when EmitAllDecls is specified.
643 if (Features.EmitAllDecls)
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000644 return false;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000645
Argyrios Kyrtzidisc9049332010-07-29 20:08:05 +0000646 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000647}
648
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000649llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
650 const AliasAttr *AA = VD->getAttr<AliasAttr>();
651 assert(AA && "No alias?");
652
653 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
654
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000655 // See if there is already something with the target's name in the module.
John McCall7ec50432010-03-19 23:29:14 +0000656 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000657
658 llvm::Constant *Aliasee;
659 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +0000660 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000661 else
John McCall7ec50432010-03-19 23:29:14 +0000662 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000663 llvm::PointerType::getUnqual(DeclTy), 0);
664 if (!Entry) {
665 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
666 F->setLinkage(llvm::Function::ExternalWeakLinkage);
667 WeakRefReferences.insert(F);
668 }
669
670 return Aliasee;
671}
672
Chris Lattnere0be0df2009-05-12 21:21:08 +0000673void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000674 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000675
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000676 // Weak references don't produce any output by themselves.
677 if (Global->hasAttr<WeakRefAttr>())
678 return;
679
Chris Lattner54041692009-03-22 21:47:11 +0000680 // If this is an alias definition (which otherwise looks like a declaration)
681 // emit it now.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000682 if (Global->hasAttr<AliasAttr>())
John McCall7ec50432010-03-19 23:29:14 +0000683 return EmitAliasDefinition(GD);
Daniel Dunbar0beedc12008-09-08 23:44:31 +0000684
Chris Lattner45470942009-03-21 09:44:56 +0000685 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar4e004ed2009-03-19 08:27:24 +0000686 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000687 if (FD->getIdentifier()) {
688 llvm::StringRef Name = FD->getName();
689 if (Name == "_Block_object_assign") {
690 BlockObjectAssignDecl = FD;
691 } else if (Name == "_Block_object_dispose") {
692 BlockObjectDisposeDecl = FD;
693 }
694 }
695
Daniel Dunbar6b8720e2009-02-13 21:18:01 +0000696 // Forward declarations are emitted lazily on first use.
697 if (!FD->isThisDeclarationADefinition())
698 return;
Daniel Dunbar08b26a02009-02-13 20:29:50 +0000699 } else {
700 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000701 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
702
Daniel Dunbar3348e2d2010-07-16 00:00:19 +0000703 if (VD->getIdentifier()) {
704 llvm::StringRef Name = VD->getName();
705 if (Name == "_NSConcreteGlobalBlock") {
706 NSConcreteGlobalBlockDecl = VD;
707 } else if (Name == "_NSConcreteStackBlock") {
708 NSConcreteStackBlockDecl = VD;
709 }
710 }
711
712
Douglas Gregor61f6db52010-02-06 05:15:45 +0000713 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorbeecd582009-04-21 17:11:58 +0000714 return;
Nate Begeman8e8d4982008-04-20 06:29:50 +0000715 }
716
Chris Lattner45470942009-03-21 09:44:56 +0000717 // Defer code generation when possible if this is a static definition, inline
718 // function etc. These we only want to emit if they are used.
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000719 if (!MayDeferGeneration(Global)) {
720 // Emit the definition if it can't be deferred.
721 EmitGlobalDefinition(GD);
Daniel Dunbar9c426522008-07-29 23:18:29 +0000722 return;
723 }
John McCall70013b62010-07-15 23:40:35 +0000724
725 // If we're deferring emission of a C++ variable with an
726 // initializer, remember the order in which it appeared in the file.
727 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) &&
728 cast<VarDecl>(Global)->hasInit()) {
729 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
730 CXXGlobalInits.push_back(0);
731 }
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000732
733 // If the value has already been used, add it directly to the
734 // DeferredDeclsToEmit list.
Anders Carlssonea836bc2010-06-22 16:16:50 +0000735 llvm::StringRef MangledName = getMangledName(GD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000736 if (GetGlobalValue(MangledName))
737 DeferredDeclsToEmit.push_back(GD);
738 else {
739 // Otherwise, remember that we saw a deferred decl with this name. The
740 // first use of the mangled name will cause it to move into
741 // DeferredDeclsToEmit.
742 DeferredDecls[MangledName] = GD;
743 }
Nate Begeman8e8d4982008-04-20 06:29:50 +0000744}
745
Chris Lattnere0be0df2009-05-12 21:21:08 +0000746void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson38988d72009-09-10 23:38:47 +0000747 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump11289f42009-09-09 15:08:12 +0000748
Dan Gohman145f3f12010-04-19 16:39:44 +0000749 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson29295bf2009-10-27 14:32:27 +0000750 Context.getSourceManager(),
751 "Generating code for declaration");
752
Douglas Gregora700f682010-07-13 06:02:28 +0000753 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
754 // At -O0, don't generate IR for functions with available_externally
755 // linkage.
Douglas Gregor89976902010-07-15 22:58:18 +0000756 if (CodeGenOpts.OptimizationLevel == 0 &&
757 !Function->hasAttr<AlwaysInlineAttr>() &&
Douglas Gregora700f682010-07-13 06:02:28 +0000758 getFunctionLinkage(Function)
759 == llvm::Function::AvailableExternallyLinkage)
760 return;
Anders Carlssonaf82f632010-03-23 04:31:31 +0000761
Douglas Gregora700f682010-07-13 06:02:28 +0000762 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
763 if (Method->isVirtual())
764 getVTables().EmitThunks(GD);
765
766 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
767 return EmitCXXConstructor(CD, GD.getCtorType());
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000768
Douglas Gregora700f682010-07-13 06:02:28 +0000769 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method))
770 return EmitCXXDestructor(DD, GD.getDtorType());
771 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000772
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000773 return EmitGlobalFunctionDefinition(GD);
Douglas Gregora700f682010-07-13 06:02:28 +0000774 }
Chris Lattnerd8d760c2010-04-13 17:57:11 +0000775
776 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
777 return EmitGlobalVarDefinition(VD);
Chris Lattner7a4a29f2010-04-13 17:39:09 +0000778
779 assert(0 && "Invalid argument to EmitGlobalDefinition()");
Daniel Dunbar9c426522008-07-29 23:18:29 +0000780}
781
Chris Lattnerd4808922009-03-22 21:03:39 +0000782/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
783/// module, create and return an llvm Function with the specified type. If there
784/// is something in the module with the specified name, return it potentially
785/// bitcasted to the right type.
786///
787/// If D is non-null, it specifies a decl that correspond to this. This is used
788/// to set the attributes on the function when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000789llvm::Constant *
790CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
791 const llvm::Type *Ty,
792 GlobalDecl D) {
Chris Lattnera85d68e2009-03-21 09:25:43 +0000793 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000794 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000795 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000796 if (WeakRefReferences.count(Entry)) {
797 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
798 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000799 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000800
801 WeakRefReferences.erase(Entry);
802 }
803
Chris Lattnera85d68e2009-03-21 09:25:43 +0000804 if (Entry->getType()->getElementType() == Ty)
805 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000806
Chris Lattnera85d68e2009-03-21 09:25:43 +0000807 // Make sure the result is of the correct type.
Owen Anderson9793f0e2009-07-29 22:16:19 +0000808 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Owen Andersonade90fd2009-07-29 18:54:39 +0000809 return llvm::ConstantExpr::getBitCast(Entry, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000810 }
Mike Stump11289f42009-09-09 15:08:12 +0000811
Eli Friedmancc522d92009-11-09 05:07:37 +0000812 // This function doesn't have a complete type (for example, the return
813 // type is an incomplete struct). Use a fake type instead, and make
814 // sure not to try to set attributes.
815 bool IsIncompleteFunction = false;
John McCalld06fb862010-04-28 00:00:30 +0000816
817 const llvm::FunctionType *FTy;
818 if (isa<llvm::FunctionType>(Ty)) {
819 FTy = cast<llvm::FunctionType>(Ty);
820 } else {
Benjamin Kramer1e188892011-01-22 12:15:57 +0000821 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false);
Eli Friedmancc522d92009-11-09 05:07:37 +0000822 IsIncompleteFunction = true;
823 }
Chris Lattner5c740f12010-06-30 19:14:05 +0000824
John McCalld06fb862010-04-28 00:00:30 +0000825 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedmancc522d92009-11-09 05:07:37 +0000826 llvm::Function::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000827 MangledName, &getModule());
828 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedmancc522d92009-11-09 05:07:37 +0000829 if (D.getDecl())
Anders Carlsson6710c532010-02-06 02:44:09 +0000830 SetFunctionAttributes(D, F, IsIncompleteFunction);
Eli Friedmancc522d92009-11-09 05:07:37 +0000831
Chris Lattner45470942009-03-21 09:44:56 +0000832 // This is the first use or definition of a mangled name. If there is a
833 // deferred decl with this name, remember that we need to emit it at the end
834 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000835 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000836 if (DDI != DeferredDecls.end()) {
837 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
838 // list, and remove it from DeferredDecls (since we don't need it anymore).
839 DeferredDeclsToEmit.push_back(DDI->second);
840 DeferredDecls.erase(DDI);
John McCall357d0f32010-12-15 04:00:32 +0000841
842 // Otherwise, there are cases we have to worry about where we're
843 // using a declaration for which we must emit a definition but where
844 // we might not find a top-level definition:
845 // - member functions defined inline in their classes
846 // - friend functions defined inline in some class
847 // - special member functions with implicit definitions
848 // If we ever change our AST traversal to walk into class methods,
849 // this will be unnecessary.
850 } else if (getLangOptions().CPlusPlus && D.getDecl()) {
851 // Look for a declaration that's lexically in a record.
852 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
853 do {
854 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
855 if (FD->isImplicit()) {
856 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
857 DeferredDeclsToEmit.push_back(D);
858 break;
859 } else if (FD->isThisDeclarationADefinition()) {
860 DeferredDeclsToEmit.push_back(D);
861 break;
862 }
Rafael Espindola70e040d2010-03-02 21:28:26 +0000863 }
John McCall357d0f32010-12-15 04:00:32 +0000864 FD = FD->getPreviousDeclaration();
865 } while (FD);
Chris Lattner45470942009-03-21 09:44:56 +0000866 }
Mike Stump11289f42009-09-09 15:08:12 +0000867
John McCalld06fb862010-04-28 00:00:30 +0000868 // Make sure the result is of the requested type.
869 if (!IsIncompleteFunction) {
870 assert(F->getType()->getElementType() == Ty);
871 return F;
872 }
873
874 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
875 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattnera85d68e2009-03-21 09:25:43 +0000876}
877
Chris Lattnerd4808922009-03-22 21:03:39 +0000878/// GetAddrOfFunction - Return the address of the given function. If Ty is
879/// non-null, then this function will use the specified type if it has to
880/// create it (this occurs when we see a definition of the function).
Chris Lattnere0be0df2009-05-12 21:21:08 +0000881llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattnerd4808922009-03-22 21:03:39 +0000882 const llvm::Type *Ty) {
883 // If there was no specific requested type, just convert it now.
884 if (!Ty)
Anders Carlsson38988d72009-09-10 23:38:47 +0000885 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattner5c740f12010-06-30 19:14:05 +0000886
Anders Carlssonea836bc2010-06-22 16:16:50 +0000887 llvm::StringRef MangledName = getMangledName(GD);
John McCall7ec50432010-03-19 23:29:14 +0000888 return GetOrCreateLLVMFunction(MangledName, Ty, GD);
Chris Lattnerd4808922009-03-22 21:03:39 +0000889}
Eli Friedmanc18d9d52008-05-30 19:50:47 +0000890
Chris Lattnerd4808922009-03-22 21:03:39 +0000891/// CreateRuntimeFunction - Create a new runtime function with the specified
892/// type and name.
893llvm::Constant *
894CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
John McCall7ec50432010-03-19 23:29:14 +0000895 llvm::StringRef Name) {
Chris Lattnere0be0df2009-05-12 21:21:08 +0000896 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
Chris Lattnerd4808922009-03-22 21:03:39 +0000897}
Daniel Dunbar9c426522008-07-29 23:18:29 +0000898
Eli Friedmanb095e152009-12-11 21:23:03 +0000899static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
John McCall340aafa2010-02-08 21:46:50 +0000900 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
Eli Friedmanb095e152009-12-11 21:23:03 +0000901 return false;
902 if (Context.getLangOptions().CPlusPlus &&
903 Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
904 // FIXME: We should do something fancier here!
905 return false;
906 }
907 return true;
908}
909
Chris Lattnerd4808922009-03-22 21:03:39 +0000910/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
911/// create and return an llvm GlobalVariable with the specified type. If there
912/// is something in the module with the specified name, return it potentially
913/// bitcasted to the right type.
914///
915/// If D is non-null, it specifies a decl that correspond to this. This is used
916/// to set the attributes on the global when it is first created.
John McCall7ec50432010-03-19 23:29:14 +0000917llvm::Constant *
918CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
919 const llvm::PointerType *Ty,
Rafael Espindolad661a852011-01-18 21:07:57 +0000920 const VarDecl *D,
921 bool UnnamedAddr) {
Daniel Dunbar829e9882008-08-05 23:31:02 +0000922 // Lookup the entry, lazily creating it if necessary.
John McCall7ec50432010-03-19 23:29:14 +0000923 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner3bfce182009-03-21 08:03:33 +0000924 if (Entry) {
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000925 if (WeakRefReferences.count(Entry)) {
926 if (D && !D->hasAttr<WeakAttr>())
Anders Carlssonaf82f632010-03-23 04:31:31 +0000927 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola2e42fec2010-03-04 18:17:24 +0000928
929 WeakRefReferences.erase(Entry);
930 }
931
Rafael Espindolad661a852011-01-18 21:07:57 +0000932 if (UnnamedAddr)
933 Entry->setUnnamedAddr(true);
934
Chris Lattnerd4808922009-03-22 21:03:39 +0000935 if (Entry->getType() == Ty)
Chris Lattner149927c2009-03-21 09:16:30 +0000936 return Entry;
Mike Stump11289f42009-09-09 15:08:12 +0000937
Chris Lattner3bfce182009-03-21 08:03:33 +0000938 // Make sure the result is of the correct type.
Owen Andersonade90fd2009-07-29 18:54:39 +0000939 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbardec798b2009-01-13 02:25:00 +0000940 }
Mike Stump11289f42009-09-09 15:08:12 +0000941
Chris Lattner45470942009-03-21 09:44:56 +0000942 // This is the first use or definition of a mangled name. If there is a
943 // deferred decl with this name, remember that we need to emit it at the end
944 // of the file.
John McCall7ec50432010-03-19 23:29:14 +0000945 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner45470942009-03-21 09:44:56 +0000946 if (DDI != DeferredDecls.end()) {
947 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
948 // list, and remove it from DeferredDecls (since we don't need it anymore).
949 DeferredDeclsToEmit.push_back(DDI->second);
950 DeferredDecls.erase(DDI);
951 }
Mike Stump11289f42009-09-09 15:08:12 +0000952
953 llvm::GlobalVariable *GV =
954 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner3bfce182009-03-21 08:03:33 +0000955 llvm::GlobalValue::ExternalLinkage,
John McCall7ec50432010-03-19 23:29:14 +0000956 0, MangledName, 0,
Eli Friedman4f856742009-04-19 21:05:03 +0000957 false, Ty->getAddressSpace());
Chris Lattner3bfce182009-03-21 08:03:33 +0000958
959 // Handle things which are present even on external declarations.
Chris Lattnerd4808922009-03-22 21:03:39 +0000960 if (D) {
Mike Stump18bb9282009-05-16 07:57:57 +0000961 // FIXME: This code is overly simple and should be merged with other global
962 // handling.
Eli Friedmanb095e152009-12-11 21:23:03 +0000963 GV->setConstant(DeclIsConstantGlobal(Context, D));
Chris Lattner3bfce182009-03-21 08:03:33 +0000964
John McCall37bb6c92010-10-29 22:22:43 +0000965 // Set linkage and visibility in case we never see a definition.
John McCallc273f242010-10-30 11:50:40 +0000966 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
967 if (LV.linkage() != ExternalLinkage) {
John McCall37bb6c92010-10-29 22:22:43 +0000968 GV->setLinkage(llvm::GlobalValue::InternalLinkage);
969 } else {
970 if (D->hasAttr<DLLImportAttr>())
971 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
972 else if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakImportAttr>())
973 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner3bfce182009-03-21 08:03:33 +0000974
John McCallc273f242010-10-30 11:50:40 +0000975 // Set visibility on a declaration only if it's explicit.
976 if (LV.visibilityExplicit())
977 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall37bb6c92010-10-29 22:22:43 +0000978 }
Eli Friedman4f856742009-04-19 21:05:03 +0000979
980 GV->setThreadLocal(D->isThreadSpecified());
Chris Lattnerd4808922009-03-22 21:03:39 +0000981 }
Mike Stump11289f42009-09-09 15:08:12 +0000982
John McCall7ec50432010-03-19 23:29:14 +0000983 return GV;
Daniel Dunbar9c426522008-07-29 23:18:29 +0000984}
985
Chris Lattnerd4808922009-03-22 21:03:39 +0000986
Anders Carlssonda80af32011-01-29 18:20:20 +0000987llvm::GlobalVariable *
988CodeGenModule::CreateOrReplaceCXXRuntimeVariable(llvm::StringRef Name,
989 const llvm::Type *Ty,
990 llvm::GlobalValue::LinkageTypes Linkage) {
991 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
992 llvm::GlobalVariable *OldGV = 0;
993
994
995 if (GV) {
996 // Check if the variable has the right type.
997 if (GV->getType()->getElementType() == Ty)
998 return GV;
999
1000 // Because C++ name mangling, the only way we can end up with an already
1001 // existing global with the same name is if it has been declared extern "C".
Anders Carlsson93be9a92011-01-29 18:25:07 +00001002 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlssonda80af32011-01-29 18:20:20 +00001003 OldGV = GV;
1004 }
1005
1006 // Create a new variable.
1007 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1008 Linkage, 0, Name);
1009
1010 if (OldGV) {
1011 // Replace occurrences of the old variable if needed.
1012 GV->takeName(OldGV);
1013
1014 if (!OldGV->use_empty()) {
1015 llvm::Constant *NewPtrForOldDecl =
1016 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1017 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1018 }
1019
1020 OldGV->eraseFromParent();
1021 }
1022
1023 return GV;
1024}
1025
Chris Lattnerd4808922009-03-22 21:03:39 +00001026/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1027/// given global variable. If Ty is non-null and if the global doesn't exist,
1028/// then it will be greated with the specified type instead of whatever the
1029/// normal requested type would be.
1030llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1031 const llvm::Type *Ty) {
1032 assert(D->hasGlobalStorage() && "Not a global variable");
1033 QualType ASTTy = D->getType();
1034 if (Ty == 0)
1035 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump11289f42009-09-09 15:08:12 +00001036
1037 const llvm::PointerType *PTy =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001038 llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
John McCall7ec50432010-03-19 23:29:14 +00001039
Anders Carlssonea836bc2010-06-22 16:16:50 +00001040 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001041 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattnerd4808922009-03-22 21:03:39 +00001042}
1043
1044/// CreateRuntimeVariable - Create a new runtime global variable with the
1045/// specified type and name.
1046llvm::Constant *
1047CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
John McCall7ec50432010-03-19 23:29:14 +00001048 llvm::StringRef Name) {
Rafael Espindolad661a852011-01-18 21:07:57 +00001049 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
1050 true);
Chris Lattnerd4808922009-03-22 21:03:39 +00001051}
1052
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001053void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1054 assert(!D->getInit() && "Cannot emit definite definitions here!");
1055
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001056 if (MayDeferGeneration(D)) {
1057 // If we have not seen a reference to this variable yet, place it
1058 // into the deferred declarations table to be emitted if needed
1059 // later.
Anders Carlssonea836bc2010-06-22 16:16:50 +00001060 llvm::StringRef MangledName = getMangledName(D);
John McCall7ec50432010-03-19 23:29:14 +00001061 if (!GetGlobalValue(MangledName)) {
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001062 DeferredDecls[MangledName] = D;
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001063 return;
Douglas Gregorfa9ab532009-04-21 19:28:58 +00001064 }
1065 }
1066
1067 // The tentative definition is the only definition.
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001068 EmitGlobalVarDefinition(D);
1069}
1070
Douglas Gregor88d292c2010-05-13 16:44:06 +00001071void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1072 if (DefinitionRequired)
1073 getVTables().GenerateClassData(getVTableLinkage(Class), Class);
1074}
1075
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001076llvm::GlobalVariable::LinkageTypes
Anders Carlsson11e51402010-04-17 20:15:18 +00001077CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Douglas Gregor2a34df32010-01-06 22:00:56 +00001078 if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1079 return llvm::GlobalVariable::InternalLinkage;
1080
1081 if (const CXXMethodDecl *KeyFunction
1082 = RD->getASTContext().getKeyFunction(RD)) {
1083 // If this class has a key function, use that to determine the linkage of
1084 // the vtable.
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001085 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001086 if (KeyFunction->hasBody(Def))
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001087 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregor2a34df32010-01-06 22:00:56 +00001088
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001089 switch (KeyFunction->getTemplateSpecializationKind()) {
1090 case TSK_Undeclared:
1091 case TSK_ExplicitSpecialization:
1092 if (KeyFunction->isInlined())
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001093 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001094
1095 return llvm::GlobalVariable::ExternalLinkage;
1096
1097 case TSK_ImplicitInstantiation:
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001098 return llvm::GlobalVariable::LinkOnceODRLinkage;
1099
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001100 case TSK_ExplicitInstantiationDefinition:
1101 return llvm::GlobalVariable::WeakODRLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001102
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001103 case TSK_ExplicitInstantiationDeclaration:
1104 // FIXME: Use available_externally linkage. However, this currently
1105 // breaks LLVM's build due to undefined symbols.
1106 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001107 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001108 }
Douglas Gregor2a34df32010-01-06 22:00:56 +00001109 }
1110
1111 switch (RD->getTemplateSpecializationKind()) {
1112 case TSK_Undeclared:
1113 case TSK_ExplicitSpecialization:
1114 case TSK_ImplicitInstantiation:
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001115 return llvm::GlobalVariable::LinkOnceODRLinkage;
1116
Douglas Gregor2a34df32010-01-06 22:00:56 +00001117 case TSK_ExplicitInstantiationDefinition:
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001118 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor2a34df32010-01-06 22:00:56 +00001119
1120 case TSK_ExplicitInstantiationDeclaration:
1121 // FIXME: Use available_externally linkage. However, this currently
1122 // breaks LLVM's build due to undefined symbols.
1123 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001124 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001125 }
1126
1127 // Silence GCC warning.
Anders Carlsson571e2ad2011-01-24 00:46:19 +00001128 return llvm::GlobalVariable::LinkOnceODRLinkage;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00001129}
1130
Ken Dyck98ca7942010-01-26 13:48:07 +00001131CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
Ken Dyck9a648692011-01-18 02:01:14 +00001132 return Context.toCharUnitsFromBits(
1133 TheTargetData.getTypeStoreSizeInBits(Ty));
Ken Dyck98ca7942010-01-26 13:48:07 +00001134}
1135
Daniel Dunbar9c426522008-07-29 23:18:29 +00001136void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001137 llvm::Constant *Init = 0;
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001138 QualType ASTTy = D->getType();
Eli Friedman5866fe32010-01-08 00:50:11 +00001139 bool NonConstInit = false;
Mike Stump11289f42009-09-09 15:08:12 +00001140
Sebastian Redl5ca79842010-02-01 20:16:42 +00001141 const Expr *InitExpr = D->getAnyInitializer();
Anders Carlssonca4a5452010-01-26 17:43:42 +00001142
1143 if (!InitExpr) {
Eli Friedman6859a1b2008-05-30 20:39:54 +00001144 // This is a tentative definition; tentative definitions are
Daniel Dunbar7dd749e2009-04-15 22:08:45 +00001145 // implicitly initialized with { 0 }.
1146 //
1147 // Note that tentative definitions are only emitted at the end of
1148 // a translation unit, so they should never have incomplete
1149 // type. In addition, EmitTentativeDefinition makes sure that we
1150 // never attempt to emit a tentative definition if a real one
1151 // exists. A use may still exists, however, so we still may need
1152 // to do a RAUW.
1153 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonf18318c2009-08-02 21:18:22 +00001154 Init = EmitNullConstant(D->getType());
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001155 } else {
Douglas Gregord450f062010-05-05 20:15:55 +00001156 Init = EmitConstantExpr(InitExpr, D->getType());
Eli Friedman719ed1a2009-02-20 01:18:21 +00001157 if (!Init) {
Anders Carlssonca4a5452010-01-26 17:43:42 +00001158 QualType T = InitExpr->getType();
Douglas Gregord450f062010-05-05 20:15:55 +00001159 if (D->getType()->isReferenceType())
1160 T = D->getType();
1161
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001162 if (getLangOptions().CPlusPlus) {
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001163 Init = EmitNullConstant(T);
Eli Friedman5866fe32010-01-08 00:50:11 +00001164 NonConstInit = true;
Anders Carlssonb8be93f2009-08-08 23:24:23 +00001165 } else {
1166 ErrorUnsupported(D, "static initializer");
1167 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1168 }
John McCall70013b62010-07-15 23:40:35 +00001169 } else {
1170 // We don't need an initializer, so remove the entry for the delayed
1171 // initializer position (just in case this entry was delayed).
1172 if (getLangOptions().CPlusPlus)
1173 DelayedCXXInitPosition.erase(D);
Eli Friedman719ed1a2009-02-20 01:18:21 +00001174 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001175 }
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001176
Chris Lattner64c55932009-03-21 08:13:05 +00001177 const llvm::Type* InitType = Init->getType();
Chris Lattner149927c2009-03-21 09:16:30 +00001178 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump11289f42009-09-09 15:08:12 +00001179
Chris Lattner149927c2009-03-21 09:16:30 +00001180 // Strip off a bitcast if we got one back.
1181 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattneraa64ca22009-07-16 16:48:25 +00001182 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1183 // all zero index gep.
1184 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner149927c2009-03-21 09:16:30 +00001185 Entry = CE->getOperand(0);
1186 }
Mike Stump11289f42009-09-09 15:08:12 +00001187
Chris Lattner149927c2009-03-21 09:16:30 +00001188 // Entry is now either a Function or GlobalVariable.
1189 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001190
Chris Lattner149927c2009-03-21 09:16:30 +00001191 // We have a definition after a declaration with the wrong type.
1192 // We must make a new GlobalVariable* and update everything that used OldGV
1193 // (a declaration or tentative definition) with the new GlobalVariable*
1194 // (which will be a definition).
1195 //
1196 // This happens if there is a prototype for a global (e.g.
1197 // "extern int x[];") and then a definition of a different type (e.g.
1198 // "int x[10];"). This also happens when an initializer has a different type
1199 // from the type of the global (this happens with unions).
Chris Lattner149927c2009-03-21 09:16:30 +00001200 if (GV == 0 ||
1201 GV->getType()->getElementType() != InitType ||
1202 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
Mike Stump11289f42009-09-09 15:08:12 +00001203
John McCall7ec50432010-03-19 23:29:14 +00001204 // Move the old entry aside so that we'll create a new one.
1205 Entry->setName(llvm::StringRef());
Daniel Dunbarb2f4cdb2009-02-19 05:36:41 +00001206
Chris Lattner149927c2009-03-21 09:16:30 +00001207 // Make a new global with the correct type, this is now guaranteed to work.
1208 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattnera85d68e2009-03-21 09:25:43 +00001209
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001210 // Replace all uses of the old global with the new global
Mike Stump11289f42009-09-09 15:08:12 +00001211 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001212 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner149927c2009-03-21 09:16:30 +00001213 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedmanc18d9d52008-05-30 19:50:47 +00001214
1215 // Erase the old global, since it is no longer used.
Chris Lattner149927c2009-03-21 09:16:30 +00001216 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner9d3b0e02007-07-14 00:23:28 +00001217 }
Devang Patel19c2b9a2007-10-26 16:31:40 +00001218
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001219 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
Nate Begemanfaae0812008-04-19 04:17:09 +00001220 SourceManager &SM = Context.getSourceManager();
1221 AddAnnotation(EmitAnnotateAttr(GV, AA,
Chris Lattner8a425862009-01-16 07:36:28 +00001222 SM.getInstantiationLineNumber(D->getLocation())));
Nate Begemanfaae0812008-04-19 04:17:09 +00001223 }
1224
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001225 GV->setInitializer(Init);
Chris Lattnerf49573d2009-08-05 05:20:29 +00001226
1227 // If it is safe to mark the global 'constant', do so now.
1228 GV->setConstant(false);
Eli Friedman5866fe32010-01-08 00:50:11 +00001229 if (!NonConstInit && DeclIsConstantGlobal(Context, D))
Chris Lattnerf49573d2009-08-05 05:20:29 +00001230 GV->setConstant(true);
Mike Stump11289f42009-09-09 15:08:12 +00001231
Ken Dyck160146e2010-01-27 17:10:57 +00001232 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001233
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001234 // Set the llvm linkage type as appropriate.
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001235 llvm::GlobalValue::LinkageTypes Linkage =
1236 GetLLVMLinkageVarDefinition(D, GV);
1237 GV->setLinkage(Linkage);
1238 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnerf49573d2009-08-05 05:20:29 +00001239 // common vars aren't constant even if declared const.
1240 GV->setConstant(false);
Daniel Dunbard272cca2009-04-10 20:26:50 +00001241
Daniel Dunbar38932572009-04-14 08:05:55 +00001242 SetCommonAttributes(D, GV);
Daniel Dunbarf5f359f2009-04-14 06:00:08 +00001243
John McCallcdf7ef52010-11-06 09:44:32 +00001244 // Emit the initializer function if necessary.
1245 if (NonConstInit)
1246 EmitCXXGlobalVarDeclInitFunc(D, GV);
1247
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001248 // Emit global variable debug information.
Chris Lattner64c55932009-03-21 08:13:05 +00001249 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarb9fd9022008-10-17 16:15:48 +00001250 DI->setLocation(D->getLocation());
Sanjiv Gupta158143a2008-06-05 08:59:10 +00001251 DI->EmitGlobalVariable(GV, D);
1252 }
Chris Lattnerd14bfa92007-07-13 05:13:43 +00001253}
Chris Lattner09153c02007-06-22 18:48:09 +00001254
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001255llvm::GlobalValue::LinkageTypes
1256CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1257 llvm::GlobalVariable *GV) {
1258 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1259 if (Linkage == GVA_Internal)
1260 return llvm::Function::InternalLinkage;
1261 else if (D->hasAttr<DLLImportAttr>())
1262 return llvm::Function::DLLImportLinkage;
1263 else if (D->hasAttr<DLLExportAttr>())
1264 return llvm::Function::DLLExportLinkage;
1265 else if (D->hasAttr<WeakAttr>()) {
1266 if (GV->isConstant())
1267 return llvm::GlobalVariable::WeakODRLinkage;
1268 else
1269 return llvm::GlobalVariable::WeakAnyLinkage;
1270 } else if (Linkage == GVA_TemplateInstantiation ||
1271 Linkage == GVA_ExplicitTemplateInstantiation)
1272 // FIXME: It seems like we can provide more specific linkage here
1273 // (LinkOnceODR, WeakODR).
1274 return llvm::GlobalVariable::WeakAnyLinkage;
Eric Christopher8a2ee392010-12-02 02:45:55 +00001275 else if (!getLangOptions().CPlusPlus &&
1276 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1277 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian1518a5ec2010-10-27 16:21:54 +00001278 !D->hasExternalStorage() && !D->getInit() &&
1279 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) {
1280 // Thread local vars aren't considered common linkage.
1281 return llvm::GlobalVariable::CommonLinkage;
1282 }
1283 return llvm::GlobalVariable::ExternalLinkage;
1284}
1285
Chris Lattner36797ab2009-05-05 06:16:31 +00001286/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1287/// implement a function with no prototype, e.g. "int foo() {}". If there are
1288/// existing call uses of the old function in the module, this adjusts them to
1289/// call the new function directly.
1290///
1291/// This is not just a cleanup: the always_inline pass requires direct calls to
1292/// functions to be able to inline them. If there is a bitcast in the way, it
1293/// won't inline them. Instcombine normally deletes these calls, but it isn't
1294/// run at -O0.
1295static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1296 llvm::Function *NewFn) {
1297 // If we're redefining a global as a function, don't transform it.
1298 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1299 if (OldFn == 0) return;
Mike Stump11289f42009-09-09 15:08:12 +00001300
Chris Lattner36797ab2009-05-05 06:16:31 +00001301 const llvm::Type *NewRetTy = NewFn->getReturnType();
1302 llvm::SmallVector<llvm::Value*, 4> ArgList;
1303
1304 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001305 UI != E; ) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001306 // TODO: Do invokes ever occur in C code? If so, we should handle them too.
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001307 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1308 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
Gabor Greif79ac9ed2010-07-28 09:19:33 +00001309 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I)
Gabor Greifd394aec2010-04-10 03:45:50 +00001310 llvm::CallSite CS(CI);
Benjamin Kramer2e8ca0b2010-04-10 11:02:40 +00001311 if (!CI || !CS.isCallee(I)) continue;
Mike Stump11289f42009-09-09 15:08:12 +00001312
Chris Lattner36797ab2009-05-05 06:16:31 +00001313 // If the return types don't match exactly, and if the call isn't dead, then
1314 // we can't transform this call.
1315 if (CI->getType() != NewRetTy && !CI->use_empty())
1316 continue;
1317
1318 // If the function was passed too few arguments, don't transform. If extra
1319 // arguments were passed, we silently drop them. If any of the types
1320 // mismatch, we don't transform.
1321 unsigned ArgNo = 0;
1322 bool DontTransform = false;
1323 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1324 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
Gabor Greifd394aec2010-04-10 03:45:50 +00001325 if (CS.arg_size() == ArgNo ||
1326 CS.getArgument(ArgNo)->getType() != AI->getType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001327 DontTransform = true;
1328 break;
1329 }
1330 }
1331 if (DontTransform)
1332 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001333
Chris Lattner36797ab2009-05-05 06:16:31 +00001334 // Okay, we can transform this. Create the new call instruction and copy
1335 // over the required information.
Gabor Greifd0ef1342010-04-10 02:56:12 +00001336 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
Chris Lattner36797ab2009-05-05 06:16:31 +00001337 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1338 ArgList.end(), "", CI);
1339 ArgList.clear();
Benjamin Kramerdde0fee2009-10-05 13:47:21 +00001340 if (!NewCall->getType()->isVoidTy())
Chris Lattner36797ab2009-05-05 06:16:31 +00001341 NewCall->takeName(CI);
Chris Lattner36797ab2009-05-05 06:16:31 +00001342 NewCall->setAttributes(CI->getAttributes());
Daniel Dunbar0ef34792009-09-12 00:59:20 +00001343 NewCall->setCallingConv(CI->getCallingConv());
Chris Lattner36797ab2009-05-05 06:16:31 +00001344
1345 // Finally, remove the old call, replacing any uses with the new one.
Chris Lattner734351d2009-10-14 05:49:21 +00001346 if (!CI->use_empty())
1347 CI->replaceAllUsesWith(NewCall);
Devang Patel74684892009-10-13 17:02:04 +00001348
Chris Lattnere675d0f2010-04-01 06:31:43 +00001349 // Copy debug location attached to CI.
1350 if (!CI->getDebugLoc().isUnknown())
1351 NewCall->setDebugLoc(CI->getDebugLoc());
Chris Lattner36797ab2009-05-05 06:16:31 +00001352 CI->eraseFromParent();
1353 }
1354}
1355
Daniel Dunbar9c426522008-07-29 23:18:29 +00001356
Chris Lattnere0be0df2009-05-12 21:21:08 +00001357void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnere0be0df2009-05-12 21:21:08 +00001358 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +00001359 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001360 // Get or create the prototype for the function.
Chris Lattnere0be0df2009-05-12 21:21:08 +00001361 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001362
Chris Lattnera85d68e2009-03-21 09:25:43 +00001363 // Strip off a bitcast if we got one back.
1364 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1365 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1366 Entry = CE->getOperand(0);
1367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368
1369
Chris Lattnera85d68e2009-03-21 09:25:43 +00001370 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001371 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001372
Daniel Dunbar99d28352009-03-09 23:53:08 +00001373 // If the types mismatch then we have to rewrite the definition.
Chris Lattner36797ab2009-05-05 06:16:31 +00001374 assert(OldFn->isDeclaration() &&
Chris Lattnera85d68e2009-03-21 09:25:43 +00001375 "Shouldn't replace non-declaration");
Chris Lattner832323e2009-03-21 08:53:37 +00001376
Chris Lattner5eaee562009-03-21 08:38:50 +00001377 // F is the Function* for the one with the wrong type, we must make a new
1378 // Function* and update everything that used F (a declaration) with the new
1379 // Function* (which will be a definition).
1380 //
1381 // This happens if there is a prototype for a function
1382 // (e.g. "int f()") and then a definition of a different type
John McCall7ec50432010-03-19 23:29:14 +00001383 // (e.g. "int f(int x)"). Move the old function aside so that it
1384 // doesn't interfere with GetAddrOfFunction.
1385 OldFn->setName(llvm::StringRef());
Chris Lattnere0be0df2009-05-12 21:21:08 +00001386 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump11289f42009-09-09 15:08:12 +00001387
Chris Lattner36797ab2009-05-05 06:16:31 +00001388 // If this is an implementation of a function without a prototype, try to
1389 // replace any existing uses of the function (which may be calls) with uses
1390 // of the new function
Chris Lattnereb7466d2009-05-12 20:58:15 +00001391 if (D->getType()->isFunctionNoProtoType()) {
Chris Lattner36797ab2009-05-05 06:16:31 +00001392 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattnereb7466d2009-05-12 20:58:15 +00001393 OldFn->removeDeadConstantUsers();
1394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
Chris Lattner5eaee562009-03-21 08:38:50 +00001396 // Replace uses of F with the Function we will endow with a body.
Chris Lattner36797ab2009-05-05 06:16:31 +00001397 if (!Entry->use_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00001398 llvm::Constant *NewPtrForOldDecl =
Owen Andersonade90fd2009-07-29 18:54:39 +00001399 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattner36797ab2009-05-05 06:16:31 +00001400 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1401 }
Mike Stump11289f42009-09-09 15:08:12 +00001402
Chris Lattner5eaee562009-03-21 08:38:50 +00001403 // Ok, delete the old function now, which is dead.
Chris Lattner36797ab2009-05-05 06:16:31 +00001404 OldFn->eraseFromParent();
Mike Stump11289f42009-09-09 15:08:12 +00001405
Chris Lattnera85d68e2009-03-21 09:25:43 +00001406 Entry = NewFn;
Daniel Dunbar9c426522008-07-29 23:18:29 +00001407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
John McCall8e7cb6d2010-11-02 21:04:24 +00001409 // We need to set linkage and visibility on the function before
1410 // generating code for it because various parts of IR generation
1411 // want to propagate this information down (e.g. to local static
1412 // declarations).
Chris Lattnera85d68e2009-03-21 09:25:43 +00001413 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall7cb02202010-05-25 04:30:21 +00001414 setFunctionLinkage(D, Fn);
Daniel Dunbar9c426522008-07-29 23:18:29 +00001415
John McCall8e7cb6d2010-11-02 21:04:24 +00001416 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlssonc6a47892011-01-29 19:39:23 +00001417 setGlobalVisibility(Fn, D);
John McCall8e7cb6d2010-11-02 21:04:24 +00001418
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001419 CodeGenFunction(*this).GenerateCode(D, Fn);
Daniel Dunbar74aa7e12008-08-01 00:01:51 +00001420
Daniel Dunbar38932572009-04-14 08:05:55 +00001421 SetFunctionDefinitionAttributes(D, Fn);
1422 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump11289f42009-09-09 15:08:12 +00001423
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001424 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001425 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001426 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar0beedc12008-09-08 23:44:31 +00001427 AddGlobalDtor(Fn, DA->getPriority());
Daniel Dunbar9c426522008-07-29 23:18:29 +00001428}
1429
John McCall7ec50432010-03-19 23:29:14 +00001430void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1431 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001432 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattner54041692009-03-22 21:47:11 +00001433 assert(AA && "Not an alias?");
1434
Anders Carlssonea836bc2010-06-22 16:16:50 +00001435 llvm::StringRef MangledName = getMangledName(GD);
Mike Stump11289f42009-09-09 15:08:12 +00001436
John McCall7ec50432010-03-19 23:29:14 +00001437 // If there is a definition in the module, then it wins over the alias.
1438 // This is dubious, but allow it to be safe. Just ignore the alias.
1439 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1440 if (Entry && !Entry->isDeclaration())
1441 return;
1442
1443 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattner54041692009-03-22 21:47:11 +00001444
1445 // Create a reference to the named value. This ensures that it is emitted
1446 // if a deferred decl.
1447 llvm::Constant *Aliasee;
1448 if (isa<llvm::FunctionType>(DeclTy))
John McCall7ec50432010-03-19 23:29:14 +00001449 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
Chris Lattner54041692009-03-22 21:47:11 +00001450 else
John McCall7ec50432010-03-19 23:29:14 +00001451 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson9793f0e2009-07-29 22:16:19 +00001452 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattner54041692009-03-22 21:47:11 +00001453
1454 // Create the new alias itself, but don't set a name yet.
Mike Stump11289f42009-09-09 15:08:12 +00001455 llvm::GlobalValue *GA =
Chris Lattner54041692009-03-22 21:47:11 +00001456 new llvm::GlobalAlias(Aliasee->getType(),
1457 llvm::Function::ExternalLinkage,
1458 "", Aliasee, &getModule());
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattner54041692009-03-22 21:47:11 +00001460 if (Entry) {
John McCall7ec50432010-03-19 23:29:14 +00001461 assert(Entry->isDeclaration());
1462
Chris Lattner54041692009-03-22 21:47:11 +00001463 // If there is a declaration in the module, then we had an extern followed
1464 // by the alias, as in:
1465 // extern int test6();
1466 // ...
1467 // int test6() __attribute__((alias("test7")));
1468 //
1469 // Remove it and replace uses of it with the alias.
John McCall7ec50432010-03-19 23:29:14 +00001470 GA->takeName(Entry);
Mike Stump11289f42009-09-09 15:08:12 +00001471
Owen Andersonade90fd2009-07-29 18:54:39 +00001472 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattner54041692009-03-22 21:47:11 +00001473 Entry->getType()));
Chris Lattner54041692009-03-22 21:47:11 +00001474 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +00001475 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +00001476 GA->setName(MangledName);
Chris Lattner54041692009-03-22 21:47:11 +00001477 }
Mike Stump11289f42009-09-09 15:08:12 +00001478
Daniel Dunbar38932572009-04-14 08:05:55 +00001479 // Set attributes which are particular to an alias; this is a
1480 // specialization of the attributes which may be set on a global
1481 // variable/function.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001482 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001483 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1484 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00001485 if (FD->hasBody())
Daniel Dunbar38932572009-04-14 08:05:55 +00001486 GA->setLinkage(llvm::Function::DLLExportLinkage);
1487 } else {
1488 GA->setLinkage(llvm::Function::DLLExportLinkage);
1489 }
Mike Stump11289f42009-09-09 15:08:12 +00001490 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindolac18086a2010-02-23 22:00:30 +00001491 D->hasAttr<WeakRefAttr>() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001492 D->hasAttr<WeakImportAttr>()) {
Daniel Dunbar38932572009-04-14 08:05:55 +00001493 GA->setLinkage(llvm::Function::WeakAnyLinkage);
1494 }
1495
1496 SetCommonAttributes(D, GA);
Chris Lattner54041692009-03-22 21:47:11 +00001497}
1498
Chris Lattnere64911a2009-03-22 21:56:56 +00001499/// getBuiltinLibFunction - Given a builtin id for a function like
1500/// "__builtin_fabsf", return a Function* for "fabsf".
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001501llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1502 unsigned BuiltinID) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001503 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
Mike Stump11289f42009-09-09 15:08:12 +00001504 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001505 "isn't a lib fn");
Mike Stump11289f42009-09-09 15:08:12 +00001506
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001507 // Get the name, skip over the __builtin_ prefix (if necessary).
1508 const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1509 if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1510 Name += 10;
Mike Stump11289f42009-09-09 15:08:12 +00001511
Mike Stump11289f42009-09-09 15:08:12 +00001512 const llvm::FunctionType *Ty =
Eli Friedman4f678f32009-12-09 03:05:59 +00001513 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
Chris Lattner1eec6602007-08-31 04:31:45 +00001514
Daniel Dunbarff0553e2009-09-14 04:33:21 +00001515 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
Chris Lattner1eec6602007-08-31 04:31:45 +00001516}
1517
Chris Lattnerb8be97e2007-12-18 00:25:38 +00001518llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1519 unsigned NumTys) {
1520 return llvm::Intrinsic::getDeclaration(&getModule(),
1521 (llvm::Intrinsic::ID)IID, Tys, NumTys);
1522}
Chris Lattner1eec6602007-08-31 04:31:45 +00001523
Daniel Dunbar64509b22009-07-23 22:52:48 +00001524static llvm::StringMapEntry<llvm::Constant*> &
1525GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1526 const StringLiteral *Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001527 bool TargetIsLSB,
Daniel Dunbar64509b22009-07-23 22:52:48 +00001528 bool &IsUTF16,
1529 unsigned &StringLength) {
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001530 llvm::StringRef String = Literal->getString();
1531 unsigned NumBytes = String.size();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001532
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001533 // Check for simple case.
1534 if (!Literal->containsNonAsciiOrNull()) {
1535 StringLength = NumBytes;
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001536 return Map.GetOrCreateValue(String);
Daniel Dunbarb879c3c2009-09-22 10:03:52 +00001537 }
1538
Daniel Dunbar64509b22009-07-23 22:52:48 +00001539 // Otherwise, convert the UTF8 literals into a byte string.
1540 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001541 const UTF8 *FromPtr = (UTF8 *)String.data();
Daniel Dunbar64509b22009-07-23 22:52:48 +00001542 UTF16 *ToPtr = &ToBuf[0];
Mike Stump11289f42009-09-09 15:08:12 +00001543
Fariborz Jahanian535618b2010-09-07 19:57:04 +00001544 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1545 &ToPtr, ToPtr + NumBytes,
1546 strictConversion);
Mike Stump11289f42009-09-09 15:08:12 +00001547
Daniel Dunbar91ade142009-07-23 23:41:22 +00001548 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar64509b22009-07-23 22:52:48 +00001549 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar91ade142009-07-23 23:41:22 +00001550
1551 // Render the UTF-16 string into a byte array and convert to the target byte
1552 // order.
1553 //
1554 // FIXME: This isn't something we should need to do here.
1555 llvm::SmallString<128> AsBytes;
1556 AsBytes.reserve(StringLength * 2);
1557 for (unsigned i = 0; i != StringLength; ++i) {
1558 unsigned short Val = ToBuf[i];
1559 if (TargetIsLSB) {
1560 AsBytes.push_back(Val & 0xFF);
1561 AsBytes.push_back(Val >> 8);
1562 } else {
1563 AsBytes.push_back(Val >> 8);
1564 AsBytes.push_back(Val & 0xFF);
1565 }
1566 }
Daniel Dunbar4d93a4f2009-08-03 21:47:08 +00001567 // Append one extra null character, the second is automatically added by our
1568 // caller.
1569 AsBytes.push_back(0);
Daniel Dunbar91ade142009-07-23 23:41:22 +00001570
Daniel Dunbar64509b22009-07-23 22:52:48 +00001571 IsUTF16 = true;
Daniel Dunbar91ade142009-07-23 23:41:22 +00001572 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
Daniel Dunbar64509b22009-07-23 22:52:48 +00001573}
1574
1575llvm::Constant *
1576CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1577 unsigned StringLength = 0;
1578 bool isUTF16 = false;
1579 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump11289f42009-09-09 15:08:12 +00001580 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Daniel Dunbar91ade142009-07-23 23:41:22 +00001581 getTargetData().isLittleEndian(),
1582 isUTF16, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001583
Daniel Dunbar64509b22009-07-23 22:52:48 +00001584 if (llvm::Constant *C = Entry.getValue())
1585 return C;
Mike Stump11289f42009-09-09 15:08:12 +00001586
Owen Anderson41a75022009-08-13 21:57:51 +00001587 llvm::Constant *Zero =
1588 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
Daniel Dunbard644ad62008-08-23 18:37:06 +00001589 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump11289f42009-09-09 15:08:12 +00001590
Chris Lattneraa64ca22009-07-16 16:48:25 +00001591 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonb04ea612007-08-21 00:21:21 +00001592 if (!CFConstantStringClassRef) {
1593 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001594 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001595 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattneraa64ca22009-07-16 16:48:25 +00001596 "__CFConstantStringClassReference");
Daniel Dunbard644ad62008-08-23 18:37:06 +00001597 // Decay array -> ptr
1598 CFConstantStringClassRef =
Owen Andersonade90fd2009-07-29 18:54:39 +00001599 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Anders Carlssonb04ea612007-08-21 00:21:21 +00001600 }
Mike Stump11289f42009-09-09 15:08:12 +00001601
Anders Carlssonc2480a52008-11-15 18:54:24 +00001602 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbard644ad62008-08-23 18:37:06 +00001603
Mike Stump11289f42009-09-09 15:08:12 +00001604 const llvm::StructType *STy =
Anders Carlssonc2480a52008-11-15 18:54:24 +00001605 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1606
Anders Carlsson157c3212009-08-16 05:55:31 +00001607 std::vector<llvm::Constant*> Fields(4);
Douglas Gregor91f84212008-12-11 16:49:14 +00001608
Anders Carlssonb04ea612007-08-21 00:21:21 +00001609 // Class pointer.
Anders Carlsson157c3212009-08-16 05:55:31 +00001610 Fields[0] = CFConstantStringClassRef;
Mike Stump11289f42009-09-09 15:08:12 +00001611
Anders Carlssonb04ea612007-08-21 00:21:21 +00001612 // Flags.
Daniel Dunbard644ad62008-08-23 18:37:06 +00001613 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump11289f42009-09-09 15:08:12 +00001614 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson157c3212009-08-16 05:55:31 +00001615 llvm::ConstantInt::get(Ty, 0x07C8);
1616
Anders Carlssonb04ea612007-08-21 00:21:21 +00001617 // String pointer.
Owen Anderson41a75022009-08-13 21:57:51 +00001618 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001619
Chris Lattner3afa3e12009-07-16 05:03:48 +00001620 llvm::GlobalValue::LinkageTypes Linkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001621 bool isConstant;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001622 if (isUTF16) {
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001623 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner3afa3e12009-07-16 05:03:48 +00001624 Linkage = llvm::GlobalValue::InternalLinkage;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001625 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1626 // does make plain ascii ones writable.
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001627 isConstant = true;
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001628 } else {
1629 Linkage = llvm::GlobalValue::PrivateLinkage;
1630 isConstant = !Features.WritableStrings;
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001631 }
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001632
Mike Stump11289f42009-09-09 15:08:12 +00001633 llvm::GlobalVariable *GV =
Chris Lattner4f8a2e22009-10-14 05:55:45 +00001634 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1635 ".str");
Rafael Espindolae79d43da2011-01-17 16:31:00 +00001636 GV->setUnnamedAddr(true);
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001637 if (isUTF16) {
Ken Dycka0f99ff2010-01-26 18:46:23 +00001638 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1639 GV->setAlignment(Align.getQuantity());
Daniel Dunbarfd6cfcf2009-04-03 00:57:44 +00001640 }
Anders Carlsson157c3212009-08-16 05:55:31 +00001641 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1642
Anders Carlssonb04ea612007-08-21 00:21:21 +00001643 // String length.
1644 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson157c3212009-08-16 05:55:31 +00001645 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump11289f42009-09-09 15:08:12 +00001646
Anders Carlssonb04ea612007-08-21 00:21:21 +00001647 // The struct.
Owen Anderson0e0189d2009-07-27 22:29:56 +00001648 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump11289f42009-09-09 15:08:12 +00001649 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1650 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner3afa3e12009-07-16 05:03:48 +00001651 "_unnamed_cfstring_");
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001652 if (const char *Sect = getContext().Target.getCFStringSection())
1653 GV->setSection(Sect);
Daniel Dunbar64509b22009-07-23 22:52:48 +00001654 Entry.setValue(GV);
Mike Stump11289f42009-09-09 15:08:12 +00001655
Anders Carlsson41b7c6b2007-11-01 00:41:52 +00001656 return GV;
Anders Carlssonb04ea612007-08-21 00:21:21 +00001657}
Chris Lattnerfb300092007-11-28 05:34:05 +00001658
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001659llvm::Constant *
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001660CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001661 unsigned StringLength = 0;
1662 bool isUTF16 = false;
1663 llvm::StringMapEntry<llvm::Constant*> &Entry =
1664 GetConstantCFStringEntry(CFConstantStringMap, Literal,
1665 getTargetData().isLittleEndian(),
1666 isUTF16, StringLength);
1667
1668 if (llvm::Constant *C = Entry.getValue())
1669 return C;
1670
1671 llvm::Constant *Zero =
1672 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1673 llvm::Constant *Zeros[] = { Zero, Zero };
1674
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001675 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001676 if (!ConstantStringClassRef) {
1677 std::string StringClass(getLangOptions().ObjCConstantStringClass);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001678 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1679 Ty = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001680 llvm::Constant *GV;
1681 if (StringClass.empty())
1682 GV = CreateRuntimeVariable(Ty,
1683 Features.ObjCNonFragileABI ?
1684 "OBJC_CLASS_$_NSConstantString" :
1685 "_NSConstantStringClassReference");
1686 else {
1687 std::string str;
1688 if (Features.ObjCNonFragileABI)
1689 str = "OBJC_CLASS_$_" + StringClass;
1690 else
1691 str = "_" + StringClass + "ClassReference";
1692 GV = CreateRuntimeVariable(Ty, str);
1693 }
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001694 // Decay array -> ptr
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001695 ConstantStringClassRef =
1696 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001697 }
1698
1699 QualType NSTy = getContext().getNSConstantStringType();
1700
1701 const llvm::StructType *STy =
1702 cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1703
1704 std::vector<llvm::Constant*> Fields(3);
1705
1706 // Class pointer.
Fariborz Jahanian50c925f2010-10-19 17:19:29 +00001707 Fields[0] = ConstantStringClassRef;
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001708
1709 // String pointer.
1710 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1711
1712 llvm::GlobalValue::LinkageTypes Linkage;
1713 bool isConstant;
1714 if (isUTF16) {
1715 // FIXME: why do utf strings get "_" labels instead of "L" labels?
1716 Linkage = llvm::GlobalValue::InternalLinkage;
1717 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1718 // does make plain ascii ones writable.
1719 isConstant = true;
1720 } else {
1721 Linkage = llvm::GlobalValue::PrivateLinkage;
1722 isConstant = !Features.WritableStrings;
1723 }
1724
1725 llvm::GlobalVariable *GV =
1726 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1727 ".str");
Rafael Espindolade089d42011-01-17 22:11:21 +00001728 GV->setUnnamedAddr(true);
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001729 if (isUTF16) {
1730 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1731 GV->setAlignment(Align.getQuantity());
1732 }
1733 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1734
1735 // String length.
1736 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1737 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1738
1739 // The struct.
1740 C = llvm::ConstantStruct::get(STy, Fields);
1741 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1742 llvm::GlobalVariable::PrivateLinkage, C,
1743 "_unnamed_nsstring_");
1744 // FIXME. Fix section.
Fariborz Jahaniand3fa7012010-04-23 22:33:39 +00001745 if (const char *Sect =
1746 Features.ObjCNonFragileABI
1747 ? getContext().Target.getNSStringNonFragileABISection()
1748 : getContext().Target.getNSStringSection())
Fariborz Jahaniane804c282010-04-23 17:41:07 +00001749 GV->setSection(Sect);
1750 Entry.setValue(GV);
1751
1752 return GV;
Fariborz Jahanian63408e82010-04-22 20:26:39 +00001753}
1754
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001755/// GetStringForStringLiteral - Return the appropriate bytes for a
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001756/// string literal, properly padded to match the literal type.
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001757std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
Ken Dycka45a70c2011-01-29 17:53:12 +00001758 const ASTContext &Context = getContext();
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001759 const ConstantArrayType *CAT =
Ken Dycka45a70c2011-01-29 17:53:12 +00001760 Context.getAsConstantArrayType(E->getType());
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001761 assert(CAT && "String isn't pointer or array!");
Mike Stump11289f42009-09-09 15:08:12 +00001762
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001763 // Resize the string to the right size.
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001764 uint64_t RealLen = CAT->getSize().getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +00001765
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001766 if (E->isWide())
Ken Dycka45a70c2011-01-29 17:53:12 +00001767 RealLen *= Context.Target.getWCharWidth() / Context.getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001768
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001769 std::string Str = E->getString().str();
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001770 Str.resize(RealLen, '\0');
Mike Stump11289f42009-09-09 15:08:12 +00001771
Daniel Dunbar6dfdf8c2008-08-10 20:25:57 +00001772 return Str;
1773}
1774
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001775/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1776/// constant array for the given string literal.
1777llvm::Constant *
1778CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1779 // FIXME: This can be more efficient.
Eli Friedman49ddc5f2009-11-16 05:55:46 +00001780 // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1781 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1782 if (S->isWide()) {
1783 llvm::Type *DestTy =
1784 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1785 C = llvm::ConstantExpr::getBitCast(C, DestTy);
1786 }
1787 return C;
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001788}
1789
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001790/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1791/// array for the given ObjCEncodeExpr node.
1792llvm::Constant *
1793CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1794 std::string Str;
1795 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedman4663a332009-03-07 20:17:55 +00001796
1797 return GetAddrOfConstantCString(Str);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001798}
1799
1800
Chris Lattner36fc8792008-02-11 00:02:17 +00001801/// GenerateWritableString -- Creates storage for a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001802static llvm::Constant *GenerateStringLiteral(const std::string &str,
Chris Lattnerfb300092007-11-28 05:34:05 +00001803 bool constant,
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001804 CodeGenModule &CGM,
1805 const char *GlobalName) {
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001806 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson41a75022009-08-13 21:57:51 +00001807 llvm::Constant *C =
1808 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
Mike Stump11289f42009-09-09 15:08:12 +00001809
Chris Lattnerfb300092007-11-28 05:34:05 +00001810 // Create a global variable for this string
Rafael Espindolab7f60e32011-01-10 22:34:03 +00001811 llvm::GlobalVariable *GV =
1812 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1813 llvm::GlobalValue::PrivateLinkage,
1814 C, GlobalName);
1815 GV->setUnnamedAddr(true);
1816 return GV;
Chris Lattnerfb300092007-11-28 05:34:05 +00001817}
1818
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001819/// GetAddrOfConstantString - Returns a pointer to a character array
1820/// containing the literal. This contents are exactly that of the
1821/// given string, i.e. it will not be null terminated automatically;
1822/// see GetAddrOfConstantCString. Note that whether the result is
1823/// actually a pointer to an LLVM constant depends on
1824/// Feature.WriteableStrings.
1825///
1826/// The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001827llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1828 const char *GlobalName) {
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001829 bool IsConstant = !Features.WritableStrings;
1830
1831 // Get the default prefix if a name wasn't specified.
1832 if (!GlobalName)
Chris Lattner3afa3e12009-07-16 05:03:48 +00001833 GlobalName = ".str";
Daniel Dunbar08b216a2009-03-31 23:42:16 +00001834
1835 // Don't share any string literals if strings aren't constant.
1836 if (!IsConstant)
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001837 return GenerateStringLiteral(str, false, *this, GlobalName);
Mike Stump11289f42009-09-09 15:08:12 +00001838
1839 llvm::StringMapEntry<llvm::Constant *> &Entry =
Chris Lattner3afa3e12009-07-16 05:03:48 +00001840 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
Chris Lattnerfb300092007-11-28 05:34:05 +00001841
1842 if (Entry.getValue())
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001843 return Entry.getValue();
Chris Lattnerfb300092007-11-28 05:34:05 +00001844
1845 // Create a global variable for this.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001846 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
Chris Lattnerfb300092007-11-28 05:34:05 +00001847 Entry.setValue(C);
1848 return C;
1849}
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001850
1851/// GetAddrOfConstantCString - Returns a pointer to a character
1852/// array containing the literal and a terminating '\-'
1853/// character. The result has pointer to array type.
Daniel Dunbardfcf5992008-10-17 21:56:50 +00001854llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1855 const char *GlobalName){
Chris Lattner2e41b0e2008-12-09 19:10:54 +00001856 return GetAddrOfConstantString(str + '\0', GlobalName);
Daniel Dunbarc4baa062008-08-13 23:20:05 +00001857}
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001858
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001859/// EmitObjCPropertyImplementations - Emit information for synthesized
1860/// properties for an implementation.
Mike Stump11289f42009-09-09 15:08:12 +00001861void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001862 ObjCImplementationDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00001863 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001864 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001865 ObjCPropertyImplDecl *PID = *i;
Mike Stump11289f42009-09-09 15:08:12 +00001866
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001867 // Dynamic is just for type-checking.
1868 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1869 ObjCPropertyDecl *PD = PID->getPropertyDecl();
1870
1871 // Determine which methods need to be implemented, some may have
1872 // been overridden. Note that ::isSynthesized is not the method
1873 // we want, that just indicates if the decl came from a
1874 // property. What we want to know is if the method is defined in
1875 // this implementation.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001876 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001877 CodeGenFunction(*this).GenerateObjCGetter(
1878 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001879 if (!PD->isReadOnly() &&
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001880 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001881 CodeGenFunction(*this).GenerateObjCSetter(
1882 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001883 }
1884 }
1885}
1886
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001887/// EmitObjCIvarInitializations - Emit information for ivar initialization
1888/// for an implementation.
1889void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1890 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1891 return;
1892 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1893 assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1894 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1895 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1896 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1897 D->getLocation(),
1898 D->getLocation(), cxxSelector,
1899 getContext().VoidTy, 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001900 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001901 ObjCMethodDecl::Required);
1902 D->addInstanceMethod(DTORMethod);
1903 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1904
1905 II = &getContext().Idents.get(".cxx_construct");
1906 cxxSelector = getContext().Selectors.getSelector(0, &II);
1907 // The constructor returns 'self'.
1908 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1909 D->getLocation(),
1910 D->getLocation(), cxxSelector,
1911 getContext().getObjCIdType(), 0,
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001912 DC, true, false, true, false,
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001913 ObjCMethodDecl::Required);
1914 D->addInstanceMethod(CTORMethod);
1915 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1916
1917
1918}
1919
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001920/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson237f3492009-04-01 00:58:25 +00001921void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001922 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson237f3492009-04-01 00:58:25 +00001923 I != E; ++I)
1924 EmitTopLevelDecl(*I);
1925}
1926
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001927// EmitLinkageSpec - Emit all declarations in a linkage spec.
1928void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmane480ce32009-08-01 20:48:04 +00001929 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1930 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001931 ErrorUnsupported(LSD, "linkage spec");
1932 return;
1933 }
1934
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001935 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00001936 I != E; ++I)
1937 EmitTopLevelDecl(*I);
1938}
1939
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001940/// EmitTopLevelDecl - Emit code for a single top level declaration.
1941void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1942 // If an error has occurred, stop code generation, but continue
1943 // parsing and semantic analysis (to ensure all warnings and errors
1944 // are emitted).
1945 if (Diags.hasErrorOccurred())
1946 return;
1947
Douglas Gregor70d83e22009-06-29 17:30:29 +00001948 // Ignore dependent declarations.
1949 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1950 return;
Mike Stump11289f42009-09-09 15:08:12 +00001951
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001952 switch (D->getKind()) {
Anders Carlsson6c0a6e42009-08-25 13:14:46 +00001953 case Decl::CXXConversion:
Anders Carlsson468fa632009-04-04 20:47:02 +00001954 case Decl::CXXMethod:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001955 case Decl::Function:
Douglas Gregor70d83e22009-06-29 17:30:29 +00001956 // Skip function templates
1957 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1958 return;
Mike Stump11289f42009-09-09 15:08:12 +00001959
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001960 EmitGlobal(cast<FunctionDecl>(D));
1961 break;
1962
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001963 case Decl::Var:
Anders Carlssonecf9bf02009-09-10 23:43:36 +00001964 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001965 break;
1966
Anders Carlssonf7475242009-04-15 15:55:24 +00001967 // C++ Decls
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001968 case Decl::Namespace:
Anders Carlsson237f3492009-04-01 00:58:25 +00001969 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001970 break;
Douglas Gregorfec52632009-06-20 00:51:54 +00001971 // No code generation needed.
John McCall1e9de052009-11-17 09:33:40 +00001972 case Decl::UsingShadow:
Douglas Gregorfec52632009-06-20 00:51:54 +00001973 case Decl::Using:
Douglas Gregore5feb512009-09-02 23:49:23 +00001974 case Decl::UsingDirective:
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001975 case Decl::ClassTemplate:
1976 case Decl::FunctionTemplate:
Anders Carlsson649a17e2009-09-23 19:19:16 +00001977 case Decl::NamespaceAlias:
Douglas Gregorfec52632009-06-20 00:51:54 +00001978 break;
Anders Carlssonf7475242009-04-15 15:55:24 +00001979 case Decl::CXXConstructor:
Anders Carlsson0ade9712009-11-24 05:16:24 +00001980 // Skip function templates
1981 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1982 return;
1983
Anders Carlssonf7475242009-04-15 15:55:24 +00001984 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1985 break;
Anders Carlssoneaa28f72009-04-17 01:58:57 +00001986 case Decl::CXXDestructor:
1987 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1988 break;
Anders Carlsson87835432009-06-11 21:22:55 +00001989
1990 case Decl::StaticAssert:
1991 // Nothing to do.
1992 break;
1993
Anders Carlssonf7475242009-04-15 15:55:24 +00001994 // Objective-C Decls
Mike Stump11289f42009-09-09 15:08:12 +00001995
Fariborz Jahanian3654e652009-03-18 22:33:24 +00001996 // Forward declarations, no (immediate) code generation.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001997 case Decl::ObjCClass:
Daniel Dunbarfce4be82008-08-15 23:26:23 +00001998 case Decl::ObjCForwardProtocol:
Chris Lattnerd18136a2009-04-01 02:36:43 +00001999 case Decl::ObjCInterface:
Chris Lattnerd18136a2009-04-01 02:36:43 +00002000 break;
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00002001
2002 case Decl::ObjCCategory: {
2003 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
2004 if (CD->IsClassExtension() && CD->hasSynthBitfield())
2005 Context.ResetObjCLayout(CD->getClassInterface());
2006 break;
2007 }
2008
Chris Lattnerd18136a2009-04-01 02:36:43 +00002009
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002010 case Decl::ObjCProtocol:
Fariborz Jahanian629aed92009-03-21 18:06:45 +00002011 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002012 break;
2013
2014 case Decl::ObjCCategoryImpl:
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002015 // Categories have properties but don't support synthesize so we
2016 // can ignore them here.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002017 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
2018 break;
2019
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002020 case Decl::ObjCImplementation: {
2021 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
Fariborz Jahanianbf9294f2010-08-23 18:51:39 +00002022 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield())
2023 Context.ResetObjCLayout(OMD->getClassInterface());
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002024 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00002025 EmitObjCIvarInitializations(OMD);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00002026 Runtime->GenerateClass(OMD);
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002027 break;
Mike Stump11289f42009-09-09 15:08:12 +00002028 }
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002029 case Decl::ObjCMethod: {
2030 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2031 // If this is not a prototype, emit the body.
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002032 if (OMD->getBody())
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002033 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2034 break;
2035 }
Mike Stump11289f42009-09-09 15:08:12 +00002036 case Decl::ObjCCompatibleAlias:
Fariborz Jahanian17290c32009-01-08 01:10:55 +00002037 // compatibility-alias is a directive and has no code gen.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002038 break;
2039
Anders Carlssoncbaeb9e2009-04-02 05:55:18 +00002040 case Decl::LinkageSpec:
2041 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002042 break;
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002043
2044 case Decl::FileScopeAsm: {
2045 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002046 llvm::StringRef AsmString = AD->getAsmString()->getString();
Mike Stump11289f42009-09-09 15:08:12 +00002047
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002048 const std::string &S = getModule().getModuleInlineAsm();
2049 if (S.empty())
2050 getModule().setModuleInlineAsm(AsmString);
2051 else
Benjamin Kramerb11118b2009-12-11 13:33:18 +00002052 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002053 break;
2054 }
Mike Stump11289f42009-09-09 15:08:12 +00002055
2056 default:
Mike Stump18bb9282009-05-16 07:57:57 +00002057 // Make sure we handled everything we should, every other kind is a
2058 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2059 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbarfce4be82008-08-15 23:26:23 +00002060 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2061 }
2062}
John McCall09ae0322010-07-06 23:57:41 +00002063
2064/// Turns the given pointer into a constant.
2065static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2066 const void *Ptr) {
2067 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
2068 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
2069 return llvm::ConstantInt::get(i64, PtrInt);
2070}
2071
2072static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2073 llvm::NamedMDNode *&GlobalMetadata,
2074 GlobalDecl D,
2075 llvm::GlobalValue *Addr) {
2076 if (!GlobalMetadata)
2077 GlobalMetadata =
2078 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2079
2080 // TODO: should we report variant information for ctors/dtors?
2081 llvm::Value *Ops[] = {
2082 Addr,
2083 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2084 };
2085 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2));
2086}
2087
2088/// Emits metadata nodes associating all the global values in the
2089/// current module with the Decls they came from. This is useful for
2090/// projects using IR gen as a subroutine.
2091///
2092/// Since there's currently no way to associate an MDNode directly
2093/// with an llvm::GlobalValue, we create a global named metadata
2094/// with the name 'clang.global.decl.ptrs'.
2095void CodeGenModule::EmitDeclMetadata() {
2096 llvm::NamedMDNode *GlobalMetadata = 0;
2097
2098 // StaticLocalDeclMap
2099 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator
2100 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2101 I != E; ++I) {
2102 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2103 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2104 }
2105}
2106
2107/// Emits metadata nodes for all the local variables in the current
2108/// function.
2109void CodeGenFunction::EmitDeclMetadata() {
2110 if (LocalDeclMap.empty()) return;
2111
2112 llvm::LLVMContext &Context = getLLVMContext();
2113
2114 // Find the unique metadata ID for this name.
2115 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2116
2117 llvm::NamedMDNode *GlobalMetadata = 0;
2118
2119 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2120 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2121 const Decl *D = I->first;
2122 llvm::Value *Addr = I->second;
2123
2124 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2125 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
2126 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1));
2127 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2128 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2129 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2130 }
2131 }
2132}
Daniel Dunbar900546d2010-07-16 00:00:15 +00002133
2134///@name Custom Runtime Function Interfaces
2135///@{
2136//
2137// FIXME: These can be eliminated once we can have clients just get the required
2138// AST nodes from the builtin tables.
2139
2140llvm::Constant *CodeGenModule::getBlockObjectDispose() {
2141 if (BlockObjectDispose)
2142 return BlockObjectDispose;
2143
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002144 // If we saw an explicit decl, use that.
2145 if (BlockObjectDisposeDecl) {
2146 return BlockObjectDispose = GetAddrOfFunction(
2147 BlockObjectDisposeDecl,
2148 getTypes().GetFunctionType(BlockObjectDisposeDecl));
2149 }
2150
2151 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002152 const llvm::FunctionType *FTy;
2153 std::vector<const llvm::Type*> ArgTys;
2154 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2155 ArgTys.push_back(PtrToInt8Ty);
2156 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2157 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2158 return BlockObjectDispose =
2159 CreateRuntimeFunction(FTy, "_Block_object_dispose");
2160}
2161
2162llvm::Constant *CodeGenModule::getBlockObjectAssign() {
2163 if (BlockObjectAssign)
2164 return BlockObjectAssign;
2165
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002166 // If we saw an explicit decl, use that.
2167 if (BlockObjectAssignDecl) {
2168 return BlockObjectAssign = GetAddrOfFunction(
2169 BlockObjectAssignDecl,
2170 getTypes().GetFunctionType(BlockObjectAssignDecl));
2171 }
2172
2173 // Otherwise construct the function by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002174 const llvm::FunctionType *FTy;
2175 std::vector<const llvm::Type*> ArgTys;
2176 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
2177 ArgTys.push_back(PtrToInt8Ty);
2178 ArgTys.push_back(PtrToInt8Ty);
2179 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
2180 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
2181 return BlockObjectAssign =
2182 CreateRuntimeFunction(FTy, "_Block_object_assign");
2183}
2184
2185llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
2186 if (NSConcreteGlobalBlock)
2187 return NSConcreteGlobalBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002188
2189 // If we saw an explicit decl, use that.
2190 if (NSConcreteGlobalBlockDecl) {
2191 return NSConcreteGlobalBlock = GetAddrOfGlobalVar(
2192 NSConcreteGlobalBlockDecl,
2193 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType()));
2194 }
2195
2196 // Otherwise construct the variable by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002197 return NSConcreteGlobalBlock = CreateRuntimeVariable(
2198 PtrToInt8Ty, "_NSConcreteGlobalBlock");
2199}
2200
2201llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
2202 if (NSConcreteStackBlock)
2203 return NSConcreteStackBlock;
Daniel Dunbar3348e2d2010-07-16 00:00:19 +00002204
2205 // If we saw an explicit decl, use that.
2206 if (NSConcreteStackBlockDecl) {
2207 return NSConcreteStackBlock = GetAddrOfGlobalVar(
2208 NSConcreteStackBlockDecl,
2209 getTypes().ConvertType(NSConcreteStackBlockDecl->getType()));
2210 }
2211
2212 // Otherwise construct the variable by hand.
Daniel Dunbar900546d2010-07-16 00:00:15 +00002213 return NSConcreteStackBlock = CreateRuntimeVariable(
2214 PtrToInt8Ty, "_NSConcreteStackBlock");
2215}
2216
2217///@}