blob: 8de3518406d26e2b7935937ccaf55d3abbe11892 [file] [log] [blame]
Anders Carlssond2a889b2009-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
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Mike Stumpfc5e6de2009-03-20 21:53:12 +000016#include "clang/AST/DeclObjC.h"
Anders Carlssond2a889b2009-02-12 00:39:25 +000017#include "llvm/Module.h"
Anders Carlsson1f1cd392009-02-12 17:55:02 +000018#include "llvm/Target/TargetData.h"
Anders Carlssond2a889b2009-02-12 00:39:25 +000019#include <algorithm>
Anders Carlssond2a889b2009-02-12 00:39:25 +000020using namespace clang;
21using namespace CodeGen;
22
Mike Stump9d8c1262009-03-06 18:42:23 +000023llvm::Constant *CodeGenFunction::
Mike Stump68bb7a22009-03-25 17:58:24 +000024BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size,
25 const llvm::StructType* Ty,
Mike Stump1fa52fe2009-03-07 02:35:30 +000026 std::vector<HelperInfo> *NoteForHelper) {
Mike Stumpff8f0872009-02-13 16:55:51 +000027 const llvm::Type *UnsignedLongTy
28 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb95bc002009-02-13 16:19:19 +000029 llvm::Constant *C;
30 std::vector<llvm::Constant*> Elts;
31
32 // reserved
Mike Stumpff8f0872009-02-13 16:55:51 +000033 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpb95bc002009-02-13 16:19:19 +000034 Elts.push_back(C);
35
36 // Size
Mike Stump139c3962009-02-21 20:07:44 +000037 // FIXME: What is the right way to say this doesn't fit? We should give
38 // a user diagnostic in that case. Better fix would be to change the
39 // API to size_t.
Mike Stumpfca5da02009-02-21 20:00:35 +000040 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpb95bc002009-02-13 16:19:19 +000041 Elts.push_back(C);
42
43 if (BlockHasCopyDispose) {
44 // copy_func_helper_decl
Mike Stump2f9a4262009-04-10 18:52:28 +000045 Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
Mike Stumpb95bc002009-02-13 16:19:19 +000046
47 // destroy_func_decl
Mike Stump2f9a4262009-04-10 18:52:28 +000048 Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
Mike Stumpb95bc002009-02-13 16:19:19 +000049 }
50
51 C = llvm::ConstantStruct::get(Elts);
52
Owen Anderson96bcdd42009-07-08 01:29:18 +000053 C = new llvm::GlobalVariable(CGM.getModule().getContext(), C->getType(), true,
Mike Stumpb95bc002009-02-13 16:19:19 +000054 llvm::GlobalValue::InternalLinkage,
Mike Stump92ea8882009-02-13 20:17:16 +000055 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpb95bc002009-02-13 16:19:19 +000056 return C;
57}
58
Mike Stump1f010b52009-03-04 18:17:45 +000059llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Chris Lattner98a87992009-05-13 02:50:56 +000060 if (NSConcreteGlobalBlock == 0)
61 NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
62 "_NSConcreteGlobalBlock");
Mike Stump5f87e9d2009-02-13 17:23:42 +000063 return NSConcreteGlobalBlock;
64}
65
Mike Stump1f010b52009-03-04 18:17:45 +000066llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Chris Lattner98a87992009-05-13 02:50:56 +000067 if (NSConcreteStackBlock == 0)
68 NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
69 "_NSConcreteStackBlock");
Mike Stumpeb3a5ca2009-02-13 19:29:27 +000070 return NSConcreteStackBlock;
71}
72
Mike Stump1bdbf632009-03-05 08:32:30 +000073static void CollectBlockDeclRefInfo(const Stmt *S,
Anders Carlsson6cf64be2009-03-01 01:09:12 +000074 CodeGenFunction::BlockInfo &Info) {
75 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
76 I != E; ++I)
Daniel Dunbar56941d32009-03-02 07:00:57 +000077 if (*I)
78 CollectBlockDeclRefInfo(*I, Info);
Mike Stump1bdbf632009-03-05 08:32:30 +000079
Anders Carlsson6cf64be2009-03-01 01:09:12 +000080 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
81 // FIXME: Handle enums.
82 if (isa<FunctionDecl>(DE->getDecl()))
83 return;
Mike Stump1bdbf632009-03-05 08:32:30 +000084
Anders Carlsson6cf64be2009-03-01 01:09:12 +000085 if (DE->isByRef())
86 Info.ByRefDeclRefs.push_back(DE);
87 else
88 Info.ByCopyDeclRefs.push_back(DE);
89 }
90}
91
Mike Stumpf13eac12009-03-04 22:48:06 +000092/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
93/// declared as a global variable instead of on the stack.
Chris Lattner98a87992009-05-13 02:50:56 +000094static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
Anders Carlsson6cf64be2009-03-01 01:09:12 +000095 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
96}
97
Mike Stumpf13eac12009-03-04 22:48:06 +000098// FIXME: Push most into CGM, passing down a few bits, like current function
99// name.
Mike Stumpf1711822009-02-25 23:33:13 +0000100llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpb95bc002009-02-13 16:19:19 +0000101
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000102 std::string Name = CurFn->getName();
103 CodeGenFunction::BlockInfo Info(0, Name.c_str());
104 CollectBlockDeclRefInfo(BE->getBody(), Info);
105
106 // Check if the block can be global.
Mike Stumpf13eac12009-03-04 22:48:06 +0000107 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
108 // to just have one code path. We should move this function into CGM and pass
109 // CGF, then we can just check to see if CGF is 0.
Mike Stumpad9605d2009-03-04 03:23:46 +0000110 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson6cf64be2009-03-01 01:09:12 +0000111 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump1bdbf632009-03-05 08:32:30 +0000112
113 std::vector<llvm::Constant*> Elts(5);
Mike Stumpb95bc002009-02-13 16:19:19 +0000114 llvm::Constant *C;
Mike Stumpf1711822009-02-25 23:33:13 +0000115 llvm::Value *V;
Mike Stumpb95bc002009-02-13 16:19:19 +0000116
Mike Stumpb95bc002009-02-13 16:19:19 +0000117 {
118 // C = BuildBlockStructInitlist();
119 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
120
Mike Stump1bdbf632009-03-05 08:32:30 +0000121 // We run this first so that we set BlockHasCopyDispose from the entire
122 // block literal.
123 // __invoke
124 uint64_t subBlockSize, subBlockAlign;
125 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stump68bb7a22009-03-25 17:58:24 +0000126 bool subBlockHasCopyDispose = false;
Mike Stump1bdbf632009-03-05 08:32:30 +0000127 llvm::Function *Fn
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000128 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl, LocalDeclMap,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000129 subBlockSize,
Mike Stump1bdbf632009-03-05 08:32:30 +0000130 subBlockAlign,
131 subBlockDeclRefDecls,
Mike Stump68bb7a22009-03-25 17:58:24 +0000132 subBlockHasCopyDispose);
133 BlockHasCopyDispose |= subBlockHasCopyDispose;
Mike Stump1bdbf632009-03-05 08:32:30 +0000134 Elts[3] = Fn;
135
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000136 // FIXME: Don't use BlockHasCopyDispose, it is set more often then
137 // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
Mike Stump68bb7a22009-03-25 17:58:24 +0000138 if (subBlockHasCopyDispose)
Mike Stumpb95bc002009-02-13 16:19:19 +0000139 flags |= BLOCK_HAS_COPY_DISPOSE;
140
Mike Stump92ea8882009-02-13 20:17:16 +0000141 // __isa
Mike Stumpeb3a5ca2009-02-13 19:29:27 +0000142 C = CGM.getNSConcreteStackBlock();
Mike Stumpb95bc002009-02-13 16:19:19 +0000143 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump1bdbf632009-03-05 08:32:30 +0000144 Elts[0] = C;
Mike Stumpb95bc002009-02-13 16:19:19 +0000145
146 // __flags
147 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
148 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
149 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump1bdbf632009-03-05 08:32:30 +0000150 Elts[1] = C;
Mike Stumpb95bc002009-02-13 16:19:19 +0000151
152 // __reserved
153 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump1bdbf632009-03-05 08:32:30 +0000154 Elts[2] = C;
Mike Stumpb95bc002009-02-13 16:19:19 +0000155
Mike Stumpf1711822009-02-25 23:33:13 +0000156 if (subBlockDeclRefDecls.size() == 0) {
Mike Stump9d8c1262009-03-06 18:42:23 +0000157 // __descriptor
Mike Stump68bb7a22009-03-25 17:58:24 +0000158 Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize, 0, 0);
Mike Stump9d8c1262009-03-06 18:42:23 +0000159
Mike Stumpa7db9be2009-03-01 20:07:53 +0000160 // Optimize to being a global block.
161 Elts[0] = CGM.getNSConcreteGlobalBlock();
162 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
163
Mike Stumpf1711822009-02-25 23:33:13 +0000164 C = llvm::ConstantStruct::get(Elts);
165
166 char Name[32];
167 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
Owen Anderson96bcdd42009-07-08 01:29:18 +0000168 C = new llvm::GlobalVariable(CGM.getModule().getContext(),
169 C->getType(), true,
Mike Stumpf1711822009-02-25 23:33:13 +0000170 llvm::GlobalValue::InternalLinkage,
171 C, Name, &CGM.getModule());
172 QualType BPT = BE->getType();
173 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
174 return C;
175 }
Mike Stump1bdbf632009-03-05 08:32:30 +0000176
Mike Stumpf1711822009-02-25 23:33:13 +0000177 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
Mike Stump1fa52fe2009-03-07 02:35:30 +0000178 for (int i=0; i<4; ++i)
Mike Stumpf1711822009-02-25 23:33:13 +0000179 Types[i] = Elts[i]->getType();
Mike Stump1fa52fe2009-03-07 02:35:30 +0000180 Types[4] = PtrToInt8Ty;
Mike Stumpf1711822009-02-25 23:33:13 +0000181
Mike Stump2b6933f2009-02-28 09:07:16 +0000182 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
183 const Expr *E = subBlockDeclRefDecls[i];
184 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
185 QualType Ty = E->getType();
Mike Stumpad9605d2009-03-04 03:23:46 +0000186 if (BDRE && BDRE->isByRef()) {
187 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
188 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
189 } else
190 Types[i+5] = ConvertType(Ty);
Mike Stump2b6933f2009-02-28 09:07:16 +0000191 }
Mike Stumpf1711822009-02-25 23:33:13 +0000192
Mike Stump1fa52fe2009-03-07 02:35:30 +0000193 llvm::StructType *Ty = llvm::StructType::get(Types, true);
Mike Stumpf1711822009-02-25 23:33:13 +0000194
195 llvm::AllocaInst *A = CreateTempAlloca(Ty);
196 A->setAlignment(subBlockAlign);
197 V = A;
198
Mike Stump1fa52fe2009-03-07 02:35:30 +0000199 std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
200 int helpersize = 0;
201
202 for (unsigned i=0; i<4; ++i)
Mike Stumpf1711822009-02-25 23:33:13 +0000203 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump1bdbf632009-03-05 08:32:30 +0000204
Mike Stumpf1711822009-02-25 23:33:13 +0000205 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
206 {
Mike Stump2b6933f2009-02-28 09:07:16 +0000207 // FIXME: Push const down.
208 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
209 DeclRefExpr *DR;
210 ValueDecl *VD;
Mike Stumpf1711822009-02-25 23:33:13 +0000211
Mike Stump2b6933f2009-02-28 09:07:16 +0000212 DR = dyn_cast<DeclRefExpr>(E);
213 // Skip padding.
214 if (DR) continue;
215
216 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
217 VD = BDRE->getDecl();
218
Mike Stumpad9605d2009-03-04 03:23:46 +0000219 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stump1fa52fe2009-03-07 02:35:30 +0000220 NoteForHelper[helpersize].index = i+5;
221 NoteForHelper[helpersize].RequiresCopying = BlockRequiresCopying(VD->getType());
222 NoteForHelper[helpersize].flag
223 = VD->getType()->isBlockPointerType() ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT;
224
Mike Stump2b6933f2009-02-28 09:07:16 +0000225 if (LocalDeclMap[VD]) {
Mike Stumpad9605d2009-03-04 03:23:46 +0000226 if (BDRE->isByRef()) {
Mike Stump1fa52fe2009-03-07 02:35:30 +0000227 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
Mike Stump0a33ed32009-03-07 06:04:31 +0000228 // FIXME: Someone double check this.
229 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stumpad9605d2009-03-04 03:23:46 +0000230 const llvm::Type *Ty = Types[i+5];
231 llvm::Value *Loc = LocalDeclMap[VD];
232 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
233 Loc = Builder.CreateLoad(Loc, false);
234 Loc = Builder.CreateBitCast(Loc, Ty);
235 Builder.CreateStore(Loc, Addr);
Mike Stump1fa52fe2009-03-07 02:35:30 +0000236 ++helpersize;
Mike Stumpad9605d2009-03-04 03:23:46 +0000237 continue;
238 } else
239 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
240 VD->getType(), SourceLocation(),
241 false, false);
Mike Stump2b6933f2009-02-28 09:07:16 +0000242 }
Mike Stumpad9605d2009-03-04 03:23:46 +0000243 if (BDRE->isByRef()) {
Mike Stump29782de2009-03-21 21:00:35 +0000244 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
245 // FIXME: Someone double check this.
246 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stump2b6933f2009-02-28 09:07:16 +0000247 E = new (getContext())
248 UnaryOperator(E, UnaryOperator::AddrOf,
249 getContext().getPointerType(E->getType()),
250 SourceLocation());
Mike Stumpad9605d2009-03-04 03:23:46 +0000251 }
Mike Stump1fa52fe2009-03-07 02:35:30 +0000252 ++helpersize;
Mike Stump2b6933f2009-02-28 09:07:16 +0000253
Mike Stump2b6933f2009-02-28 09:07:16 +0000254 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpad9605d2009-03-04 03:23:46 +0000255 if (r.isScalar()) {
256 llvm::Value *Loc = r.getScalarVal();
257 const llvm::Type *Ty = Types[i+5];
258 if (BDRE->isByRef()) {
Mike Stumpf13eac12009-03-04 22:48:06 +0000259 // E is now the address of the value field, instead, we want the
260 // address of the actual ByRef struct. We optimize this slightly
261 // compared to gcc by not grabbing the forwarding slot as this must
262 // be done during Block_copy for us, and we can postpone the work
263 // until then.
264 uint64_t offset = BlockDecls[BDRE->getDecl()];
Mike Stump1bdbf632009-03-05 08:32:30 +0000265
Mike Stumpf13eac12009-03-04 22:48:06 +0000266 llvm::Value *BlockLiteral = LoadBlockStruct();
Mike Stump1bdbf632009-03-05 08:32:30 +0000267
Mike Stumpf13eac12009-03-04 22:48:06 +0000268 Loc = Builder.CreateGEP(BlockLiteral,
269 llvm::ConstantInt::get(llvm::Type::Int64Ty,
270 offset),
271 "block.literal");
272 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpad9605d2009-03-04 03:23:46 +0000273 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpf13eac12009-03-04 22:48:06 +0000274 Loc = Builder.CreateLoad(Loc, false);
275 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpad9605d2009-03-04 03:23:46 +0000276 }
277 Builder.CreateStore(Loc, Addr);
278 } else if (r.isComplex())
Mike Stumpf1711822009-02-25 23:33:13 +0000279 // FIXME: implement
280 ErrorUnsupported(BE, "complex in block literal");
281 else if (r.isAggregate())
282 ; // Already created into the destination
283 else
284 assert (0 && "bad block variable");
285 // FIXME: Ensure that the offset created by the backend for
286 // the struct matches the previously computed offset in BlockDecls.
287 }
Mike Stump1fa52fe2009-03-07 02:35:30 +0000288 NoteForHelper.resize(helpersize);
Mike Stump9d8c1262009-03-06 18:42:23 +0000289
290 // __descriptor
Mike Stump68bb7a22009-03-25 17:58:24 +0000291 llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
292 subBlockSize, Ty,
Mike Stump1fa52fe2009-03-07 02:35:30 +0000293 &NoteForHelper);
294 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
295 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpb95bc002009-02-13 16:19:19 +0000296 }
Mike Stump1bdbf632009-03-05 08:32:30 +0000297
Mike Stumpd55240e2009-02-19 01:01:04 +0000298 QualType BPT = BE->getType();
Mike Stumpf1711822009-02-25 23:33:13 +0000299 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpb95bc002009-02-13 16:19:19 +0000300}
301
302
Mike Stump1f010b52009-03-04 18:17:45 +0000303const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stump95e54802009-02-13 15:16:56 +0000304 if (BlockDescriptorType)
305 return BlockDescriptorType;
306
Mike Stumpc4ae9632009-02-13 15:32:32 +0000307 const llvm::Type *UnsignedLongTy =
Mike Stump95e54802009-02-13 15:16:56 +0000308 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000309
Mike Stump95e54802009-02-13 15:16:56 +0000310 // struct __block_descriptor {
311 // unsigned long reserved;
312 // unsigned long block_size;
313 // };
Mike Stumpc4ae9632009-02-13 15:32:32 +0000314 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
315 UnsignedLongTy,
Mike Stump95e54802009-02-13 15:16:56 +0000316 NULL);
317
318 getModule().addTypeName("struct.__block_descriptor",
319 BlockDescriptorType);
320
321 return BlockDescriptorType;
Anders Carlssond2a889b2009-02-12 00:39:25 +0000322}
323
Mike Stump1f010b52009-03-04 18:17:45 +0000324const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump0dffa462009-02-13 15:25:34 +0000325 if (GenericBlockLiteralType)
326 return GenericBlockLiteralType;
327
Mike Stumpc4ae9632009-02-13 15:32:32 +0000328 const llvm::Type *BlockDescPtrTy =
Mike Stump0dffa462009-02-13 15:25:34 +0000329 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000330
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000331 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
332 getTypes().ConvertType(getContext().IntTy));
333
Mike Stump0dffa462009-02-13 15:25:34 +0000334 // struct __block_literal_generic {
Mike Stumpd55240e2009-02-19 01:01:04 +0000335 // void *__isa;
336 // int __flags;
337 // int __reserved;
338 // void (*__invoke)(void *);
339 // struct __block_descriptor *__descriptor;
Mike Stump0dffa462009-02-13 15:25:34 +0000340 // };
Mike Stump60294662009-03-05 01:23:13 +0000341 GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000342 IntTy,
343 IntTy,
Mike Stump60294662009-03-05 01:23:13 +0000344 PtrToInt8Ty,
Mike Stump0dffa462009-02-13 15:25:34 +0000345 BlockDescPtrTy,
346 NULL);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000347
Mike Stump0dffa462009-02-13 15:25:34 +0000348 getModule().addTypeName("struct.__block_literal_generic",
349 GenericBlockLiteralType);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000350
Mike Stump0dffa462009-02-13 15:25:34 +0000351 return GenericBlockLiteralType;
Anders Carlssond2a889b2009-02-12 00:39:25 +0000352}
353
Mike Stump1f010b52009-03-04 18:17:45 +0000354const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpd55240e2009-02-19 01:01:04 +0000355 if (GenericExtendedBlockLiteralType)
356 return GenericExtendedBlockLiteralType;
357
Mike Stumpd55240e2009-02-19 01:01:04 +0000358 const llvm::Type *BlockDescPtrTy =
359 llvm::PointerType::getUnqual(getBlockDescriptorType());
360
361 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
362 getTypes().ConvertType(getContext().IntTy));
363
364 // struct __block_literal_generic {
365 // void *__isa;
366 // int __flags;
367 // int __reserved;
368 // void (*__invoke)(void *);
369 // struct __block_descriptor *__descriptor;
370 // void *__copy_func_helper_decl;
371 // void *__destroy_func_decl;
372 // };
Mike Stump60294662009-03-05 01:23:13 +0000373 GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stumpd55240e2009-02-19 01:01:04 +0000374 IntTy,
375 IntTy,
Mike Stump60294662009-03-05 01:23:13 +0000376 PtrToInt8Ty,
Mike Stumpd55240e2009-02-19 01:01:04 +0000377 BlockDescPtrTy,
Mike Stump60294662009-03-05 01:23:13 +0000378 PtrToInt8Ty,
379 PtrToInt8Ty,
Mike Stumpd55240e2009-02-19 01:01:04 +0000380 NULL);
381
382 getModule().addTypeName("struct.__block_literal_extended_generic",
383 GenericExtendedBlockLiteralType);
384
385 return GenericExtendedBlockLiteralType;
386}
387
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000388RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpc4ae9632009-02-13 15:32:32 +0000389 const BlockPointerType *BPT =
Anders Carlssond2a889b2009-02-12 00:39:25 +0000390 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpc4ae9632009-02-13 15:32:32 +0000391
Anders Carlssond2a889b2009-02-12 00:39:25 +0000392 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
393
394 // Get a pointer to the generic block literal.
395 const llvm::Type *BlockLiteralTy =
Mike Stump0dffa462009-02-13 15:25:34 +0000396 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssond2a889b2009-02-12 00:39:25 +0000397
398 // Bitcast the callee to a block literal.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000399 llvm::Value *BlockLiteral =
Anders Carlssond2a889b2009-02-12 00:39:25 +0000400 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
401
402 // Get the function pointer from the literal.
403 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Anders Carlssond2a889b2009-02-12 00:39:25 +0000404
Mike Stumpc4ae9632009-02-13 15:32:32 +0000405 BlockLiteral =
406 Builder.CreateBitCast(BlockLiteral,
Anders Carlssond2a889b2009-02-12 00:39:25 +0000407 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
408 "tmp");
Mike Stumpc4ae9632009-02-13 15:32:32 +0000409
Anders Carlssond2a889b2009-02-12 00:39:25 +0000410 // Add the block literal.
411 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
412 CallArgList Args;
413 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000414
Anders Carlsson6759c4d2009-04-08 23:13:16 +0000415 QualType FnType = BPT->getPointeeType();
416
Anders Carlssond2a889b2009-02-12 00:39:25 +0000417 // And the rest of the arguments.
Anders Carlsson6759c4d2009-04-08 23:13:16 +0000418 EmitCallArgs(Args, FnType->getAsFunctionProtoType(),
419 E->arg_begin(), E->arg_end());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000420
Anders Carlsson417d9832009-04-07 22:10:22 +0000421 // Load the function.
422 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
423
Anders Carlssonea92a922009-04-08 02:55:55 +0000424 QualType ResultType = FnType->getAsFunctionType()->getResultType();
425
426 const CGFunctionInfo &FnInfo =
427 CGM.getTypes().getFunctionInfo(ResultType, Args);
Anders Carlsson417d9832009-04-07 22:10:22 +0000428
429 // Cast the function pointer to the right type.
430 const llvm::Type *BlockFTy =
Anders Carlssonea92a922009-04-08 02:55:55 +0000431 CGM.getTypes().GetFunctionType(FnInfo, false);
Anders Carlsson417d9832009-04-07 22:10:22 +0000432
433 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
434 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
435
Anders Carlssond2a889b2009-02-12 00:39:25 +0000436 // And call the block.
Anders Carlsson3f03b812009-04-07 00:20:24 +0000437 return EmitCall(FnInfo, Func, Args);
Anders Carlssond2a889b2009-02-12 00:39:25 +0000438}
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000439
Mike Stumpad9605d2009-03-04 03:23:46 +0000440llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
441 uint64_t &offset = BlockDecls[E->getDecl()];
442
443 const llvm::Type *Ty;
444 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
445
Mike Stumpad9605d2009-03-04 03:23:46 +0000446 // See if we have already allocated an offset for this variable.
447 if (offset == 0) {
Mike Stump1bdbf632009-03-05 08:32:30 +0000448 // Don't run the expensive check, unless we have to.
449 if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
450 BlockHasCopyDispose = true;
Mike Stumpad9605d2009-03-04 03:23:46 +0000451 // if not, allocate one now.
452 offset = getBlockOffset(E);
453 }
454
455 llvm::Value *BlockLiteral = LoadBlockStruct();
456 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
457 llvm::ConstantInt::get(llvm::Type::Int64Ty,
458 offset),
Mike Stumpf13eac12009-03-04 22:48:06 +0000459 "block.literal");
Mike Stumpad9605d2009-03-04 03:23:46 +0000460 if (E->isByRef()) {
461 bool needsCopyDispose = BlockRequiresCopying(E->getType());
462 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
463 const llvm::Type *PtrStructTy
464 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
Mike Stump29782de2009-03-21 21:00:35 +0000465 // The block literal will need a copy/destroy helper.
466 BlockHasCopyDispose = true;
Mike Stumpad9605d2009-03-04 03:23:46 +0000467 Ty = PtrStructTy;
468 Ty = llvm::PointerType::get(Ty, 0);
469 V = Builder.CreateBitCast(V, Ty);
470 V = Builder.CreateLoad(V, false);
471 V = Builder.CreateStructGEP(V, 1, "forwarding");
472 V = Builder.CreateLoad(V, false);
473 V = Builder.CreateBitCast(V, PtrStructTy);
474 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
475 } else {
476 Ty = llvm::PointerType::get(Ty, 0);
477 V = Builder.CreateBitCast(V, Ty);
478 }
479 return V;
480}
481
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000482void CodeGenFunction::BlockForwardSelf() {
483 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
484 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
485 llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
486 if (DMEntry)
487 return;
488 // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
489 BlockDeclRefExpr *BDRE = new (getContext())
490 BlockDeclRefExpr(SelfDecl,
491 SelfDecl->getType(), SourceLocation(), false);
492 DMEntry = GetAddrOfBlockDecl(BDRE);
493}
494
Mike Stump084ba462009-02-14 22:16:35 +0000495llvm::Constant *
Mike Stumpd6d0ebe2009-03-04 18:47:42 +0000496BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000497 // Generate the block descriptor.
498 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000499 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
500 getTypes().ConvertType(getContext().IntTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000501
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000502 llvm::Constant *DescriptorFields[2];
Mike Stumpc4ae9632009-02-13 15:32:32 +0000503
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000504 // Reserved
505 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000506
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000507 // Block literal size. For global blocks we just use the size of the generic
508 // block literal struct.
Mike Stumpc4ae9632009-02-13 15:32:32 +0000509 uint64_t BlockLiteralSize =
Mike Stump0dffa462009-02-13 15:25:34 +0000510 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000511 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000512
513 llvm::Constant *DescriptorStruct =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000514 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000515
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000516 llvm::GlobalVariable *Descriptor =
Owen Anderson96bcdd42009-07-08 01:29:18 +0000517 new llvm::GlobalVariable(getModule().getContext(),
518 DescriptorStruct->getType(), true,
Mike Stumpc4ae9632009-02-13 15:32:32 +0000519 llvm::GlobalVariable::InternalLinkage,
520 DescriptorStruct, "__block_descriptor_global",
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000521 &getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000522
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000523 // Generate the constants for the block literal.
524 llvm::Constant *LiteralFields[5];
Mike Stumpc4ae9632009-02-13 15:32:32 +0000525
Mike Stump084ba462009-02-14 22:16:35 +0000526 CodeGenFunction::BlockInfo Info(0, n);
Mike Stumpf1711822009-02-25 23:33:13 +0000527 uint64_t subBlockSize, subBlockAlign;
Mike Stump2b6933f2009-02-28 09:07:16 +0000528 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Daniel Dunbaradaf35f2009-03-12 03:07:24 +0000529 bool subBlockHasCopyDispose = false;
Mike Stumpa20c59e2009-03-13 23:34:28 +0000530 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stumpfca5da02009-02-21 20:00:35 +0000531 llvm::Function *Fn
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000532 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000533 subBlockSize,
Mike Stumpd6d0ebe2009-03-04 18:47:42 +0000534 subBlockAlign,
Mike Stump1bdbf632009-03-05 08:32:30 +0000535 subBlockDeclRefDecls,
536 subBlockHasCopyDispose);
Mike Stumpfca5da02009-02-21 20:00:35 +0000537 assert(subBlockSize == BlockLiteralSize
538 && "no imports allowed for global block");
Mike Stumpc4ae9632009-02-13 15:32:32 +0000539
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000540 // isa
Mike Stump5f87e9d2009-02-13 17:23:42 +0000541 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpc4ae9632009-02-13 15:32:32 +0000542
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000543 // Flags
Mike Stump1bdbf632009-03-05 08:32:30 +0000544 LiteralFields[1] =
Anders Carlsson63810c62009-03-01 21:09:29 +0000545 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000546
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000547 // Reserved
Mike Stump7b7cd8b2009-02-13 16:01:35 +0000548 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000549
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000550 // Function
551 LiteralFields[3] = Fn;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000552
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000553 // Descriptor
554 LiteralFields[4] = Descriptor;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000555
556 llvm::Constant *BlockLiteralStruct =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000557 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000558
559 llvm::GlobalVariable *BlockLiteral =
Owen Anderson96bcdd42009-07-08 01:29:18 +0000560 new llvm::GlobalVariable(getModule().getContext(),
561 BlockLiteralStruct->getType(), true,
Mike Stumpc4ae9632009-02-13 15:32:32 +0000562 llvm::GlobalVariable::InternalLinkage,
563 BlockLiteralStruct, "__block_literal_global",
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000564 &getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000565
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000566 return BlockLiteral;
567}
568
Mike Stumpfca5da02009-02-21 20:00:35 +0000569llvm::Value *CodeGenFunction::LoadBlockStruct() {
570 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
571}
572
Mike Stump1bdbf632009-03-05 08:32:30 +0000573llvm::Function *
574CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
575 const BlockInfo& Info,
Mike Stumpfc5e6de2009-03-20 21:53:12 +0000576 const Decl *OuterFuncDecl,
Mike Stumpa20c59e2009-03-13 23:34:28 +0000577 llvm::DenseMap<const Decl*, llvm::Value*> ldm,
Mike Stump1bdbf632009-03-05 08:32:30 +0000578 uint64_t &Size,
579 uint64_t &Align,
580 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
581 bool &subBlockHasCopyDispose) {
Devang Patel6ae64bb2009-04-15 21:51:44 +0000582
583 // Check if we should generate debug info for this block.
584 if (CGM.getDebugInfo())
585 DebugInfo = CGM.getDebugInfo();
586
Mike Stumpa20c59e2009-03-13 23:34:28 +0000587 // Arrange for local static and local extern declarations to appear
588 // to be local to this function as well, as they are directly referenced
589 // in a block.
590 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
591 i != ldm.end();
592 ++i) {
593 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
594
Daniel Dunbar644c15e2009-04-14 02:25:56 +0000595 if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
Mike Stumpa20c59e2009-03-13 23:34:28 +0000596 LocalDeclMap[VD] = i->second;
597 }
598
Eli Friedman584abaf2009-03-28 03:24:54 +0000599 // FIXME: We need to rearrange the code for copy/dispose so we have this
600 // sooner, so we can calculate offsets correctly.
601 if (!BlockHasCopyDispose)
602 BlockOffset = CGM.getTargetData()
603 .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
604 else
605 BlockOffset = CGM.getTargetData()
606 .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
607 BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
608
Fariborz Jahanian3413b1a2009-04-11 17:55:15 +0000609 const FunctionType *BlockFunctionType = BExpr->getFunctionType();
610 QualType ResultType;
611 bool IsVariadic;
Fariborz Jahaniande6a6492009-04-11 18:54:57 +0000612 if (const FunctionProtoType *FTy =
613 dyn_cast<FunctionProtoType>(BlockFunctionType)) {
Fariborz Jahanian3413b1a2009-04-11 17:55:15 +0000614 ResultType = FTy->getResultType();
615 IsVariadic = FTy->isVariadic();
616 }
617 else {
618 // K&R style block.
619 ResultType = BlockFunctionType->getResultType();
620 IsVariadic = false;
621 }
Mike Stumpc4ae9632009-02-13 15:32:32 +0000622
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000623 FunctionArgList Args;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000624
Chris Lattner8130e7f2009-02-28 19:01:03 +0000625 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000626
627 // FIXME: This leaks
Mike Stumpc4ae9632009-02-13 15:32:32 +0000628 ImplicitParamDecl *SelfDecl =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000629 ImplicitParamDecl::Create(getContext(), 0,
630 SourceLocation(), 0,
631 getContext().getPointerType(getContext().VoidTy));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000632
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000633 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stumpfca5da02009-02-21 20:00:35 +0000634 BlockStructDecl = SelfDecl;
Mike Stumpc4ae9632009-02-13 15:32:32 +0000635
Steve Naroff494cb0f2009-03-13 16:56:44 +0000636 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000637 e = BD->param_end(); i != e; ++i)
Mike Stump459207f2009-02-17 23:25:52 +0000638 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpc4ae9632009-02-13 15:32:32 +0000639
640 const CGFunctionInfo &FI =
Fariborz Jahanian3413b1a2009-04-11 17:55:15 +0000641 CGM.getTypes().getFunctionInfo(ResultType, Args);
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000642
Mike Stump084ba462009-02-14 22:16:35 +0000643 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000644 CodeGenTypes &Types = CGM.getTypes();
Fariborz Jahanian3413b1a2009-04-11 17:55:15 +0000645 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
Mike Stumpc4ae9632009-02-13 15:32:32 +0000646
647 llvm::Function *Fn =
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000648 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
649 Name,
650 &CGM.getModule());
Mike Stumpc4ae9632009-02-13 15:32:32 +0000651
Daniel Dunbar5b90ae12009-04-17 00:48:04 +0000652 CGM.SetInternalFunctionAttributes(BD, Fn, FI);
653
Chris Lattnerab3d3732009-04-23 07:18:56 +0000654 StartFunction(BD, ResultType, Fn, Args,
Chris Lattner8130e7f2009-02-28 19:01:03 +0000655 BExpr->getBody()->getLocEnd());
Chris Lattnerab3d3732009-04-23 07:18:56 +0000656 CurFuncDecl = OuterFuncDecl;
Chris Lattnerf6279ae2009-04-23 05:30:27 +0000657 CurCodeDecl = BD;
Chris Lattner8130e7f2009-02-28 19:01:03 +0000658 EmitStmt(BExpr->getBody());
659 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000660
Mike Stumpf1711822009-02-25 23:33:13 +0000661 // The runtime needs a minimum alignment of a void *.
662 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
663 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
664
Mike Stumpfca5da02009-02-21 20:00:35 +0000665 Size = BlockOffset;
Mike Stumpf1711822009-02-25 23:33:13 +0000666 Align = BlockAlign;
667 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump1bdbf632009-03-05 08:32:30 +0000668 subBlockHasCopyDispose |= BlockHasCopyDispose;
Anders Carlsson1f1cd392009-02-12 17:55:02 +0000669 return Fn;
670}
Mike Stump2b6933f2009-02-28 09:07:16 +0000671
Mike Stump1fa52fe2009-03-07 02:35:30 +0000672uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
Mike Stump2b6933f2009-02-28 09:07:16 +0000673 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
674
675 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
676 uint64_t Align = getContext().getDeclAlignInBytes(D);
677
678 if (BDRE->isByRef()) {
679 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
680 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
681 }
682
683 assert ((Align > 0) && "alignment must be 1 byte or more");
684
685 uint64_t OldOffset = BlockOffset;
686
687 // Ensure proper alignment, even if it means we have to have a gap
688 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
689 BlockAlign = std::max(Align, BlockAlign);
Mike Stump1bdbf632009-03-05 08:32:30 +0000690
Mike Stump2b6933f2009-02-28 09:07:16 +0000691 uint64_t Pad = BlockOffset - OldOffset;
692 if (Pad) {
693 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
694 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
695 llvm::APInt(32, Pad),
696 ArrayType::Normal, 0);
697 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
698 0, QualType(PadTy), VarDecl::None,
699 SourceLocation());
700 Expr *E;
701 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
702 SourceLocation(), false, false);
703 BlockDeclRefDecls.push_back(E);
704 }
705 BlockDeclRefDecls.push_back(BDRE);
706
707 BlockOffset += Size;
708 return BlockOffset-Size;
709}
Mike Stumpad9605d2009-03-04 03:23:46 +0000710
Mike Stump1fa52fe2009-03-07 02:35:30 +0000711llvm::Constant *BlockFunction::
712GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
Mike Stump2f9a4262009-04-10 18:52:28 +0000713 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpecd79422009-03-06 01:33:24 +0000714 QualType R = getContext().VoidTy;
715
716 FunctionArgList Args;
717 // FIXME: This leaks
Mike Stump1fa52fe2009-03-07 02:35:30 +0000718 ImplicitParamDecl *Dst =
719 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
720 getContext().getPointerType(getContext().VoidTy));
721 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpecd79422009-03-06 01:33:24 +0000722 ImplicitParamDecl *Src =
723 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
724 getContext().getPointerType(getContext().VoidTy));
Mike Stumpecd79422009-03-06 01:33:24 +0000725 Args.push_back(std::make_pair(Src, Src->getType()));
726
727 const CGFunctionInfo &FI =
728 CGM.getTypes().getFunctionInfo(R, Args);
729
Mike Stumpc32f9c12009-06-05 23:26:36 +0000730 // FIXME: We'd like to put these into a mergable by content, with
731 // internal linkage.
Mike Stumpecd79422009-03-06 01:33:24 +0000732 std::string Name = std::string("__copy_helper_block_");
733 CodeGenTypes &Types = CGM.getTypes();
734 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
735
736 llvm::Function *Fn =
737 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
738 Name,
739 &CGM.getModule());
740
741 IdentifierInfo *II
742 = &CGM.getContext().Idents.get("__copy_helper_block_");
743
744 FunctionDecl *FD = FunctionDecl::Create(getContext(),
745 getContext().getTranslationUnitDecl(),
746 SourceLocation(), II, R,
747 FunctionDecl::Static, false,
748 true);
749 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1fa52fe2009-03-07 02:35:30 +0000750
751 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
752 llvm::Type *PtrPtrT;
Mike Stump1fa52fe2009-03-07 02:35:30 +0000753
Mike Stump2f9a4262009-04-10 18:52:28 +0000754 if (NoteForHelperp) {
755 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump1fa52fe2009-03-07 02:35:30 +0000756
Mike Stump2f9a4262009-04-10 18:52:28 +0000757 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
758 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
759 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump1fa52fe2009-03-07 02:35:30 +0000760
Mike Stump2f9a4262009-04-10 18:52:28 +0000761 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
Mike Stumpb71fa972009-04-15 22:11:36 +0000762 llvm::Type *PtrPtrT;
763 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
764 DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
765 DstObj = Builder.CreateLoad(DstObj);
Mike Stump1fa52fe2009-03-07 02:35:30 +0000766
Mike Stump2f9a4262009-04-10 18:52:28 +0000767 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
768 int flag = NoteForHelper[i].flag;
769 int index = NoteForHelper[i].index;
Mike Stump1fa52fe2009-03-07 02:35:30 +0000770
Mike Stump2f9a4262009-04-10 18:52:28 +0000771 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
772 || NoteForHelper[i].RequiresCopying) {
773 llvm::Value *Srcv = SrcObj;
774 Srcv = Builder.CreateStructGEP(Srcv, index);
775 Srcv = Builder.CreateBitCast(Srcv,
776 llvm::PointerType::get(PtrToInt8Ty, 0));
777 Srcv = Builder.CreateLoad(Srcv);
778
779 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
780 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
781
782 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
783 llvm::Value *F = getBlockObjectAssign();
784 Builder.CreateCall3(F, Dstv, Srcv, N);
785 }
Mike Stump1fa52fe2009-03-07 02:35:30 +0000786 }
787 }
788
Mike Stumpecd79422009-03-06 01:33:24 +0000789 CGF.FinishFunction();
790
791 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpad9605d2009-03-04 03:23:46 +0000792}
793
Mike Stump9d8c1262009-03-06 18:42:23 +0000794llvm::Constant *BlockFunction::
Mike Stump1fa52fe2009-03-07 02:35:30 +0000795GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
796 const llvm::StructType* T,
Mike Stump2f9a4262009-04-10 18:52:28 +0000797 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stumpecd79422009-03-06 01:33:24 +0000798 QualType R = getContext().VoidTy;
799
800 FunctionArgList Args;
801 // FIXME: This leaks
802 ImplicitParamDecl *Src =
803 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
804 getContext().getPointerType(getContext().VoidTy));
805
806 Args.push_back(std::make_pair(Src, Src->getType()));
807
808 const CGFunctionInfo &FI =
809 CGM.getTypes().getFunctionInfo(R, Args);
810
Mike Stumpc32f9c12009-06-05 23:26:36 +0000811 // FIXME: We'd like to put these into a mergable by content, with
812 // internal linkage.
Mike Stumpecd79422009-03-06 01:33:24 +0000813 std::string Name = std::string("__destroy_helper_block_");
814 CodeGenTypes &Types = CGM.getTypes();
815 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
816
817 llvm::Function *Fn =
818 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
819 Name,
820 &CGM.getModule());
821
822 IdentifierInfo *II
823 = &CGM.getContext().Idents.get("__destroy_helper_block_");
824
825 FunctionDecl *FD = FunctionDecl::Create(getContext(),
826 getContext().getTranslationUnitDecl(),
827 SourceLocation(), II, R,
828 FunctionDecl::Static, false,
829 true);
830 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump05a6d4e2009-03-07 02:53:18 +0000831
Mike Stump2f9a4262009-04-10 18:52:28 +0000832 if (NoteForHelperp) {
833 std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
Mike Stump05a6d4e2009-03-07 02:53:18 +0000834
Mike Stump2f9a4262009-04-10 18:52:28 +0000835 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
836 llvm::Type *PtrPtrT;
837 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
838 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
839 SrcObj = Builder.CreateLoad(SrcObj);
Mike Stump05a6d4e2009-03-07 02:53:18 +0000840
Mike Stump2f9a4262009-04-10 18:52:28 +0000841 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
842 int flag = NoteForHelper[i].flag;
843 int index = NoteForHelper[i].index;
Mike Stump05a6d4e2009-03-07 02:53:18 +0000844
Mike Stump2f9a4262009-04-10 18:52:28 +0000845 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
846 || NoteForHelper[i].RequiresCopying) {
847 llvm::Value *Srcv = SrcObj;
848 Srcv = Builder.CreateStructGEP(Srcv, index);
849 Srcv = Builder.CreateBitCast(Srcv,
850 llvm::PointerType::get(PtrToInt8Ty, 0));
851 Srcv = Builder.CreateLoad(Srcv);
852
853 BuildBlockRelease(Srcv, flag);
854 }
Mike Stump05a6d4e2009-03-07 02:53:18 +0000855 }
856 }
857
Mike Stumpecd79422009-03-06 01:33:24 +0000858 CGF.FinishFunction();
859
860 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
861}
862
Mike Stump1fa52fe2009-03-07 02:35:30 +0000863llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
Mike Stump2f9a4262009-04-10 18:52:28 +0000864 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump1fa52fe2009-03-07 02:35:30 +0000865 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
866 T, NoteForHelper);
Mike Stumpecd79422009-03-06 01:33:24 +0000867}
868
Mike Stump1fa52fe2009-03-07 02:35:30 +0000869llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
Mike Stump2f9a4262009-04-10 18:52:28 +0000870 std::vector<HelperInfo> *NoteForHelperp) {
Mike Stump1fa52fe2009-03-07 02:35:30 +0000871 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
Mike Stump2f9a4262009-04-10 18:52:28 +0000872 T, NoteForHelperp);
Mike Stumpad9605d2009-03-04 03:23:46 +0000873}
Mike Stump60294662009-03-05 01:23:13 +0000874
Mike Stump11973b62009-03-06 06:12:24 +0000875llvm::Constant *BlockFunction::
876GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stumpf4b62342009-03-06 02:29:21 +0000877 QualType R = getContext().VoidTy;
878
879 FunctionArgList Args;
880 // FIXME: This leaks
Mike Stump11973b62009-03-06 06:12:24 +0000881 ImplicitParamDecl *Dst =
882 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
883 getContext().getPointerType(getContext().VoidTy));
884 Args.push_back(std::make_pair(Dst, Dst->getType()));
885
886 // FIXME: This leaks
Mike Stumpf4b62342009-03-06 02:29:21 +0000887 ImplicitParamDecl *Src =
888 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
889 getContext().getPointerType(getContext().VoidTy));
Mike Stumpf4b62342009-03-06 02:29:21 +0000890 Args.push_back(std::make_pair(Src, Src->getType()));
891
892 const CGFunctionInfo &FI =
893 CGM.getTypes().getFunctionInfo(R, Args);
894
895 std::string Name = std::string("__Block_byref_id_object_copy_");
896 CodeGenTypes &Types = CGM.getTypes();
897 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
898
Mike Stumpc32f9c12009-06-05 23:26:36 +0000899 // FIXME: We'd like to put these into a mergable by content, with
900 // internal linkage.
Mike Stumpf4b62342009-03-06 02:29:21 +0000901 llvm::Function *Fn =
902 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
903 Name,
904 &CGM.getModule());
905
906 IdentifierInfo *II
907 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
908
909 FunctionDecl *FD = FunctionDecl::Create(getContext(),
910 getContext().getTranslationUnitDecl(),
911 SourceLocation(), II, R,
912 FunctionDecl::Static, false,
913 true);
914 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump11973b62009-03-06 06:12:24 +0000915
916 // dst->x
917 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
Mike Stumpb71fa972009-04-15 22:11:36 +0000918 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
919 V = Builder.CreateLoad(V);
Mike Stump11973b62009-03-06 06:12:24 +0000920 V = Builder.CreateStructGEP(V, 6, "x");
921 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
922
923 // src->x
924 V = CGF.GetAddrOfLocalVar(Src);
925 V = Builder.CreateLoad(V);
926 V = Builder.CreateBitCast(V, T);
927 V = Builder.CreateStructGEP(V, 6, "x");
928 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
929 llvm::Value *SrcObj = Builder.CreateLoad(V);
930
931 flag |= BLOCK_BYREF_CALLER;
932
933 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
934 llvm::Value *F = getBlockObjectAssign();
935 Builder.CreateCall3(F, DstObj, SrcObj, N);
936
Mike Stumpf4b62342009-03-06 02:29:21 +0000937 CGF.FinishFunction();
938
939 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
940}
941
Mike Stump4a0e5132009-03-06 04:53:30 +0000942llvm::Constant *
943BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
944 int flag) {
Mike Stumpf4b62342009-03-06 02:29:21 +0000945 QualType R = getContext().VoidTy;
946
947 FunctionArgList Args;
948 // FIXME: This leaks
949 ImplicitParamDecl *Src =
950 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
951 getContext().getPointerType(getContext().VoidTy));
952
953 Args.push_back(std::make_pair(Src, Src->getType()));
954
955 const CGFunctionInfo &FI =
956 CGM.getTypes().getFunctionInfo(R, Args);
957
958 std::string Name = std::string("__Block_byref_id_object_dispose_");
959 CodeGenTypes &Types = CGM.getTypes();
960 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
961
Mike Stumpc32f9c12009-06-05 23:26:36 +0000962 // FIXME: We'd like to put these into a mergable by content, with
963 // internal linkage.
Mike Stumpf4b62342009-03-06 02:29:21 +0000964 llvm::Function *Fn =
965 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
966 Name,
967 &CGM.getModule());
968
969 IdentifierInfo *II
970 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
971
972 FunctionDecl *FD = FunctionDecl::Create(getContext(),
973 getContext().getTranslationUnitDecl(),
974 SourceLocation(), II, R,
975 FunctionDecl::Static, false,
976 true);
977 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump4a0e5132009-03-06 04:53:30 +0000978
979 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
Mike Stumpb71fa972009-04-15 22:11:36 +0000980 V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
981 V = Builder.CreateLoad(V);
Mike Stump4a0e5132009-03-06 04:53:30 +0000982 V = Builder.CreateStructGEP(V, 6, "x");
Mike Stumpb71fa972009-04-15 22:11:36 +0000983 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
984 V = Builder.CreateLoad(V);
Mike Stump4a0e5132009-03-06 04:53:30 +0000985
Mike Stump4a0e5132009-03-06 04:53:30 +0000986 flag |= BLOCK_BYREF_CALLER;
987 BuildBlockRelease(V, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +0000988 CGF.FinishFunction();
989
990 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
991}
992
Mike Stump11973b62009-03-06 06:12:24 +0000993llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
Mike Stumpc32f9c12009-06-05 23:26:36 +0000994 int flag, unsigned Align) {
995 // All alignments below that of pointer alignment collpase down to just
996 // pointer alignment, as we always have at least that much alignment to begin
997 // with.
998 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
999 // As an optimization, we only generate a single function of each kind we
1000 // might need. We need a different one for each alignment and for each
1001 // setting of flags. We mix Align and flag to get the kind.
1002 uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1003 llvm::Constant *& Entry = CGM.AssignCache[kind];
1004 if (Entry)
1005 return Entry;
1006 return Entry=CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +00001007}
1008
Mike Stump4a0e5132009-03-06 04:53:30 +00001009llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
Mike Stumpc32f9c12009-06-05 23:26:36 +00001010 int flag,
1011 unsigned Align) {
1012 // All alignments below that of pointer alignment collpase down to just
1013 // pointer alignment, as we always have at least that much alignment to begin
1014 // with.
1015 Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1016 // As an optimization, we only generate a single function of each kind we
1017 // might need. We need a different one for each alignment and for each
1018 // setting of flags. We mix Align and flag to get the kind.
1019 uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1020 llvm::Constant *& Entry = CGM.DestroyCache[kind];
1021 if (Entry)
1022 return Entry;
1023 return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
Mike Stumpf4b62342009-03-06 02:29:21 +00001024}
1025
Mike Stump60294662009-03-05 01:23:13 +00001026llvm::Value *BlockFunction::getBlockObjectDispose() {
1027 if (CGM.BlockObjectDispose == 0) {
1028 const llvm::FunctionType *FTy;
1029 std::vector<const llvm::Type*> ArgTys;
1030 const llvm::Type *ResultType = llvm::Type::VoidTy;
1031 ArgTys.push_back(PtrToInt8Ty);
1032 ArgTys.push_back(llvm::Type::Int32Ty);
1033 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump1bdbf632009-03-05 08:32:30 +00001034 CGM.BlockObjectDispose
Mike Stump60294662009-03-05 01:23:13 +00001035 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1036 }
1037 return CGM.BlockObjectDispose;
1038}
1039
Mike Stump11973b62009-03-06 06:12:24 +00001040llvm::Value *BlockFunction::getBlockObjectAssign() {
1041 if (CGM.BlockObjectAssign == 0) {
1042 const llvm::FunctionType *FTy;
1043 std::vector<const llvm::Type*> ArgTys;
1044 const llvm::Type *ResultType = llvm::Type::VoidTy;
1045 ArgTys.push_back(PtrToInt8Ty);
1046 ArgTys.push_back(PtrToInt8Ty);
1047 ArgTys.push_back(llvm::Type::Int32Ty);
1048 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1049 CGM.BlockObjectAssign
1050 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1051 }
1052 return CGM.BlockObjectAssign;
1053}
1054
Mike Stump4a0e5132009-03-06 04:53:30 +00001055void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump60294662009-03-05 01:23:13 +00001056 llvm::Value *F = getBlockObjectDispose();
Mike Stump4a0e5132009-03-06 04:53:30 +00001057 llvm::Value *N;
Mike Stump60294662009-03-05 01:23:13 +00001058 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump4a0e5132009-03-06 04:53:30 +00001059 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
Mike Stump60294662009-03-05 01:23:13 +00001060 Builder.CreateCall2(F, V, N);
1061}
Mike Stump1bdbf632009-03-05 08:32:30 +00001062
1063ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump1fa52fe2009-03-07 02:35:30 +00001064
1065BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1066 CGBuilderTy &B)
1067 : CGM(cgm), CGF(cgf), Builder(B) {
1068 PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1069
1070 BlockHasCopyDispose = false;
1071}