blob: d7e0d5fcbc147ead25a29552b4aa103d689e15c4 [file] [log] [blame]
Anders Carlssonacfde802009-02-12 00:39:25 +00001//===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit blocks.
11//
12//===----------------------------------------------------------------------===//
13
Mike Stumpb1a6e682009-09-30 02:43:10 +000014#include "CGDebugInfo.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000015#include "CodeGenFunction.h"
Fariborz Jahanian263c4de2010-02-10 23:34:57 +000016#include "CGObjCRuntime.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "CodeGenModule.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000018#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000019#include "llvm/Module.h"
Benjamin Kramer6876fe62010-03-31 15:04:05 +000020#include "llvm/ADT/SmallSet.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000021#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000022#include <algorithm>
Torok Edwinf42e4a62009-08-24 13:25:12 +000023
Anders Carlssonacfde802009-02-12 00:39:25 +000024using namespace clang;
25using namespace CodeGen;
26
John McCallee504292010-05-21 04:11:14 +000027/// CGBlockInfo - Information to generate a block literal.
28class clang::CodeGen::CGBlockInfo {
29public:
30 /// Name - The name of the block, kindof.
31 const char *Name;
32
33 /// DeclRefs - Variables from parent scopes that have been
34 /// imported into this block.
35 llvm::SmallVector<const BlockDeclRefExpr *, 8> DeclRefs;
36
37 /// InnerBlocks - This block and the blocks it encloses.
38 llvm::SmallPtrSet<const DeclContext *, 4> InnerBlocks;
39
40 /// CXXThisRef - Non-null if 'this' was required somewhere, in
41 /// which case this is that expression.
42 const CXXThisExpr *CXXThisRef;
43
44 /// NeedsObjCSelf - True if something in this block has an implicit
45 /// reference to 'self'.
46 bool NeedsObjCSelf;
47
48 /// These are initialized by GenerateBlockFunction.
49 bool BlockHasCopyDispose;
50 CharUnits BlockSize;
51 CharUnits BlockAlign;
52 llvm::SmallVector<const Expr*, 8> BlockLayout;
53
54 CGBlockInfo(const char *Name);
55};
56
57CGBlockInfo::CGBlockInfo(const char *N)
58 : Name(N), CXXThisRef(0), NeedsObjCSelf(false) {
59
60 // Skip asm prefix, if any.
61 if (Name && Name[0] == '\01')
62 ++Name;
63}
64
65
Mike Stumpcf62d392009-03-06 18:42:23 +000066llvm::Constant *CodeGenFunction::
Blaine Garst2a7eb282010-02-23 21:51:17 +000067BuildDescriptorBlockDecl(const BlockExpr *BE, bool BlockHasCopyDispose, CharUnits Size,
Mike Stumpa803b0e2009-03-25 17:58:24 +000068 const llvm::StructType* Ty,
Mike Stump08920992009-03-07 02:35:30 +000069 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump56129b12009-02-13 16:55:51 +000070 const llvm::Type *UnsignedLongTy
71 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000072 llvm::Constant *C;
73 std::vector<llvm::Constant*> Elts;
74
75 // reserved
Owen Anderson4a28d5d2009-07-24 23:12:58 +000076 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000077 Elts.push_back(C);
78
79 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000080 // FIXME: What is the right way to say this doesn't fit? We should give
81 // a user diagnostic in that case. Better fix would be to change the
82 // API to size_t.
Ken Dyck199c3d62010-01-11 17:06:35 +000083 C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
Mike Stumpe5fee252009-02-13 16:19:19 +000084 Elts.push_back(C);
85
Blaine Garst2a7eb282010-02-23 21:51:17 +000086 // optional copy/dispose helpers
Mike Stumpe5fee252009-02-13 16:19:19 +000087 if (BlockHasCopyDispose) {
88 // copy_func_helper_decl
Mike Stumpb7477cf2009-04-10 18:52:28 +000089 Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000090
91 // destroy_func_decl
Mike Stumpb7477cf2009-04-10 18:52:28 +000092 Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000093 }
94
Blaine Garst2a7eb282010-02-23 21:51:17 +000095 // Signature. non-optional ObjC-style method descriptor @encode sequence
96 std::string BlockTypeEncoding;
97 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
98
99 Elts.push_back(llvm::ConstantExpr::getBitCast(
100 CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty));
101
102 // Layout.
103 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
104 Elts.push_back(C);
105
Nick Lewycky0d36dd22009-09-19 20:00:52 +0000106 C = llvm::ConstantStruct::get(VMContext, Elts, false);
Mike Stumpe5fee252009-02-13 16:19:19 +0000107
Owen Anderson1c431b32009-07-08 19:05:04 +0000108 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
Mike Stumpe5fee252009-02-13 16:19:19 +0000109 llvm::GlobalValue::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000110 C, "__block_descriptor_tmp");
Mike Stumpe5fee252009-02-13 16:19:19 +0000111 return C;
112}
113
Mike Stump2a998142009-03-04 18:17:45 +0000114llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Chris Lattnere2f79b62009-05-13 02:50:56 +0000115 if (NSConcreteGlobalBlock == 0)
Mike Stump1eb44332009-09-09 15:08:12 +0000116 NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
Chris Lattnere2f79b62009-05-13 02:50:56 +0000117 "_NSConcreteGlobalBlock");
Mike Stumpf99f1d02009-02-13 17:23:42 +0000118 return NSConcreteGlobalBlock;
119}
120
Mike Stump2a998142009-03-04 18:17:45 +0000121llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Chris Lattnere2f79b62009-05-13 02:50:56 +0000122 if (NSConcreteStackBlock == 0)
Mike Stump1eb44332009-09-09 15:08:12 +0000123 NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
Chris Lattnere2f79b62009-05-13 02:50:56 +0000124 "_NSConcreteStackBlock");
Mike Stump59c5b112009-02-13 19:29:27 +0000125 return NSConcreteStackBlock;
126}
127
John McCallee504292010-05-21 04:11:14 +0000128static void CollectBlockDeclRefInfo(const Stmt *S, CGBlockInfo &Info) {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000129 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
130 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000131 if (*I)
John McCallee504292010-05-21 04:11:14 +0000132 CollectBlockDeclRefInfo(*I, Info);
Mike Stump00470a12009-03-05 08:32:30 +0000133
Mike Stumpea26cb52009-10-21 03:49:08 +0000134 // We want to ensure we walk down into block literals so we can find
135 // all nested BlockDeclRefExprs.
Mike Stump38e16272009-10-21 22:01:24 +0000136 if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallee504292010-05-21 04:11:14 +0000137 Info.InnerBlocks.insert(BE->getBlockDecl());
138 CollectBlockDeclRefInfo(BE->getBody(), Info);
Mike Stump38e16272009-10-21 22:01:24 +0000139 }
Mike Stumpea26cb52009-10-21 03:49:08 +0000140
John McCallee504292010-05-21 04:11:14 +0000141 else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
142 const ValueDecl *D = BDRE->getDecl();
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000143 // FIXME: Handle enums.
John McCallee504292010-05-21 04:11:14 +0000144 if (isa<FunctionDecl>(D))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000145 return;
Mike Stump00470a12009-03-05 08:32:30 +0000146
John McCallee504292010-05-21 04:11:14 +0000147 if (isa<ImplicitParamDecl>(D) &&
148 isa<ObjCMethodDecl>(D->getDeclContext()) &&
149 cast<ObjCMethodDecl>(D->getDeclContext())->getSelfDecl() == D) {
150 Info.NeedsObjCSelf = true;
151 return;
152 }
153
Mike Stump38e16272009-10-21 22:01:24 +0000154 // Only Decls that escape are added.
John McCallee504292010-05-21 04:11:14 +0000155 if (!Info.InnerBlocks.count(D->getDeclContext()))
Mike Stump38e16272009-10-21 22:01:24 +0000156 Info.DeclRefs.push_back(BDRE);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000157 }
John McCallea1471e2010-05-20 01:18:31 +0000158
John McCallee504292010-05-21 04:11:14 +0000159 // Make sure to capture implicit 'self' references due to super calls.
160 else if (const ObjCMessageExpr *E = dyn_cast<ObjCMessageExpr>(S))
161 if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
162 E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
163 Info.NeedsObjCSelf = true;
164
165 // Getter/setter uses may also cause implicit super references,
166 // which we can check for with:
167 else if (isa<ObjCSuperExpr>(S))
168 Info.NeedsObjCSelf = true;
169
170 else if (isa<CXXThisExpr>(S))
John McCallea1471e2010-05-20 01:18:31 +0000171 Info.CXXThisRef = cast<CXXThisExpr>(S);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000172}
173
John McCallee504292010-05-21 04:11:14 +0000174/// CanBlockBeGlobal - Given a CGBlockInfo struct, determines if a block can be
Mike Stump58a85142009-03-04 22:48:06 +0000175/// declared as a global variable instead of on the stack.
John McCallee504292010-05-21 04:11:14 +0000176static bool CanBlockBeGlobal(const CGBlockInfo &Info) {
Mike Stumpea26cb52009-10-21 03:49:08 +0000177 return Info.DeclRefs.empty();
178}
179
180/// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
181/// ensure we can generate the debug information for the parameter for the block
182/// invoke function.
John McCallee504292010-05-21 04:11:14 +0000183static void AllocateAllBlockDeclRefs(CodeGenFunction &CGF, CGBlockInfo &Info) {
John McCallea1471e2010-05-20 01:18:31 +0000184 if (Info.CXXThisRef)
John McCallee504292010-05-21 04:11:14 +0000185 CGF.AllocateBlockCXXThisPointer(Info.CXXThisRef);
Mike Stumpea26cb52009-10-21 03:49:08 +0000186
187 for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
John McCallee504292010-05-21 04:11:14 +0000188 CGF.AllocateBlockDecl(Info.DeclRefs[i]);
189
190 if (Info.NeedsObjCSelf) {
191 ValueDecl *Self = cast<ObjCMethodDecl>(CGF.CurFuncDecl)->getSelfDecl();
192 BlockDeclRefExpr *BDRE =
193 new (CGF.getContext()) BlockDeclRefExpr(Self, Self->getType(),
194 SourceLocation(), false);
195 Info.DeclRefs.push_back(BDRE);
196 CGF.AllocateBlockDecl(BDRE);
197 }
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000198}
199
Mike Stump58a85142009-03-04 22:48:06 +0000200// FIXME: Push most into CGM, passing down a few bits, like current function
201// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000202llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000203 std::string Name = CurFn->getName();
John McCallee504292010-05-21 04:11:14 +0000204 CGBlockInfo Info(Name.c_str());
205 Info.InnerBlocks.insert(BE->getBlockDecl());
206 CollectBlockDeclRefInfo(BE->getBody(), Info);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000207
208 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000209 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
210 // to just have one code path. We should move this function into CGM and pass
211 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000212 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000213 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump00470a12009-03-05 08:32:30 +0000214
David Chisnall5e530af2009-11-17 19:33:30 +0000215 size_t BlockFields = 5;
216
David Chisnall5e530af2009-11-17 19:33:30 +0000217 std::vector<llvm::Constant*> Elts(BlockFields);
218
Mike Stumpe5fee252009-02-13 16:19:19 +0000219 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000220 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000221
Mike Stumpe5fee252009-02-13 16:19:19 +0000222 {
223 // C = BuildBlockStructInitlist();
Blaine Garsta36e2232010-03-05 01:29:59 +0000224 unsigned int flags = BLOCK_HAS_SIGNATURE;
David Chisnall5e530af2009-11-17 19:33:30 +0000225
Mike Stump00470a12009-03-05 08:32:30 +0000226 // We run this first so that we set BlockHasCopyDispose from the entire
227 // block literal.
228 // __invoke
Mike Stump00470a12009-03-05 08:32:30 +0000229 llvm::Function *Fn
Mike Stumpbb304192009-09-24 22:31:14 +0000230 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
John McCallee504292010-05-21 04:11:14 +0000231 LocalDeclMap);
232 BlockHasCopyDispose |= Info.BlockHasCopyDispose;
Mike Stump00470a12009-03-05 08:32:30 +0000233 Elts[3] = Fn;
234
Mike Stumpf5408fe2009-05-16 07:57:57 +0000235 // FIXME: Don't use BlockHasCopyDispose, it is set more often then
236 // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
John McCallee504292010-05-21 04:11:14 +0000237 if (Info.BlockHasCopyDispose)
Mike Stumpe5fee252009-02-13 16:19:19 +0000238 flags |= BLOCK_HAS_COPY_DISPOSE;
239
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000240 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000241 C = CGM.getNSConcreteStackBlock();
Owen Anderson3c4972d2009-07-29 18:54:39 +0000242 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump00470a12009-03-05 08:32:30 +0000243 Elts[0] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000244
245 // __flags
Blaine Garsta36e2232010-03-05 01:29:59 +0000246 {
247 QualType BPT = BE->getType();
248 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
249 QualType ResultType = ftype->getResultType();
250
251 CallArgList Args;
252 CodeGenTypes &Types = CGM.getTypes();
253 const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000254 FunctionType::ExtInfo());
Blaine Garsta36e2232010-03-05 01:29:59 +0000255 if (CGM.ReturnTypeUsesSret(FnInfo))
256 flags |= BLOCK_USE_STRET;
257 }
Mike Stumpe5fee252009-02-13 16:19:19 +0000258 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
259 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000260 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump00470a12009-03-05 08:32:30 +0000261 Elts[1] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000262
263 // __reserved
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000264 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump00470a12009-03-05 08:32:30 +0000265 Elts[2] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000266
John McCallee504292010-05-21 04:11:14 +0000267 if (Info.BlockLayout.empty()) {
Mike Stumpcf62d392009-03-06 18:42:23 +0000268 // __descriptor
John McCallee504292010-05-21 04:11:14 +0000269 Elts[4] = BuildDescriptorBlockDecl(BE, Info.BlockHasCopyDispose,
270 Info.BlockSize, 0, 0);
Mike Stumpcf62d392009-03-06 18:42:23 +0000271
Mike Stump5570cfe2009-03-01 20:07:53 +0000272 // Optimize to being a global block.
273 Elts[0] = CGM.getNSConcreteGlobalBlock();
Blaine Garsta36e2232010-03-05 01:29:59 +0000274
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000275 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
Mike Stump5570cfe2009-03-01 20:07:53 +0000276
Nick Lewycky0d36dd22009-09-19 20:00:52 +0000277 C = llvm::ConstantStruct::get(VMContext, Elts, false);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000278
Owen Anderson1c431b32009-07-08 19:05:04 +0000279 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000280 llvm::GlobalValue::InternalLinkage, C,
281 "__block_holder_tmp_" +
282 llvm::Twine(CGM.getGlobalUniqueCount()));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000283 QualType BPT = BE->getType();
Owen Anderson3c4972d2009-07-29 18:54:39 +0000284 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000285 return C;
286 }
Mike Stump00470a12009-03-05 08:32:30 +0000287
John McCallee504292010-05-21 04:11:14 +0000288 std::vector<const llvm::Type *> Types(BlockFields+Info.BlockLayout.size());
Mike Stump08920992009-03-07 02:35:30 +0000289 for (int i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000290 Types[i] = Elts[i]->getType();
Mike Stump08920992009-03-07 02:35:30 +0000291 Types[4] = PtrToInt8Ty;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000292
John McCallee504292010-05-21 04:11:14 +0000293 for (unsigned i = 0, n = Info.BlockLayout.size(); i != n; ++i) {
294 const Expr *E = Info.BlockLayout[i];
Mike Stumpa99038c2009-02-28 09:07:16 +0000295 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
296 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000297 if (BDRE && BDRE->isByRef()) {
David Chisnall5e530af2009-11-17 19:33:30 +0000298 Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000299 } else
David Chisnall5e530af2009-11-17 19:33:30 +0000300 Types[i+BlockFields] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000301 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000302
Owen Anderson47a434f2009-08-05 23:18:46 +0000303 llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000304
305 llvm::AllocaInst *A = CreateTempAlloca(Ty);
John McCallee504292010-05-21 04:11:14 +0000306 A->setAlignment(Info.BlockAlign.getQuantity());
Mike Stump8a2b4b12009-02-25 23:33:13 +0000307 V = A;
308
John McCallea1471e2010-05-20 01:18:31 +0000309 // Build layout / cleanup information for all the data entries in the
310 // layout, and write the enclosing fields into the type.
John McCallee504292010-05-21 04:11:14 +0000311 std::vector<HelperInfo> NoteForHelper(Info.BlockLayout.size());
John McCallea1471e2010-05-20 01:18:31 +0000312 unsigned NumHelpers = 0;
Mike Stump08920992009-03-07 02:35:30 +0000313
314 for (unsigned i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000315 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump00470a12009-03-05 08:32:30 +0000316
John McCallee504292010-05-21 04:11:14 +0000317 for (unsigned i=0; i < Info.BlockLayout.size(); ++i) {
318 const Expr *E = Info.BlockLayout[i];
Mike Stump8a2b4b12009-02-25 23:33:13 +0000319
John McCallea1471e2010-05-20 01:18:31 +0000320 // Skip padding.
321 if (isa<DeclRefExpr>(E)) continue;
Mike Stumpa99038c2009-02-28 09:07:16 +0000322
John McCallea1471e2010-05-20 01:18:31 +0000323 llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
324 HelperInfo &Note = NoteForHelper[NumHelpers++];
Mike Stumpa99038c2009-02-28 09:07:16 +0000325
John McCallea1471e2010-05-20 01:18:31 +0000326 Note.index = i+5;
Mike Stump08920992009-03-07 02:35:30 +0000327
John McCallea1471e2010-05-20 01:18:31 +0000328 if (isa<CXXThisExpr>(E)) {
329 Note.RequiresCopying = false;
330 Note.flag = BLOCK_FIELD_IS_OBJECT;
Mike Stumpa99038c2009-02-28 09:07:16 +0000331
John McCallea1471e2010-05-20 01:18:31 +0000332 Builder.CreateStore(LoadCXXThis(), Addr);
333 continue;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000334 }
John McCallea1471e2010-05-20 01:18:31 +0000335
336 const BlockDeclRefExpr *BDRE = cast<BlockDeclRefExpr>(E);
337 const ValueDecl *VD = BDRE->getDecl();
338 QualType T = VD->getType();
339
340 Note.RequiresCopying = BlockRequiresCopying(T);
341
342 if (BDRE->isByRef()) {
343 Note.flag = BLOCK_FIELD_IS_BYREF;
344 if (T.isObjCGCWeak())
345 Note.flag |= BLOCK_FIELD_IS_WEAK;
346 } else if (T->isBlockPointerType()) {
347 Note.flag = BLOCK_FIELD_IS_BLOCK;
348 } else {
349 Note.flag = BLOCK_FIELD_IS_OBJECT;
350 }
351
352 if (LocalDeclMap[VD]) {
353 if (BDRE->isByRef()) {
354 llvm::Value *Loc = LocalDeclMap[VD];
355 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
356 Loc = Builder.CreateLoad(Loc);
357 Builder.CreateStore(Loc, Addr);
358 continue;
359 } else {
360 E = new (getContext()) DeclRefExpr(const_cast<ValueDecl*>(VD),
361 VD->getType(),
362 SourceLocation());
363 }
364 }
365
366 if (BDRE->isByRef()) {
367 E = new (getContext())
368 UnaryOperator(const_cast<Expr*>(E), UnaryOperator::AddrOf,
369 getContext().getPointerType(E->getType()),
370 SourceLocation());
371 }
372
373 RValue r = EmitAnyExpr(E, Addr, false);
374 if (r.isScalar()) {
375 llvm::Value *Loc = r.getScalarVal();
376 const llvm::Type *Ty = Types[i+BlockFields];
377 if (BDRE->isByRef()) {
378 // E is now the address of the value field, instead, we want the
379 // address of the actual ByRef struct. We optimize this slightly
380 // compared to gcc by not grabbing the forwarding slot as this must
381 // be done during Block_copy for us, and we can postpone the work
382 // until then.
383 CharUnits offset = BlockDecls[BDRE->getDecl()];
384
385 llvm::Value *BlockLiteral = LoadBlockStruct();
386
387 Loc = Builder.CreateGEP(BlockLiteral,
388 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
389 offset.getQuantity()),
390 "block.literal");
391 Ty = llvm::PointerType::get(Ty, 0);
392 Loc = Builder.CreateBitCast(Loc, Ty);
393 Loc = Builder.CreateLoad(Loc);
394 // Loc = Builder.CreateBitCast(Loc, Ty);
395 }
396 Builder.CreateStore(Loc, Addr);
397 } else if (r.isComplex())
398 // FIXME: implement
399 ErrorUnsupported(BE, "complex in block literal");
400 else if (r.isAggregate())
401 ; // Already created into the destination
402 else
403 assert (0 && "bad block variable");
404 // FIXME: Ensure that the offset created by the backend for
405 // the struct matches the previously computed offset in BlockDecls.
406 }
407 NoteForHelper.resize(NumHelpers);
Mike Stumpcf62d392009-03-06 18:42:23 +0000408
409 // __descriptor
Blaine Garst2a7eb282010-02-23 21:51:17 +0000410 llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE,
John McCallee504292010-05-21 04:11:14 +0000411 Info.BlockHasCopyDispose,
412 Info.BlockSize, Ty,
Mike Stump08920992009-03-07 02:35:30 +0000413 &NoteForHelper);
414 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
415 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpe5fee252009-02-13 16:19:19 +0000416 }
Mike Stump00470a12009-03-05 08:32:30 +0000417
Mike Stumpbd65cac2009-02-19 01:01:04 +0000418 QualType BPT = BE->getType();
Fariborz Jahanian263c4de2010-02-10 23:34:57 +0000419 V = Builder.CreateBitCast(V, ConvertType(BPT));
420 // See if this is a __weak block variable and the must call objc_read_weak
421 // on it.
422 const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
423 QualType RES = ftype->getResultType();
424 if (RES.isObjCGCWeak()) {
425 // Must cast argument to id*
426 const llvm::Type *ObjectPtrTy =
427 ConvertType(CGM.getContext().getObjCIdType());
428 const llvm::Type *PtrObjectPtrTy =
429 llvm::PointerType::getUnqual(ObjectPtrTy);
430 V = Builder.CreateBitCast(V, PtrObjectPtrTy);
431 V = CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
432 }
433 return V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000434}
435
436
Mike Stump2a998142009-03-04 18:17:45 +0000437const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000438 if (BlockDescriptorType)
439 return BlockDescriptorType;
440
Mike Stumpa5448542009-02-13 15:32:32 +0000441 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000442 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000443
Mike Stumpab695142009-02-13 15:16:56 +0000444 // struct __block_descriptor {
445 // unsigned long reserved;
446 // unsigned long block_size;
Blaine Garst2a7eb282010-02-23 21:51:17 +0000447 //
448 // // later, the following will be added
449 //
450 // struct {
451 // void (*copyHelper)();
452 // void (*copyHelper)();
453 // } helpers; // !!! optional
454 //
455 // const char *signature; // the block signature
456 // const char *layout; // reserved
Mike Stumpab695142009-02-13 15:16:56 +0000457 // };
Owen Anderson47a434f2009-08-05 23:18:46 +0000458 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
459 UnsignedLongTy,
Mike Stumpa5448542009-02-13 15:32:32 +0000460 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000461 NULL);
462
463 getModule().addTypeName("struct.__block_descriptor",
464 BlockDescriptorType);
465
466 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000467}
468
Mike Stump2a998142009-03-04 18:17:45 +0000469const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000470 if (GenericBlockLiteralType)
471 return GenericBlockLiteralType;
472
Mike Stumpa5448542009-02-13 15:32:32 +0000473 const llvm::Type *BlockDescPtrTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000474 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000475
Mike Stump7cbb3602009-02-13 16:01:35 +0000476 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
477 getTypes().ConvertType(getContext().IntTy));
478
Mike Stump9b8a7972009-02-13 15:25:34 +0000479 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000480 // void *__isa;
481 // int __flags;
482 // int __reserved;
483 // void (*__invoke)(void *);
484 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000485 // };
Blaine Garst2a7eb282010-02-23 21:51:17 +0000486 GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000487 PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000488 IntTy,
489 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000490 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000491 BlockDescPtrTy,
492 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000493
Mike Stump9b8a7972009-02-13 15:25:34 +0000494 getModule().addTypeName("struct.__block_literal_generic",
495 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000496
Mike Stump9b8a7972009-02-13 15:25:34 +0000497 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000498}
499
Mike Stumpbd65cac2009-02-19 01:01:04 +0000500
Anders Carlssona1736c02009-12-24 21:13:40 +0000501RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
502 ReturnValueSlot ReturnValue) {
Mike Stumpa5448542009-02-13 15:32:32 +0000503 const BlockPointerType *BPT =
Ted Kremenek6217b802009-07-29 21:53:49 +0000504 E->getCallee()->getType()->getAs<BlockPointerType>();
Mike Stumpa5448542009-02-13 15:32:32 +0000505
Anders Carlssonacfde802009-02-12 00:39:25 +0000506 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
507
508 // Get a pointer to the generic block literal.
509 const llvm::Type *BlockLiteralTy =
Owen Anderson96e0fc72009-07-29 22:16:19 +0000510 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000511
512 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000513 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000514 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
515
516 // Get the function pointer from the literal.
517 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000518
Mike Stumpa5448542009-02-13 15:32:32 +0000519 BlockLiteral =
520 Builder.CreateBitCast(BlockLiteral,
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000521 llvm::Type::getInt8PtrTy(VMContext),
Anders Carlssonacfde802009-02-12 00:39:25 +0000522 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000523
Anders Carlssonacfde802009-02-12 00:39:25 +0000524 // Add the block literal.
525 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
526 CallArgList Args;
527 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000528
Anders Carlsson782f3972009-04-08 23:13:16 +0000529 QualType FnType = BPT->getPointeeType();
530
Anders Carlssonacfde802009-02-12 00:39:25 +0000531 // And the rest of the arguments.
John McCall183700f2009-09-21 23:43:11 +0000532 EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
Anders Carlsson782f3972009-04-08 23:13:16 +0000533 E->arg_begin(), E->arg_end());
Mike Stumpa5448542009-02-13 15:32:32 +0000534
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000535 // Load the function.
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000536 llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000537
John McCall04a67a62010-02-05 21:31:56 +0000538 const FunctionType *FuncTy = FnType->getAs<FunctionType>();
539 QualType ResultType = FuncTy->getResultType();
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000540
Mike Stump1eb44332009-09-09 15:08:12 +0000541 const CGFunctionInfo &FnInfo =
Rafael Espindola264ba482010-03-30 20:24:48 +0000542 CGM.getTypes().getFunctionInfo(ResultType, Args,
543 FuncTy->getExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000545 // Cast the function pointer to the right type.
Mike Stump1eb44332009-09-09 15:08:12 +0000546 const llvm::Type *BlockFTy =
Anders Carlssona17d7cc2009-04-08 02:55:55 +0000547 CGM.getTypes().GetFunctionType(FnInfo, false);
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Owen Anderson96e0fc72009-07-29 22:16:19 +0000549 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
Anders Carlsson6e460ff2009-04-07 22:10:22 +0000550 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Anders Carlssonacfde802009-02-12 00:39:25 +0000552 // And call the block.
Anders Carlssona1736c02009-12-24 21:13:40 +0000553 return EmitCall(FnInfo, Func, ReturnValue, Args);
Anders Carlssonacfde802009-02-12 00:39:25 +0000554}
Anders Carlssond5cab542009-02-12 17:55:02 +0000555
John McCallea1471e2010-05-20 01:18:31 +0000556void CodeGenFunction::AllocateBlockCXXThisPointer(const CXXThisExpr *E) {
557 assert(BlockCXXThisOffset.isZero() && "already computed 'this' pointer");
558
559 // Figure out what the offset is.
560 QualType T = E->getType();
561 std::pair<CharUnits,CharUnits> TypeInfo = getContext().getTypeInfoInChars(T);
562 CharUnits Offset = getBlockOffset(TypeInfo.first, TypeInfo.second);
563
564 BlockCXXThisOffset = Offset;
565 BlockLayout.push_back(E);
566}
567
568void CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000569 const ValueDecl *VD = E->getDecl();
John McCallea1471e2010-05-20 01:18:31 +0000570 CharUnits &Offset = BlockDecls[VD];
Mike Stumpdab514f2009-03-04 03:23:46 +0000571
Mike Stumpdab514f2009-03-04 03:23:46 +0000572 // See if we have already allocated an offset for this variable.
John McCallea1471e2010-05-20 01:18:31 +0000573 if (!Offset.isZero())
574 return;
Mike Stumpea26cb52009-10-21 03:49:08 +0000575
576 // Don't run the expensive check, unless we have to.
Mike Stump083c25e2009-10-22 00:49:09 +0000577 if (!BlockHasCopyDispose)
578 if (E->isByRef()
579 || BlockRequiresCopying(E->getType()))
580 BlockHasCopyDispose = true;
Mike Stumpea26cb52009-10-21 03:49:08 +0000581
John McCallea1471e2010-05-20 01:18:31 +0000582 const ValueDecl *D = cast<ValueDecl>(E->getDecl());
Mike Stumpea26cb52009-10-21 03:49:08 +0000583
John McCallea1471e2010-05-20 01:18:31 +0000584 CharUnits Size;
585 CharUnits Align;
586
587 if (E->isByRef()) {
588 llvm::tie(Size,Align) =
589 getContext().getTypeInfoInChars(getContext().VoidPtrTy);
590 } else {
591 Size = getContext().getTypeSizeInChars(D->getType());
592 Align = getContext().getDeclAlign(D);
593 }
594
595 Offset = getBlockOffset(Size, Align);
596 BlockLayout.push_back(E);
Mike Stumpea26cb52009-10-21 03:49:08 +0000597}
598
John McCallee504292010-05-21 04:11:14 +0000599llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const ValueDecl *VD,
600 bool IsByRef) {
John McCallea1471e2010-05-20 01:18:31 +0000601 CharUnits offset = BlockDecls[VD];
602 assert(!offset.isZero() && "getting address of unallocated decl");
Mike Stumpdab514f2009-03-04 03:23:46 +0000603
604 llvm::Value *BlockLiteral = LoadBlockStruct();
605 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
Mike Stumpea26cb52009-10-21 03:49:08 +0000606 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Ken Dyck199c3d62010-01-11 17:06:35 +0000607 offset.getQuantity()),
Mike Stump58a85142009-03-04 22:48:06 +0000608 "block.literal");
John McCallee504292010-05-21 04:11:14 +0000609 if (IsByRef) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000610 const llvm::Type *PtrStructTy
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000611 = llvm::PointerType::get(BuildByRefType(VD), 0);
Mike Stumpa8b60c92009-03-21 21:00:35 +0000612 // The block literal will need a copy/destroy helper.
613 BlockHasCopyDispose = true;
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000614
615 const llvm::Type *Ty = PtrStructTy;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000616 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000617 V = Builder.CreateBitCast(V, Ty);
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000618 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000619 V = Builder.CreateStructGEP(V, 1, "forwarding");
Daniel Dunbar2da84ff2009-11-29 21:23:36 +0000620 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000621 V = Builder.CreateBitCast(V, PtrStructTy);
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000622 V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
623 VD->getNameAsString());
Fariborz Jahaniand33ded52010-05-04 17:59:32 +0000624 if (VD->getType()->isReferenceType())
625 V = Builder.CreateLoad(V);
Mike Stumpdab514f2009-03-04 03:23:46 +0000626 } else {
Anders Carlsson7dfa4072009-09-12 02:14:24 +0000627 const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
628
Owen Anderson96e0fc72009-07-29 22:16:19 +0000629 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000630 V = Builder.CreateBitCast(V, Ty);
631 }
632 return V;
633}
634
Mike Stump67a64482009-02-14 22:16:35 +0000635llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000636BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000637 // Generate the block descriptor.
638 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000639 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
640 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000641
Blaine Garst2a7eb282010-02-23 21:51:17 +0000642 llvm::Constant *DescriptorFields[4];
Mike Stumpa5448542009-02-13 15:32:32 +0000643
Anders Carlssond5cab542009-02-12 17:55:02 +0000644 // Reserved
Owen Andersonc9c88b42009-07-31 20:28:54 +0000645 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000646
Anders Carlssond5cab542009-02-12 17:55:02 +0000647 // Block literal size. For global blocks we just use the size of the generic
648 // block literal struct.
Ken Dyck687cc4a2010-01-26 13:48:07 +0000649 CharUnits BlockLiteralSize =
650 CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
Owen Andersona1cf15f2009-07-14 23:10:40 +0000651 DescriptorFields[1] =
Ken Dyck199c3d62010-01-11 17:06:35 +0000652 llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
Blaine Garst2a7eb282010-02-23 21:51:17 +0000653
654 // signature. non-optional ObjC-style method descriptor @encode sequence
655 std::string BlockTypeEncoding;
656 CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
Mike Stumpa5448542009-02-13 15:32:32 +0000657
Blaine Garst2a7eb282010-02-23 21:51:17 +0000658 DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
659 CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
660
661 // layout
662 DescriptorFields[3] =
663 llvm::ConstantInt::get(UnsignedLongTy,0);
664
665 // build the structure from the 4 elements
Mike Stumpa5448542009-02-13 15:32:32 +0000666 llvm::Constant *DescriptorStruct =
Blaine Garst2a7eb282010-02-23 21:51:17 +0000667 llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
Mike Stumpa5448542009-02-13 15:32:32 +0000668
Anders Carlssond5cab542009-02-12 17:55:02 +0000669 llvm::GlobalVariable *Descriptor =
Owen Anderson1c431b32009-07-08 19:05:04 +0000670 new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000671 llvm::GlobalVariable::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000672 DescriptorStruct, "__block_descriptor_global");
Mike Stumpa5448542009-02-13 15:32:32 +0000673
David Chisnall5e530af2009-11-17 19:33:30 +0000674 int FieldCount = 5;
Anders Carlssond5cab542009-02-12 17:55:02 +0000675 // Generate the constants for the block literal.
David Chisnall5e530af2009-11-17 19:33:30 +0000676
677 std::vector<llvm::Constant*> LiteralFields(FieldCount);
Mike Stumpa5448542009-02-13 15:32:32 +0000678
John McCallee504292010-05-21 04:11:14 +0000679 CGBlockInfo Info(n);
Mike Stump7f28a9c2009-03-13 23:34:28 +0000680 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000681 llvm::Function *Fn
John McCallee504292010-05-21 04:11:14 +0000682 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap);
683 assert(Info.BlockSize == BlockLiteralSize
Mike Stump4e7a1f72009-02-21 20:00:35 +0000684 && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000685
Anders Carlssond5cab542009-02-12 17:55:02 +0000686 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000687 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000688
Anders Carlssond5cab542009-02-12 17:55:02 +0000689 // Flags
Blaine Garst2a7eb282010-02-23 21:51:17 +0000690 LiteralFields[1] =
Blaine Garsta36e2232010-03-05 01:29:59 +0000691 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
Mike Stumpa5448542009-02-13 15:32:32 +0000692
Anders Carlssond5cab542009-02-12 17:55:02 +0000693 // Reserved
Owen Andersonc9c88b42009-07-31 20:28:54 +0000694 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000695
Anders Carlssond5cab542009-02-12 17:55:02 +0000696 // Function
697 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000698
Anders Carlssond5cab542009-02-12 17:55:02 +0000699 // Descriptor
700 LiteralFields[4] = Descriptor;
David Chisnall5e530af2009-11-17 19:33:30 +0000701
Mike Stumpa5448542009-02-13 15:32:32 +0000702 llvm::Constant *BlockLiteralStruct =
David Chisnall5e530af2009-11-17 19:33:30 +0000703 llvm::ConstantStruct::get(VMContext, LiteralFields, false);
Mike Stumpa5448542009-02-13 15:32:32 +0000704
705 llvm::GlobalVariable *BlockLiteral =
Owen Anderson1c431b32009-07-08 19:05:04 +0000706 new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000707 llvm::GlobalVariable::InternalLinkage,
Owen Anderson1c431b32009-07-08 19:05:04 +0000708 BlockLiteralStruct, "__block_literal_global");
Mike Stumpa5448542009-02-13 15:32:32 +0000709
Anders Carlssond5cab542009-02-12 17:55:02 +0000710 return BlockLiteral;
711}
712
Mike Stump4e7a1f72009-02-21 20:00:35 +0000713llvm::Value *CodeGenFunction::LoadBlockStruct() {
Mike Stumpbf1914b2009-10-20 20:30:01 +0000714 llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
715 "self");
716 // For now, we codegen based upon byte offsets.
717 return Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000718}
719
Mike Stump00470a12009-03-05 08:32:30 +0000720llvm::Function *
721CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
John McCallee504292010-05-21 04:11:14 +0000722 CGBlockInfo &Info,
Mike Stump6cc88f72009-03-20 21:53:12 +0000723 const Decl *OuterFuncDecl,
John McCallee504292010-05-21 04:11:14 +0000724 llvm::DenseMap<const Decl*, llvm::Value*> ldm) {
Devang Patel963dfbd2009-04-15 21:51:44 +0000725
726 // Check if we should generate debug info for this block.
727 if (CGM.getDebugInfo())
728 DebugInfo = CGM.getDebugInfo();
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Mike Stump7f28a9c2009-03-13 23:34:28 +0000730 // Arrange for local static and local extern declarations to appear
731 // to be local to this function as well, as they are directly referenced
732 // in a block.
733 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
734 i != ldm.end();
735 ++i) {
736 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Daniel Dunbar5466c7b2009-04-14 02:25:56 +0000738 if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
Mike Stump7f28a9c2009-03-13 23:34:28 +0000739 LocalDeclMap[VD] = i->second;
740 }
741
Ken Dyck687cc4a2010-01-26 13:48:07 +0000742 BlockOffset =
743 CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
Ken Dyck30a8a272010-01-26 19:13:33 +0000744 BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
Eli Friedman48f91222009-03-28 03:24:54 +0000745
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000746 const FunctionType *BlockFunctionType = BExpr->getFunctionType();
747 QualType ResultType;
Rafael Espindola264ba482010-03-30 20:24:48 +0000748 FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000749 bool IsVariadic;
Mike Stump1eb44332009-09-09 15:08:12 +0000750 if (const FunctionProtoType *FTy =
Fariborz Jahanianda0895d2009-04-11 18:54:57 +0000751 dyn_cast<FunctionProtoType>(BlockFunctionType)) {
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000752 ResultType = FTy->getResultType();
753 IsVariadic = FTy->isVariadic();
Mike Stumpb3589f42009-07-30 22:28:39 +0000754 } else {
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000755 // K&R style block.
756 ResultType = BlockFunctionType->getResultType();
757 IsVariadic = false;
758 }
Mike Stumpa5448542009-02-13 15:32:32 +0000759
Anders Carlssond5cab542009-02-12 17:55:02 +0000760 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000761
Mike Stumpea26cb52009-10-21 03:49:08 +0000762 CurFuncDecl = OuterFuncDecl;
763
Chris Lattner161d36d2009-02-28 19:01:03 +0000764 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000765
Mike Stumpea26cb52009-10-21 03:49:08 +0000766 IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
Mike Stumpadaaad32009-10-20 02:12:22 +0000767
John McCallea1471e2010-05-20 01:18:31 +0000768 // Build the block struct now.
John McCallee504292010-05-21 04:11:14 +0000769 AllocateAllBlockDeclRefs(*this, Info);
Mike Stumpea26cb52009-10-21 03:49:08 +0000770
Mike Stump083c25e2009-10-22 00:49:09 +0000771 QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
John McCallea1471e2010-05-20 01:18:31 +0000772 BlockLayout);
773
Anders Carlssond5cab542009-02-12 17:55:02 +0000774 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000775 ImplicitParamDecl *SelfDecl =
John McCall2888b652010-04-30 21:35:41 +0000776 ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
Mike Stumpadaaad32009-10-20 02:12:22 +0000777 SourceLocation(), II,
778 ParmTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000779
Anders Carlssond5cab542009-02-12 17:55:02 +0000780 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000781 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000782
Steve Naroffe78b8092009-03-13 16:56:44 +0000783 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000784 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000785 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000786
787 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +0000788 CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
Anders Carlssond5cab542009-02-12 17:55:02 +0000789
Anders Carlssond5cab542009-02-12 17:55:02 +0000790 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian140fb262009-04-11 17:55:15 +0000791 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
Mike Stumpa5448542009-02-13 15:32:32 +0000792
793 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000794 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000795 llvm::Twine("__") + Info.Name + "_block_invoke_",
Anders Carlssond5cab542009-02-12 17:55:02 +0000796 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000797
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000798 CGM.SetInternalFunctionAttributes(BD, Fn, FI);
799
Chris Lattner4863db42009-04-23 07:18:56 +0000800 StartFunction(BD, ResultType, Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000801 BExpr->getBody()->getLocEnd());
Mike Stumpb1a6e682009-09-30 02:43:10 +0000802
Chris Lattner4863db42009-04-23 07:18:56 +0000803 CurFuncDecl = OuterFuncDecl;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000804 CurCodeDecl = BD;
Mike Stumpb289b3f2009-10-01 22:29:41 +0000805
John McCallea1471e2010-05-20 01:18:31 +0000806 // If we have a C++ 'this' reference, go ahead and force it into
807 // existence now.
808 if (Info.CXXThisRef) {
809 assert(!BlockCXXThisOffset.isZero() &&
810 "haven't yet allocated 'this' reference");
811
812 // TODO: I have a dream that one day this will be typed.
813 llvm::Value *BlockLiteral = LoadBlockStruct();
814 llvm::Value *ThisPtrRaw =
815 Builder.CreateConstInBoundsGEP1_64(BlockLiteral,
816 BlockCXXThisOffset.getQuantity(),
817 "this.ptr.raw");
818
819 const llvm::Type *Ty =
820 CGM.getTypes().ConvertType(Info.CXXThisRef->getType());
821 Ty = llvm::PointerType::get(Ty, 0);
822 llvm::Value *ThisPtr = Builder.CreateBitCast(ThisPtrRaw, Ty, "this.ptr");
823
824 CXXThisValue = Builder.CreateLoad(ThisPtr, "this");
825 }
826
John McCallee504292010-05-21 04:11:14 +0000827 // If we have an Objective C 'self' reference, go ahead and force it
828 // into existence now.
829 if (Info.NeedsObjCSelf) {
830 ValueDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
831 LocalDeclMap[Self] = GetAddrOfBlockDecl(Self, false);
832 }
833
Mike Stumpb289b3f2009-10-01 22:29:41 +0000834 // Save a spot to insert the debug information for all the BlockDeclRefDecls.
835 llvm::BasicBlock *entry = Builder.GetInsertBlock();
836 llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
837 --entry_ptr;
838
Chris Lattner161d36d2009-02-28 19:01:03 +0000839 EmitStmt(BExpr->getBody());
Mike Stumpb289b3f2009-10-01 22:29:41 +0000840
Mike Stumpde8c5c72009-10-01 00:27:30 +0000841 // Remember where we were...
842 llvm::BasicBlock *resume = Builder.GetInsertBlock();
Mike Stumpb289b3f2009-10-01 22:29:41 +0000843
Mike Stumpde8c5c72009-10-01 00:27:30 +0000844 // Go back to the entry.
Mike Stumpb289b3f2009-10-01 22:29:41 +0000845 ++entry_ptr;
846 Builder.SetInsertPoint(entry, entry_ptr);
847
Mike Stumpb1a6e682009-09-30 02:43:10 +0000848 if (CGDebugInfo *DI = getDebugInfo()) {
Mike Stumpb1a6e682009-09-30 02:43:10 +0000849 // Emit debug information for all the BlockDeclRefDecls.
John McCallea1471e2010-05-20 01:18:31 +0000850 // FIXME: also for 'this'
851 for (unsigned i = 0, e = BlockLayout.size(); i != e; ++i) {
852 if (const BlockDeclRefExpr *BDRE =
853 dyn_cast<BlockDeclRefExpr>(BlockLayout[i])) {
Mike Stumpb1a6e682009-09-30 02:43:10 +0000854 const ValueDecl *D = BDRE->getDecl();
855 DI->setLocation(D->getLocation());
856 DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
857 LocalDeclMap[getBlockStructDecl()],
858 Builder, this);
859 }
860 }
Mike Stumpb1a6e682009-09-30 02:43:10 +0000861 }
Mike Stumpde8c5c72009-10-01 00:27:30 +0000862 // And resume where we left off.
863 if (resume == 0)
864 Builder.ClearInsertionPoint();
865 else
866 Builder.SetInsertPoint(resume);
Mike Stumpb1a6e682009-09-30 02:43:10 +0000867
Chris Lattner161d36d2009-02-28 19:01:03 +0000868 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000869
Mike Stump8a2b4b12009-02-25 23:33:13 +0000870 // The runtime needs a minimum alignment of a void *.
Ken Dyck30a8a272010-01-26 19:13:33 +0000871 CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
Ken Dyck199c3d62010-01-11 17:06:35 +0000872 BlockOffset = CharUnits::fromQuantity(
Ken Dyck30a8a272010-01-26 19:13:33 +0000873 llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
874 MinAlign.getQuantity()));
Mike Stump8a2b4b12009-02-25 23:33:13 +0000875
John McCallee504292010-05-21 04:11:14 +0000876 Info.BlockSize = BlockOffset;
877 Info.BlockAlign = BlockAlign;
878 Info.BlockLayout = BlockLayout;
879 Info.BlockHasCopyDispose = BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000880 return Fn;
881}
Mike Stumpa99038c2009-02-28 09:07:16 +0000882
John McCallea1471e2010-05-20 01:18:31 +0000883CharUnits BlockFunction::getBlockOffset(CharUnits Size, CharUnits Align) {
884 assert((Align.isPositive()) && "alignment must be 1 byte or more");
Mike Stumpa99038c2009-02-28 09:07:16 +0000885
Ken Dyck199c3d62010-01-11 17:06:35 +0000886 CharUnits OldOffset = BlockOffset;
Mike Stumpa99038c2009-02-28 09:07:16 +0000887
888 // Ensure proper alignment, even if it means we have to have a gap
Ken Dyck199c3d62010-01-11 17:06:35 +0000889 BlockOffset = CharUnits::fromQuantity(
Ken Dyck30a8a272010-01-26 19:13:33 +0000890 llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
Mike Stumpa99038c2009-02-28 09:07:16 +0000891 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000892
Ken Dyck199c3d62010-01-11 17:06:35 +0000893 CharUnits Pad = BlockOffset - OldOffset;
894 if (Pad.isPositive()) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000895 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
Ken Dyck199c3d62010-01-11 17:06:35 +0000896 llvm::APInt(32,
897 Pad.getQuantity()),
Mike Stumpa99038c2009-02-28 09:07:16 +0000898 ArrayType::Normal, 0);
Douglas Gregorba55ec22010-05-11 18:17:16 +0000899 ValueDecl *PadDecl = VarDecl::Create(getContext(),
900 getContext().getTranslationUnitDecl(),
901 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +0000902 0, QualType(PadTy), 0,
903 VarDecl::None, VarDecl::None);
John McCallea1471e2010-05-20 01:18:31 +0000904 Expr *E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
905 SourceLocation());
906 BlockLayout.push_back(E);
Mike Stumpa99038c2009-02-28 09:07:16 +0000907 }
Mike Stumpa99038c2009-02-28 09:07:16 +0000908
909 BlockOffset += Size;
John McCallea1471e2010-05-20 01:18:31 +0000910 return BlockOffset - Size;
Mike Stumpa99038c2009-02-28 09:07:16 +0000911}
Mike Stumpdab514f2009-03-04 03:23:46 +0000912
Mike Stump08920992009-03-07 02:35:30 +0000913llvm::Constant *BlockFunction::
914GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +0000915 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000916 QualType R = getContext().VoidTy;
917
918 FunctionArgList Args;
919 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000920 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +0000921 ImplicitParamDecl::Create(getContext(), 0,
922 SourceLocation(), 0,
Mike Stump08920992009-03-07 02:35:30 +0000923 getContext().getPointerType(getContext().VoidTy));
924 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000925 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +0000926 ImplicitParamDecl::Create(getContext(), 0,
927 SourceLocation(), 0,
Mike Stumpa4f668f2009-03-06 01:33:24 +0000928 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000929 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Mike Stumpa4f668f2009-03-06 01:33:24 +0000931 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +0000932 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +0000933
Mike Stump3899a7f2009-06-05 23:26:36 +0000934 // FIXME: We'd like to put these into a mergable by content, with
935 // internal linkage.
Mike Stumpa4f668f2009-03-06 01:33:24 +0000936 CodeGenTypes &Types = CGM.getTypes();
937 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
938
939 llvm::Function *Fn =
940 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +0000941 "__copy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +0000942
943 IdentifierInfo *II
944 = &CGM.getContext().Idents.get("__copy_helper_block_");
945
946 FunctionDecl *FD = FunctionDecl::Create(getContext(),
947 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000948 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000949 FunctionDecl::Static,
950 FunctionDecl::None,
951 false,
Mike Stumpa4f668f2009-03-06 01:33:24 +0000952 true);
953 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000954
955 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
956 llvm::Type *PtrPtrT;
Mike Stump08920992009-03-07 02:35:30 +0000957
Mike Stumpb7477cf2009-04-10 18:52:28 +0000958 if (NoteForHelperp) {
959 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump08920992009-03-07 02:35:30 +0000960
Owen Anderson96e0fc72009-07-29 22:16:19 +0000961 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpb7477cf2009-04-10 18:52:28 +0000962 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
963 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump08920992009-03-07 02:35:30 +0000964
Mike Stumpb7477cf2009-04-10 18:52:28 +0000965 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
Mike Stumpc2f4c342009-04-15 22:11:36 +0000966 llvm::Type *PtrPtrT;
Owen Anderson96e0fc72009-07-29 22:16:19 +0000967 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpc2f4c342009-04-15 22:11:36 +0000968 DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
969 DstObj = Builder.CreateLoad(DstObj);
Mike Stump08920992009-03-07 02:35:30 +0000970
Mike Stumpb7477cf2009-04-10 18:52:28 +0000971 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
972 int flag = NoteForHelper[i].flag;
973 int index = NoteForHelper[i].index;
Mike Stump08920992009-03-07 02:35:30 +0000974
Mike Stumpb7477cf2009-04-10 18:52:28 +0000975 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
976 || NoteForHelper[i].RequiresCopying) {
977 llvm::Value *Srcv = SrcObj;
978 Srcv = Builder.CreateStructGEP(Srcv, index);
979 Srcv = Builder.CreateBitCast(Srcv,
Owen Anderson96e0fc72009-07-29 22:16:19 +0000980 llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpb7477cf2009-04-10 18:52:28 +0000981 Srcv = Builder.CreateLoad(Srcv);
982
983 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
984 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
985
Owen Anderson0032b272009-08-13 21:57:51 +0000986 llvm::Value *N = llvm::ConstantInt::get(
987 llvm::Type::getInt32Ty(T->getContext()), flag);
Mike Stumpb7477cf2009-04-10 18:52:28 +0000988 llvm::Value *F = getBlockObjectAssign();
989 Builder.CreateCall3(F, Dstv, Srcv, N);
990 }
Mike Stump08920992009-03-07 02:35:30 +0000991 }
992 }
993
Mike Stumpa4f668f2009-03-06 01:33:24 +0000994 CGF.FinishFunction();
995
Owen Anderson3c4972d2009-07-29 18:54:39 +0000996 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000997}
998
Mike Stumpcf62d392009-03-06 18:42:23 +0000999llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +00001000GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
1001 const llvm::StructType* T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001002 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpa4f668f2009-03-06 01:33:24 +00001003 QualType R = getContext().VoidTy;
1004
1005 FunctionArgList Args;
1006 // FIXME: This leaks
1007 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001008 ImplicitParamDecl::Create(getContext(), 0,
1009 SourceLocation(), 0,
Mike Stumpa4f668f2009-03-06 01:33:24 +00001010 getContext().getPointerType(getContext().VoidTy));
1011
1012 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Mike Stumpa4f668f2009-03-06 01:33:24 +00001014 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001015 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001016
Mike Stump3899a7f2009-06-05 23:26:36 +00001017 // FIXME: We'd like to put these into a mergable by content, with
1018 // internal linkage.
Mike Stumpa4f668f2009-03-06 01:33:24 +00001019 CodeGenTypes &Types = CGM.getTypes();
1020 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1021
1022 llvm::Function *Fn =
1023 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001024 "__destroy_helper_block_", &CGM.getModule());
Mike Stumpa4f668f2009-03-06 01:33:24 +00001025
1026 IdentifierInfo *II
1027 = &CGM.getContext().Idents.get("__destroy_helper_block_");
1028
1029 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1030 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001031 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001032 FunctionDecl::Static,
1033 FunctionDecl::None,
1034 false, true);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001035 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +00001036
Mike Stumpb7477cf2009-04-10 18:52:28 +00001037 if (NoteForHelperp) {
1038 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump1edf6b62009-03-07 02:53:18 +00001039
Mike Stumpb7477cf2009-04-10 18:52:28 +00001040 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
1041 llvm::Type *PtrPtrT;
Owen Anderson96e0fc72009-07-29 22:16:19 +00001042 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
Mike Stumpb7477cf2009-04-10 18:52:28 +00001043 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
1044 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump1edf6b62009-03-07 02:53:18 +00001045
Mike Stumpb7477cf2009-04-10 18:52:28 +00001046 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
1047 int flag = NoteForHelper[i].flag;
1048 int index = NoteForHelper[i].index;
Mike Stump1edf6b62009-03-07 02:53:18 +00001049
Mike Stumpb7477cf2009-04-10 18:52:28 +00001050 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
1051 || NoteForHelper[i].RequiresCopying) {
1052 llvm::Value *Srcv = SrcObj;
1053 Srcv = Builder.CreateStructGEP(Srcv, index);
1054 Srcv = Builder.CreateBitCast(Srcv,
Owen Anderson96e0fc72009-07-29 22:16:19 +00001055 llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpb7477cf2009-04-10 18:52:28 +00001056 Srcv = Builder.CreateLoad(Srcv);
1057
1058 BuildBlockRelease(Srcv, flag);
1059 }
Mike Stump1edf6b62009-03-07 02:53:18 +00001060 }
1061 }
1062
Mike Stumpa4f668f2009-03-06 01:33:24 +00001063 CGF.FinishFunction();
1064
Owen Anderson3c4972d2009-07-29 18:54:39 +00001065 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001066}
1067
Mike Stump08920992009-03-07 02:35:30 +00001068llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001069 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump08920992009-03-07 02:35:30 +00001070 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1071 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +00001072}
1073
Mike Stump08920992009-03-07 02:35:30 +00001074llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001075 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stump08920992009-03-07 02:35:30 +00001076 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
Mike Stumpb7477cf2009-04-10 18:52:28 +00001077 T, NoteForHelperp);
Mike Stumpdab514f2009-03-04 03:23:46 +00001078}
Mike Stump797b6322009-03-05 01:23:13 +00001079
Mike Stumpee094222009-03-06 06:12:24 +00001080llvm::Constant *BlockFunction::
1081GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +00001082 QualType R = getContext().VoidTy;
1083
1084 FunctionArgList Args;
1085 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +00001086 ImplicitParamDecl *Dst =
Mike Stumpea26cb52009-10-21 03:49:08 +00001087 ImplicitParamDecl::Create(getContext(), 0,
1088 SourceLocation(), 0,
Mike Stumpee094222009-03-06 06:12:24 +00001089 getContext().getPointerType(getContext().VoidTy));
1090 Args.push_back(std::make_pair(Dst, Dst->getType()));
1091
1092 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +00001093 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001094 ImplicitParamDecl::Create(getContext(), 0,
1095 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001096 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +00001097 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Mike Stump45031c02009-03-06 02:29:21 +00001099 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001100 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001101
Mike Stump45031c02009-03-06 02:29:21 +00001102 CodeGenTypes &Types = CGM.getTypes();
1103 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1104
Mike Stump3899a7f2009-06-05 23:26:36 +00001105 // FIXME: We'd like to put these into a mergable by content, with
1106 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001107 llvm::Function *Fn =
1108 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001109 "__Block_byref_id_object_copy_", &CGM.getModule());
Mike Stump45031c02009-03-06 02:29:21 +00001110
1111 IdentifierInfo *II
1112 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1113
1114 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1115 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001116 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001117 FunctionDecl::Static,
1118 FunctionDecl::None,
1119 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001120 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +00001121
1122 // dst->x
1123 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001124 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001125 V = Builder.CreateLoad(V);
Mike Stumpee094222009-03-06 06:12:24 +00001126 V = Builder.CreateStructGEP(V, 6, "x");
1127 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1128
1129 // src->x
1130 V = CGF.GetAddrOfLocalVar(Src);
1131 V = Builder.CreateLoad(V);
1132 V = Builder.CreateBitCast(V, T);
1133 V = Builder.CreateStructGEP(V, 6, "x");
Owen Anderson96e0fc72009-07-29 22:16:19 +00001134 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpee094222009-03-06 06:12:24 +00001135 llvm::Value *SrcObj = Builder.CreateLoad(V);
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Mike Stumpee094222009-03-06 06:12:24 +00001137 flag |= BLOCK_BYREF_CALLER;
1138
Owen Anderson0032b272009-08-13 21:57:51 +00001139 llvm::Value *N = llvm::ConstantInt::get(
1140 llvm::Type::getInt32Ty(T->getContext()), flag);
Mike Stumpee094222009-03-06 06:12:24 +00001141 llvm::Value *F = getBlockObjectAssign();
1142 Builder.CreateCall3(F, DstObj, SrcObj, N);
1143
Mike Stump45031c02009-03-06 02:29:21 +00001144 CGF.FinishFunction();
1145
Owen Anderson3c4972d2009-07-29 18:54:39 +00001146 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001147}
1148
Mike Stump1851b682009-03-06 04:53:30 +00001149llvm::Constant *
1150BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1151 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +00001152 QualType R = getContext().VoidTy;
1153
1154 FunctionArgList Args;
1155 // FIXME: This leaks
1156 ImplicitParamDecl *Src =
Mike Stumpea26cb52009-10-21 03:49:08 +00001157 ImplicitParamDecl::Create(getContext(), 0,
1158 SourceLocation(), 0,
Mike Stump45031c02009-03-06 02:29:21 +00001159 getContext().getPointerType(getContext().VoidTy));
1160
1161 Args.push_back(std::make_pair(Src, Src->getType()));
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Mike Stump45031c02009-03-06 02:29:21 +00001163 const CGFunctionInfo &FI =
Rafael Espindola264ba482010-03-30 20:24:48 +00001164 CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
Mike Stump45031c02009-03-06 02:29:21 +00001165
Mike Stump45031c02009-03-06 02:29:21 +00001166 CodeGenTypes &Types = CGM.getTypes();
1167 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1168
Mike Stump3899a7f2009-06-05 23:26:36 +00001169 // FIXME: We'd like to put these into a mergable by content, with
1170 // internal linkage.
Mike Stump45031c02009-03-06 02:29:21 +00001171 llvm::Function *Fn =
1172 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Benjamin Kramer3cf7c5d2010-01-22 13:59:13 +00001173 "__Block_byref_id_object_dispose_",
Mike Stump45031c02009-03-06 02:29:21 +00001174 &CGM.getModule());
1175
1176 IdentifierInfo *II
1177 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1178
1179 FunctionDecl *FD = FunctionDecl::Create(getContext(),
1180 getContext().getTranslationUnitDecl(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001181 SourceLocation(), II, R, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001182 FunctionDecl::Static,
1183 FunctionDecl::None,
1184 false, true);
Mike Stump45031c02009-03-06 02:29:21 +00001185 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +00001186
1187 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
Owen Anderson96e0fc72009-07-29 22:16:19 +00001188 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001189 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001190 V = Builder.CreateStructGEP(V, 6, "x");
Owen Anderson96e0fc72009-07-29 22:16:19 +00001191 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
Mike Stumpc2f4c342009-04-15 22:11:36 +00001192 V = Builder.CreateLoad(V);
Mike Stump1851b682009-03-06 04:53:30 +00001193
Mike Stump1851b682009-03-06 04:53:30 +00001194 flag |= BLOCK_BYREF_CALLER;
1195 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +00001196 CGF.FinishFunction();
1197
Owen Anderson3c4972d2009-07-29 18:54:39 +00001198 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stump45031c02009-03-06 02:29:21 +00001199}
1200
Mike Stumpee094222009-03-06 06:12:24 +00001201llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
Chris Lattner10976d92009-12-05 08:21:30 +00001202 int Flag, unsigned Align) {
1203 // All alignments below that of pointer alignment collapse down to just
Mike Stump3899a7f2009-06-05 23:26:36 +00001204 // pointer alignment, as we always have at least that much alignment to begin
1205 // with.
1206 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001207
Mike Stump3899a7f2009-06-05 23:26:36 +00001208 // As an optimization, we only generate a single function of each kind we
1209 // might need. We need a different one for each alignment and for each
1210 // setting of flags. We mix Align and flag to get the kind.
Chris Lattner10976d92009-12-05 08:21:30 +00001211 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1212 llvm::Constant *&Entry = CGM.AssignCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001213 if (Entry)
1214 return Entry;
Chris Lattner10976d92009-12-05 08:21:30 +00001215 return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
Mike Stump45031c02009-03-06 02:29:21 +00001216}
1217
Mike Stump1851b682009-03-06 04:53:30 +00001218llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
Chris Lattner10976d92009-12-05 08:21:30 +00001219 int Flag,
Mike Stump3899a7f2009-06-05 23:26:36 +00001220 unsigned Align) {
1221 // All alignments below that of pointer alignment collpase down to just
1222 // pointer alignment, as we always have at least that much alignment to begin
1223 // with.
1224 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
Chris Lattner10976d92009-12-05 08:21:30 +00001225
Mike Stump3899a7f2009-06-05 23:26:36 +00001226 // As an optimization, we only generate a single function of each kind we
1227 // might need. We need a different one for each alignment and for each
1228 // setting of flags. We mix Align and flag to get the kind.
Chris Lattner10976d92009-12-05 08:21:30 +00001229 uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1230 llvm::Constant *&Entry = CGM.DestroyCache[Kind];
Mike Stump3899a7f2009-06-05 23:26:36 +00001231 if (Entry)
1232 return Entry;
Chris Lattner10976d92009-12-05 08:21:30 +00001233 return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
Mike Stump45031c02009-03-06 02:29:21 +00001234}
1235
Mike Stump797b6322009-03-05 01:23:13 +00001236llvm::Value *BlockFunction::getBlockObjectDispose() {
1237 if (CGM.BlockObjectDispose == 0) {
1238 const llvm::FunctionType *FTy;
1239 std::vector<const llvm::Type*> ArgTys;
Owen Anderson0032b272009-08-13 21:57:51 +00001240 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
Mike Stump797b6322009-03-05 01:23:13 +00001241 ArgTys.push_back(PtrToInt8Ty);
Owen Anderson0032b272009-08-13 21:57:51 +00001242 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
Owen Anderson96e0fc72009-07-29 22:16:19 +00001243 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump00470a12009-03-05 08:32:30 +00001244 CGM.BlockObjectDispose
Mike Stump797b6322009-03-05 01:23:13 +00001245 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1246 }
1247 return CGM.BlockObjectDispose;
1248}
1249
Mike Stumpee094222009-03-06 06:12:24 +00001250llvm::Value *BlockFunction::getBlockObjectAssign() {
1251 if (CGM.BlockObjectAssign == 0) {
1252 const llvm::FunctionType *FTy;
1253 std::vector<const llvm::Type*> ArgTys;
Owen Anderson0032b272009-08-13 21:57:51 +00001254 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
Mike Stumpee094222009-03-06 06:12:24 +00001255 ArgTys.push_back(PtrToInt8Ty);
1256 ArgTys.push_back(PtrToInt8Ty);
Owen Anderson0032b272009-08-13 21:57:51 +00001257 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
Owen Anderson96e0fc72009-07-29 22:16:19 +00001258 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stumpee094222009-03-06 06:12:24 +00001259 CGM.BlockObjectAssign
1260 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1261 }
1262 return CGM.BlockObjectAssign;
1263}
1264
Mike Stump1851b682009-03-06 04:53:30 +00001265void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump797b6322009-03-05 01:23:13 +00001266 llvm::Value *F = getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001267 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001268 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Owen Anderson0032b272009-08-13 21:57:51 +00001269 N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
Mike Stump797b6322009-03-05 01:23:13 +00001270 Builder.CreateCall2(F, V, N);
1271}
Mike Stump00470a12009-03-05 08:32:30 +00001272
1273ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001274
1275BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1276 CGBuilderTy &B)
Owen Andersona1cf15f2009-07-14 23:10:40 +00001277 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
Owen Anderson0032b272009-08-13 21:57:51 +00001278 PtrToInt8Ty = llvm::PointerType::getUnqual(
1279 llvm::Type::getInt8Ty(VMContext));
Mike Stump08920992009-03-07 02:35:30 +00001280
1281 BlockHasCopyDispose = false;
1282}