blob: eba741bc3c43e756306053e599c575f24e82cfcc [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
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Mike Stump6cc88f72009-03-20 21:53:12 +000016#include "clang/AST/DeclObjC.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000017#include "llvm/Module.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000018#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000019
20#include <algorithm>
21
22using namespace clang;
23using namespace CodeGen;
24
Mike Stump58919e12009-03-04 13:17:22 +000025// Temporary code to enable testing of __block variables
26// #include "clang/Frontend/CompileOptions.h"
27#include "llvm/Support/CommandLine.h"
28static llvm::cl::opt<bool>
29Enable__block("f__block",
30 // See all the FIXMEs for the various work that needs to be done
31 llvm::cl::desc("temporary option to turn on __block precessing "
32 "even though the code isn't done yet"),
33 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
Mike Stump00470a12009-03-05 08:32:30 +000034 llvm::cl::ZeroOrMore,
Mike Stump63822ba2009-03-07 06:16:52 +000035 llvm::cl::init(true));
Mike Stump58919e12009-03-04 13:17:22 +000036
Mike Stumpcf62d392009-03-06 18:42:23 +000037llvm::Constant *CodeGenFunction::
Mike Stumpa803b0e2009-03-25 17:58:24 +000038BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size,
39 const llvm::StructType* Ty,
Mike Stump08920992009-03-07 02:35:30 +000040 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump56129b12009-02-13 16:55:51 +000041 const llvm::Type *UnsignedLongTy
42 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000043 llvm::Constant *C;
44 std::vector<llvm::Constant*> Elts;
45
46 // reserved
Mike Stump56129b12009-02-13 16:55:51 +000047 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000048 Elts.push_back(C);
49
50 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000051 // FIXME: What is the right way to say this doesn't fit? We should give
52 // a user diagnostic in that case. Better fix would be to change the
53 // API to size_t.
Mike Stump4e7a1f72009-02-21 20:00:35 +000054 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpe5fee252009-02-13 16:19:19 +000055 Elts.push_back(C);
56
57 if (BlockHasCopyDispose) {
58 // copy_func_helper_decl
Mike Stump08920992009-03-07 02:35:30 +000059 Elts.push_back(BuildCopyHelper(Ty, *NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000060
61 // destroy_func_decl
Mike Stump08920992009-03-07 02:35:30 +000062 Elts.push_back(BuildDestroyHelper(Ty, *NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000063 }
64
65 C = llvm::ConstantStruct::get(Elts);
66
Mike Stumpe5fee252009-02-13 16:19:19 +000067 C = new llvm::GlobalVariable(C->getType(), true,
68 llvm::GlobalValue::InternalLinkage,
Mike Stump7d6dc4f2009-02-13 20:17:16 +000069 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpe5fee252009-02-13 16:19:19 +000070 return C;
71}
72
Mike Stump2a998142009-03-04 18:17:45 +000073llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Mike Stumpf99f1d02009-02-13 17:23:42 +000074 if (NSConcreteGlobalBlock)
75 return NSConcreteGlobalBlock;
76
Mike Stumpf7448952009-02-13 19:38:12 +000077 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000078 // same thing as CreateRuntimeFunction if there's already a variable with the
79 // same name.
Mike Stumpf99f1d02009-02-13 17:23:42 +000080 NSConcreteGlobalBlock
Mike Stump00470a12009-03-05 08:32:30 +000081 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stumpf99f1d02009-02-13 17:23:42 +000082 llvm::GlobalValue::ExternalLinkage,
83 0, "_NSConcreteGlobalBlock",
84 &getModule());
85
86 return NSConcreteGlobalBlock;
87}
88
Mike Stump2a998142009-03-04 18:17:45 +000089llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Mike Stump59c5b112009-02-13 19:29:27 +000090 if (NSConcreteStackBlock)
91 return NSConcreteStackBlock;
92
Mike Stumpf7448952009-02-13 19:38:12 +000093 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000094 // same thing as CreateRuntimeFunction if there's already a variable with the
95 // same name.
Mike Stump59c5b112009-02-13 19:29:27 +000096 NSConcreteStackBlock
Mike Stump00470a12009-03-05 08:32:30 +000097 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stump59c5b112009-02-13 19:29:27 +000098 llvm::GlobalValue::ExternalLinkage,
99 0, "_NSConcreteStackBlock",
100 &getModule());
101
102 return NSConcreteStackBlock;
103}
104
Mike Stump00470a12009-03-05 08:32:30 +0000105static void CollectBlockDeclRefInfo(const Stmt *S,
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000106 CodeGenFunction::BlockInfo &Info) {
107 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
108 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000109 if (*I)
110 CollectBlockDeclRefInfo(*I, Info);
Mike Stump00470a12009-03-05 08:32:30 +0000111
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000112 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
113 // FIXME: Handle enums.
114 if (isa<FunctionDecl>(DE->getDecl()))
115 return;
Mike Stump00470a12009-03-05 08:32:30 +0000116
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000117 if (DE->isByRef())
118 Info.ByRefDeclRefs.push_back(DE);
119 else
120 Info.ByCopyDeclRefs.push_back(DE);
121 }
122}
123
Mike Stump58a85142009-03-04 22:48:06 +0000124/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
125/// declared as a global variable instead of on the stack.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000126static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
127{
128 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
129}
130
Mike Stump58a85142009-03-04 22:48:06 +0000131// FIXME: Push most into CGM, passing down a few bits, like current function
132// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000133llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpe5fee252009-02-13 16:19:19 +0000134
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000135 std::string Name = CurFn->getName();
136 CodeGenFunction::BlockInfo Info(0, Name.c_str());
137 CollectBlockDeclRefInfo(BE->getBody(), Info);
138
139 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000140 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
141 // to just have one code path. We should move this function into CGM and pass
142 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000143 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000144 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump00470a12009-03-05 08:32:30 +0000145
146 std::vector<llvm::Constant*> Elts(5);
Mike Stumpe5fee252009-02-13 16:19:19 +0000147 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000148 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000149
Mike Stumpe5fee252009-02-13 16:19:19 +0000150 {
151 // C = BuildBlockStructInitlist();
152 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
153
Mike Stump00470a12009-03-05 08:32:30 +0000154 // We run this first so that we set BlockHasCopyDispose from the entire
155 // block literal.
156 // __invoke
157 uint64_t subBlockSize, subBlockAlign;
158 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stumpa803b0e2009-03-25 17:58:24 +0000159 bool subBlockHasCopyDispose = false;
Mike Stump00470a12009-03-05 08:32:30 +0000160 llvm::Function *Fn
Mike Stump6cc88f72009-03-20 21:53:12 +0000161 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl, LocalDeclMap,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000162 subBlockSize,
Mike Stump00470a12009-03-05 08:32:30 +0000163 subBlockAlign,
164 subBlockDeclRefDecls,
Mike Stumpa803b0e2009-03-25 17:58:24 +0000165 subBlockHasCopyDispose);
166 BlockHasCopyDispose |= subBlockHasCopyDispose;
Mike Stump00470a12009-03-05 08:32:30 +0000167 Elts[3] = Fn;
168
169 if (!Enable__block && BlockHasCopyDispose)
170 ErrorUnsupported(BE, "block literal that requires copy/dispose");
171
Mike Stumpa803b0e2009-03-25 17:58:24 +0000172 if (subBlockHasCopyDispose)
Mike Stumpe5fee252009-02-13 16:19:19 +0000173 flags |= BLOCK_HAS_COPY_DISPOSE;
174
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000175 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000176 C = CGM.getNSConcreteStackBlock();
Mike Stumpe5fee252009-02-13 16:19:19 +0000177 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump00470a12009-03-05 08:32:30 +0000178 Elts[0] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000179
180 // __flags
181 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
182 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
183 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump00470a12009-03-05 08:32:30 +0000184 Elts[1] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000185
186 // __reserved
187 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump00470a12009-03-05 08:32:30 +0000188 Elts[2] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000189
Mike Stump8a2b4b12009-02-25 23:33:13 +0000190 if (subBlockDeclRefDecls.size() == 0) {
Mike Stumpcf62d392009-03-06 18:42:23 +0000191 // __descriptor
Mike Stumpa803b0e2009-03-25 17:58:24 +0000192 assert(subBlockHasCopyDispose == false);
193 Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize, 0, 0);
Mike Stumpcf62d392009-03-06 18:42:23 +0000194
Mike Stump5570cfe2009-03-01 20:07:53 +0000195 // Optimize to being a global block.
196 Elts[0] = CGM.getNSConcreteGlobalBlock();
197 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
198
Mike Stump8a2b4b12009-02-25 23:33:13 +0000199 C = llvm::ConstantStruct::get(Elts);
200
201 char Name[32];
202 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
203 C = new llvm::GlobalVariable(C->getType(), true,
204 llvm::GlobalValue::InternalLinkage,
205 C, Name, &CGM.getModule());
206 QualType BPT = BE->getType();
207 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
208 return C;
209 }
Mike Stump00470a12009-03-05 08:32:30 +0000210
Mike Stump8a2b4b12009-02-25 23:33:13 +0000211 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
Mike Stump08920992009-03-07 02:35:30 +0000212 for (int i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000213 Types[i] = Elts[i]->getType();
Mike Stump08920992009-03-07 02:35:30 +0000214 Types[4] = PtrToInt8Ty;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000215
Mike Stumpa99038c2009-02-28 09:07:16 +0000216 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
217 const Expr *E = subBlockDeclRefDecls[i];
218 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
219 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000220 if (BDRE && BDRE->isByRef()) {
221 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
222 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
223 } else
224 Types[i+5] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000225 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000226
Mike Stump08920992009-03-07 02:35:30 +0000227 llvm::StructType *Ty = llvm::StructType::get(Types, true);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000228
229 llvm::AllocaInst *A = CreateTempAlloca(Ty);
230 A->setAlignment(subBlockAlign);
231 V = A;
232
Mike Stump08920992009-03-07 02:35:30 +0000233 std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
234 int helpersize = 0;
235
236 for (unsigned i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000237 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump00470a12009-03-05 08:32:30 +0000238
Mike Stump8a2b4b12009-02-25 23:33:13 +0000239 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
240 {
Mike Stumpa99038c2009-02-28 09:07:16 +0000241 // FIXME: Push const down.
242 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
243 DeclRefExpr *DR;
244 ValueDecl *VD;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000245
Mike Stumpa99038c2009-02-28 09:07:16 +0000246 DR = dyn_cast<DeclRefExpr>(E);
247 // Skip padding.
248 if (DR) continue;
249
250 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
251 VD = BDRE->getDecl();
252
Mike Stumpdab514f2009-03-04 03:23:46 +0000253 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stump08920992009-03-07 02:35:30 +0000254 NoteForHelper[helpersize].index = i+5;
255 NoteForHelper[helpersize].RequiresCopying = BlockRequiresCopying(VD->getType());
256 NoteForHelper[helpersize].flag
257 = VD->getType()->isBlockPointerType() ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT;
258
Mike Stumpa99038c2009-02-28 09:07:16 +0000259 if (LocalDeclMap[VD]) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000260 if (BDRE->isByRef()) {
Mike Stump08920992009-03-07 02:35:30 +0000261 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
Mike Stumpf4bc3122009-03-07 06:04:31 +0000262 // FIXME: Someone double check this.
263 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000264 const llvm::Type *Ty = Types[i+5];
265 llvm::Value *Loc = LocalDeclMap[VD];
266 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
267 Loc = Builder.CreateLoad(Loc, false);
268 Loc = Builder.CreateBitCast(Loc, Ty);
269 Builder.CreateStore(Loc, Addr);
Mike Stump08920992009-03-07 02:35:30 +0000270 ++helpersize;
Mike Stumpdab514f2009-03-04 03:23:46 +0000271 continue;
272 } else
273 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
274 VD->getType(), SourceLocation(),
275 false, false);
Mike Stumpa99038c2009-02-28 09:07:16 +0000276 }
Mike Stumpdab514f2009-03-04 03:23:46 +0000277 if (BDRE->isByRef()) {
Mike Stumpa8b60c92009-03-21 21:00:35 +0000278 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
279 // FIXME: Someone double check this.
280 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stumpa99038c2009-02-28 09:07:16 +0000281 E = new (getContext())
282 UnaryOperator(E, UnaryOperator::AddrOf,
283 getContext().getPointerType(E->getType()),
284 SourceLocation());
Mike Stumpdab514f2009-03-04 03:23:46 +0000285 }
Mike Stump08920992009-03-07 02:35:30 +0000286 ++helpersize;
Mike Stumpa99038c2009-02-28 09:07:16 +0000287
Mike Stumpa99038c2009-02-28 09:07:16 +0000288 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpdab514f2009-03-04 03:23:46 +0000289 if (r.isScalar()) {
290 llvm::Value *Loc = r.getScalarVal();
291 const llvm::Type *Ty = Types[i+5];
292 if (BDRE->isByRef()) {
Mike Stump58a85142009-03-04 22:48:06 +0000293 // E is now the address of the value field, instead, we want the
294 // address of the actual ByRef struct. We optimize this slightly
295 // compared to gcc by not grabbing the forwarding slot as this must
296 // be done during Block_copy for us, and we can postpone the work
297 // until then.
298 uint64_t offset = BlockDecls[BDRE->getDecl()];
Mike Stump00470a12009-03-05 08:32:30 +0000299
Mike Stump58a85142009-03-04 22:48:06 +0000300 llvm::Value *BlockLiteral = LoadBlockStruct();
Mike Stump00470a12009-03-05 08:32:30 +0000301
Mike Stump58a85142009-03-04 22:48:06 +0000302 Loc = Builder.CreateGEP(BlockLiteral,
303 llvm::ConstantInt::get(llvm::Type::Int64Ty,
304 offset),
305 "block.literal");
306 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000307 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stump58a85142009-03-04 22:48:06 +0000308 Loc = Builder.CreateLoad(Loc, false);
309 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000310 }
311 Builder.CreateStore(Loc, Addr);
312 } else if (r.isComplex())
Mike Stump8a2b4b12009-02-25 23:33:13 +0000313 // FIXME: implement
314 ErrorUnsupported(BE, "complex in block literal");
315 else if (r.isAggregate())
316 ; // Already created into the destination
317 else
318 assert (0 && "bad block variable");
319 // FIXME: Ensure that the offset created by the backend for
320 // the struct matches the previously computed offset in BlockDecls.
321 }
Mike Stump08920992009-03-07 02:35:30 +0000322 NoteForHelper.resize(helpersize);
Mike Stumpcf62d392009-03-06 18:42:23 +0000323
324 // __descriptor
Mike Stumpa803b0e2009-03-25 17:58:24 +0000325 llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
326 subBlockSize, Ty,
Mike Stump08920992009-03-07 02:35:30 +0000327 &NoteForHelper);
328 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
329 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpe5fee252009-02-13 16:19:19 +0000330 }
Mike Stump00470a12009-03-05 08:32:30 +0000331
Mike Stumpbd65cac2009-02-19 01:01:04 +0000332 QualType BPT = BE->getType();
Mike Stump8a2b4b12009-02-25 23:33:13 +0000333 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpe5fee252009-02-13 16:19:19 +0000334}
335
336
Mike Stump2a998142009-03-04 18:17:45 +0000337const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000338 if (BlockDescriptorType)
339 return BlockDescriptorType;
340
Mike Stumpa5448542009-02-13 15:32:32 +0000341 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000342 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000343
Mike Stumpab695142009-02-13 15:16:56 +0000344 // struct __block_descriptor {
345 // unsigned long reserved;
346 // unsigned long block_size;
347 // };
Mike Stumpa5448542009-02-13 15:32:32 +0000348 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
349 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000350 NULL);
351
352 getModule().addTypeName("struct.__block_descriptor",
353 BlockDescriptorType);
354
355 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000356}
357
Mike Stump2a998142009-03-04 18:17:45 +0000358const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000359 if (GenericBlockLiteralType)
360 return GenericBlockLiteralType;
361
Mike Stumpa5448542009-02-13 15:32:32 +0000362 const llvm::Type *BlockDescPtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000363 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000364
Mike Stump7cbb3602009-02-13 16:01:35 +0000365 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
366 getTypes().ConvertType(getContext().IntTy));
367
Mike Stump9b8a7972009-02-13 15:25:34 +0000368 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000369 // void *__isa;
370 // int __flags;
371 // int __reserved;
372 // void (*__invoke)(void *);
373 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000374 // };
Mike Stump797b6322009-03-05 01:23:13 +0000375 GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000376 IntTy,
377 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000378 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000379 BlockDescPtrTy,
380 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000381
Mike Stump9b8a7972009-02-13 15:25:34 +0000382 getModule().addTypeName("struct.__block_literal_generic",
383 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000384
Mike Stump9b8a7972009-02-13 15:25:34 +0000385 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000386}
387
Mike Stump2a998142009-03-04 18:17:45 +0000388const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000389 if (GenericExtendedBlockLiteralType)
390 return GenericExtendedBlockLiteralType;
391
Mike Stumpbd65cac2009-02-19 01:01:04 +0000392 const llvm::Type *BlockDescPtrTy =
393 llvm::PointerType::getUnqual(getBlockDescriptorType());
394
395 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
396 getTypes().ConvertType(getContext().IntTy));
397
398 // struct __block_literal_generic {
399 // void *__isa;
400 // int __flags;
401 // int __reserved;
402 // void (*__invoke)(void *);
403 // struct __block_descriptor *__descriptor;
404 // void *__copy_func_helper_decl;
405 // void *__destroy_func_decl;
406 // };
Mike Stump797b6322009-03-05 01:23:13 +0000407 GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000408 IntTy,
409 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000410 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000411 BlockDescPtrTy,
Mike Stump797b6322009-03-05 01:23:13 +0000412 PtrToInt8Ty,
413 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000414 NULL);
415
416 getModule().addTypeName("struct.__block_literal_extended_generic",
417 GenericExtendedBlockLiteralType);
418
419 return GenericExtendedBlockLiteralType;
420}
421
Mike Stumpa5448542009-02-13 15:32:32 +0000422/// getBlockFunctionType - Given a BlockPointerType, will return the
Anders Carlssonacfde802009-02-12 00:39:25 +0000423/// function type for the block, including the first block literal argument.
424static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlssond5cab542009-02-12 17:55:02 +0000425 const BlockPointerType *BPT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000426 const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
Mike Stumpa5448542009-02-13 15:32:32 +0000427
Anders Carlssonacfde802009-02-12 00:39:25 +0000428 llvm::SmallVector<QualType, 8> Types;
429 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000430
Douglas Gregor72564e72009-02-26 23:50:07 +0000431 for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000432 e = FTy->arg_type_end(); i != e; ++i)
433 Types.push_back(*i);
Mike Stumpa5448542009-02-13 15:32:32 +0000434
Anders Carlssonacfde802009-02-12 00:39:25 +0000435 return Ctx.getFunctionType(FTy->getResultType(),
Mike Stumpa5448542009-02-13 15:32:32 +0000436 &Types[0], Types.size(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000437 FTy->isVariadic(), 0);
438}
439
Anders Carlssond5cab542009-02-12 17:55:02 +0000440RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpa5448542009-02-13 15:32:32 +0000441 const BlockPointerType *BPT =
Anders Carlssonacfde802009-02-12 00:39:25 +0000442 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpa5448542009-02-13 15:32:32 +0000443
Anders Carlssonacfde802009-02-12 00:39:25 +0000444 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
445
446 // Get a pointer to the generic block literal.
447 const llvm::Type *BlockLiteralTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000448 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000449
450 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000451 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000452 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
453
454 // Get the function pointer from the literal.
455 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump20733cd2009-02-22 13:27:11 +0000456 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000457
458 // Cast the function pointer to the right type.
Mike Stumpa5448542009-02-13 15:32:32 +0000459 const llvm::Type *BlockFTy =
Anders Carlssonacfde802009-02-12 00:39:25 +0000460 ConvertType(getBlockFunctionType(getContext(), BPT));
461 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
462 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
463
Mike Stumpa5448542009-02-13 15:32:32 +0000464 BlockLiteral =
465 Builder.CreateBitCast(BlockLiteral,
Anders Carlssonacfde802009-02-12 00:39:25 +0000466 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
467 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000468
Anders Carlssonacfde802009-02-12 00:39:25 +0000469 // Add the block literal.
470 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
471 CallArgList Args;
472 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000473
Anders Carlssonacfde802009-02-12 00:39:25 +0000474 // And the rest of the arguments.
Mike Stumpa5448542009-02-13 15:32:32 +0000475 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssonacfde802009-02-12 00:39:25 +0000476 i != e; ++i)
Mike Stumpa5448542009-02-13 15:32:32 +0000477 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssonacfde802009-02-12 00:39:25 +0000478 i->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000479
Anders Carlssonacfde802009-02-12 00:39:25 +0000480 // And call the block.
Mike Stumpa5448542009-02-13 15:32:32 +0000481 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
Anders Carlssonacfde802009-02-12 00:39:25 +0000482 Func, Args);
483}
Anders Carlssond5cab542009-02-12 17:55:02 +0000484
Mike Stumpdab514f2009-03-04 03:23:46 +0000485llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
486 uint64_t &offset = BlockDecls[E->getDecl()];
487
488 const llvm::Type *Ty;
489 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
490
Mike Stump58919e12009-03-04 13:17:22 +0000491 if (!Enable__block && E->isByRef())
Mike Stumpdab514f2009-03-04 03:23:46 +0000492 ErrorUnsupported(E, "__block variable in block literal");
Mike Stumpa4f668f2009-03-06 01:33:24 +0000493 else if (!Enable__block && E->getType()->isBlockPointerType())
Mike Stumpdab514f2009-03-04 03:23:46 +0000494 ErrorUnsupported(E, "block pointer in block literal");
Mike Stump8e5d9f12009-03-07 14:53:10 +0000495 else if (!Enable__block && (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
496 getContext().isObjCNSObjectType(E->getType())))
Mike Stumpdab514f2009-03-04 03:23:46 +0000497 ErrorUnsupported(E, "__attribute__((NSObject)) variable in block "
498 "literal");
Mike Stumpa4f668f2009-03-06 01:33:24 +0000499 else if (!Enable__block && getContext().isObjCObjectPointerType(E->getType()))
Mike Stumpdab514f2009-03-04 03:23:46 +0000500 ErrorUnsupported(E, "Objective-C variable in block literal");
501
502 // See if we have already allocated an offset for this variable.
503 if (offset == 0) {
Mike Stump00470a12009-03-05 08:32:30 +0000504 // Don't run the expensive check, unless we have to.
505 if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
506 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000507 // if not, allocate one now.
508 offset = getBlockOffset(E);
509 }
510
511 llvm::Value *BlockLiteral = LoadBlockStruct();
512 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
513 llvm::ConstantInt::get(llvm::Type::Int64Ty,
514 offset),
Mike Stump58a85142009-03-04 22:48:06 +0000515 "block.literal");
Mike Stumpdab514f2009-03-04 03:23:46 +0000516 if (E->isByRef()) {
517 bool needsCopyDispose = BlockRequiresCopying(E->getType());
518 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
519 const llvm::Type *PtrStructTy
520 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
Mike Stumpa8b60c92009-03-21 21:00:35 +0000521 // The block literal will need a copy/destroy helper.
522 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000523 Ty = PtrStructTy;
524 Ty = llvm::PointerType::get(Ty, 0);
525 V = Builder.CreateBitCast(V, Ty);
526 V = Builder.CreateLoad(V, false);
527 V = Builder.CreateStructGEP(V, 1, "forwarding");
528 V = Builder.CreateLoad(V, false);
529 V = Builder.CreateBitCast(V, PtrStructTy);
530 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
531 } else {
532 Ty = llvm::PointerType::get(Ty, 0);
533 V = Builder.CreateBitCast(V, Ty);
534 }
535 return V;
536}
537
Mike Stump6cc88f72009-03-20 21:53:12 +0000538void CodeGenFunction::BlockForwardSelf() {
539 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
540 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
541 llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
542 if (DMEntry)
543 return;
544 // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
545 BlockDeclRefExpr *BDRE = new (getContext())
546 BlockDeclRefExpr(SelfDecl,
547 SelfDecl->getType(), SourceLocation(), false);
548 DMEntry = GetAddrOfBlockDecl(BDRE);
549}
550
Mike Stump67a64482009-02-14 22:16:35 +0000551llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000552BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000553 // Generate the block descriptor.
554 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000555 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
556 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000557
Anders Carlssond5cab542009-02-12 17:55:02 +0000558 llvm::Constant *DescriptorFields[2];
Mike Stumpa5448542009-02-13 15:32:32 +0000559
Anders Carlssond5cab542009-02-12 17:55:02 +0000560 // Reserved
561 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000562
Anders Carlssond5cab542009-02-12 17:55:02 +0000563 // Block literal size. For global blocks we just use the size of the generic
564 // block literal struct.
Mike Stumpa5448542009-02-13 15:32:32 +0000565 uint64_t BlockLiteralSize =
Mike Stump9b8a7972009-02-13 15:25:34 +0000566 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlssond5cab542009-02-12 17:55:02 +0000567 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpa5448542009-02-13 15:32:32 +0000568
569 llvm::Constant *DescriptorStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000570 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpa5448542009-02-13 15:32:32 +0000571
Anders Carlssond5cab542009-02-12 17:55:02 +0000572 llvm::GlobalVariable *Descriptor =
573 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000574 llvm::GlobalVariable::InternalLinkage,
575 DescriptorStruct, "__block_descriptor_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000576 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000577
Anders Carlssond5cab542009-02-12 17:55:02 +0000578 // Generate the constants for the block literal.
579 llvm::Constant *LiteralFields[5];
Mike Stumpa5448542009-02-13 15:32:32 +0000580
Mike Stump67a64482009-02-14 22:16:35 +0000581 CodeGenFunction::BlockInfo Info(0, n);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000582 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000583 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Daniel Dunbard67b09a2009-03-12 03:07:24 +0000584 bool subBlockHasCopyDispose = false;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000585 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000586 llvm::Function *Fn
Mike Stump6cc88f72009-03-20 21:53:12 +0000587 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000588 subBlockSize,
Mike Stump90a90432009-03-04 18:47:42 +0000589 subBlockAlign,
Mike Stump00470a12009-03-05 08:32:30 +0000590 subBlockDeclRefDecls,
591 subBlockHasCopyDispose);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000592 assert(subBlockSize == BlockLiteralSize
593 && "no imports allowed for global block");
Daniel Dunbard67b09a2009-03-12 03:07:24 +0000594 assert(!subBlockHasCopyDispose && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000595
Anders Carlssond5cab542009-02-12 17:55:02 +0000596 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000597 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000598
Anders Carlssond5cab542009-02-12 17:55:02 +0000599 // Flags
Mike Stump00470a12009-03-05 08:32:30 +0000600 LiteralFields[1] =
Anders Carlsson8045ee02009-03-01 21:09:29 +0000601 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpa5448542009-02-13 15:32:32 +0000602
Anders Carlssond5cab542009-02-12 17:55:02 +0000603 // Reserved
Mike Stump7cbb3602009-02-13 16:01:35 +0000604 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000605
Anders Carlssond5cab542009-02-12 17:55:02 +0000606 // Function
607 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000608
Anders Carlssond5cab542009-02-12 17:55:02 +0000609 // Descriptor
610 LiteralFields[4] = Descriptor;
Mike Stumpa5448542009-02-13 15:32:32 +0000611
612 llvm::Constant *BlockLiteralStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000613 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpa5448542009-02-13 15:32:32 +0000614
615 llvm::GlobalVariable *BlockLiteral =
Anders Carlssond5cab542009-02-12 17:55:02 +0000616 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000617 llvm::GlobalVariable::InternalLinkage,
618 BlockLiteralStruct, "__block_literal_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000619 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000620
Anders Carlssond5cab542009-02-12 17:55:02 +0000621 return BlockLiteral;
622}
623
Mike Stump4e7a1f72009-02-21 20:00:35 +0000624llvm::Value *CodeGenFunction::LoadBlockStruct() {
625 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
626}
627
Mike Stump00470a12009-03-05 08:32:30 +0000628llvm::Function *
629CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
630 const BlockInfo& Info,
Mike Stump6cc88f72009-03-20 21:53:12 +0000631 const Decl *OuterFuncDecl,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000632 llvm::DenseMap<const Decl*, llvm::Value*> ldm,
Mike Stump00470a12009-03-05 08:32:30 +0000633 uint64_t &Size,
634 uint64_t &Align,
635 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
636 bool &subBlockHasCopyDispose) {
Mike Stump7f28a9c2009-03-13 23:34:28 +0000637 // Arrange for local static and local extern declarations to appear
638 // to be local to this function as well, as they are directly referenced
639 // in a block.
640 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
641 i != ldm.end();
642 ++i) {
643 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
644
645 if (VD->getStorageClass() == VarDecl::Static
646 || VD->getStorageClass() == VarDecl::Extern)
647 LocalDeclMap[VD] = i->second;
648 }
649
Douglas Gregor72564e72009-02-26 23:50:07 +0000650 const FunctionProtoType *FTy =
Chris Lattner161d36d2009-02-28 19:01:03 +0000651 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpa5448542009-02-13 15:32:32 +0000652
Anders Carlssond5cab542009-02-12 17:55:02 +0000653 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000654
Chris Lattner161d36d2009-02-28 19:01:03 +0000655 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000656
657 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000658 ImplicitParamDecl *SelfDecl =
Anders Carlssond5cab542009-02-12 17:55:02 +0000659 ImplicitParamDecl::Create(getContext(), 0,
660 SourceLocation(), 0,
661 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000662
Anders Carlssond5cab542009-02-12 17:55:02 +0000663 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000664 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000665
Steve Naroffe78b8092009-03-13 16:56:44 +0000666 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000667 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000668 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000669
670 const CGFunctionInfo &FI =
Anders Carlssond5cab542009-02-12 17:55:02 +0000671 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
672
Mike Stump67a64482009-02-14 22:16:35 +0000673 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlssond5cab542009-02-12 17:55:02 +0000674 CodeGenTypes &Types = CGM.getTypes();
675 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000676
677 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000678 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
679 Name,
680 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000681
682 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000683 BExpr->getBody()->getLocEnd());
Mike Stump6cc88f72009-03-20 21:53:12 +0000684 CurFuncDecl = OuterFuncDecl;
Chris Lattner161d36d2009-02-28 19:01:03 +0000685 EmitStmt(BExpr->getBody());
686 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000687
Mike Stump8a2b4b12009-02-25 23:33:13 +0000688 // The runtime needs a minimum alignment of a void *.
689 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
690 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
691
Mike Stump4e7a1f72009-02-21 20:00:35 +0000692 Size = BlockOffset;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000693 Align = BlockAlign;
694 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump00470a12009-03-05 08:32:30 +0000695 subBlockHasCopyDispose |= BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000696 return Fn;
697}
Mike Stumpa99038c2009-02-28 09:07:16 +0000698
Mike Stump08920992009-03-07 02:35:30 +0000699uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000700 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
701
702 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
703 uint64_t Align = getContext().getDeclAlignInBytes(D);
704
705 if (BDRE->isByRef()) {
706 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
707 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
708 }
709
710 assert ((Align > 0) && "alignment must be 1 byte or more");
711
712 uint64_t OldOffset = BlockOffset;
713
714 // Ensure proper alignment, even if it means we have to have a gap
715 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
716 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000717
Mike Stumpa99038c2009-02-28 09:07:16 +0000718 uint64_t Pad = BlockOffset - OldOffset;
719 if (Pad) {
720 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
721 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
722 llvm::APInt(32, Pad),
723 ArrayType::Normal, 0);
724 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
725 0, QualType(PadTy), VarDecl::None,
726 SourceLocation());
727 Expr *E;
728 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
729 SourceLocation(), false, false);
730 BlockDeclRefDecls.push_back(E);
731 }
732 BlockDeclRefDecls.push_back(BDRE);
733
734 BlockOffset += Size;
735 return BlockOffset-Size;
736}
Mike Stumpdab514f2009-03-04 03:23:46 +0000737
Mike Stump08920992009-03-07 02:35:30 +0000738llvm::Constant *BlockFunction::
739GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
740 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000741 QualType R = getContext().VoidTy;
742
743 FunctionArgList Args;
744 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000745 ImplicitParamDecl *Dst =
746 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
747 getContext().getPointerType(getContext().VoidTy));
748 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000749 ImplicitParamDecl *Src =
750 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
751 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000752 Args.push_back(std::make_pair(Src, Src->getType()));
753
754 const CGFunctionInfo &FI =
755 CGM.getTypes().getFunctionInfo(R, Args);
756
757 std::string Name = std::string("__copy_helper_block_");
758 CodeGenTypes &Types = CGM.getTypes();
759 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
760
761 llvm::Function *Fn =
762 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
763 Name,
764 &CGM.getModule());
765
766 IdentifierInfo *II
767 = &CGM.getContext().Idents.get("__copy_helper_block_");
768
769 FunctionDecl *FD = FunctionDecl::Create(getContext(),
770 getContext().getTranslationUnitDecl(),
771 SourceLocation(), II, R,
772 FunctionDecl::Static, false,
773 true);
774 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000775
776 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
777 llvm::Type *PtrPtrT;
778 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
779 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
780 SrcObj = Builder.CreateLoad(SrcObj);
781
782 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
783 DstObj = Builder.CreateBitCast(DstObj, llvm::PointerType::get(T, 0));
784
785 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
786 int flag = NoteForHelper[i].flag;
787 int index = NoteForHelper[i].index;
788
789 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
790 || NoteForHelper[i].RequiresCopying) {
791 llvm::Value *Srcv = SrcObj;
792 Srcv = Builder.CreateStructGEP(Srcv, index);
793 Srcv = Builder.CreateBitCast(Srcv,
794 llvm::PointerType::get(PtrToInt8Ty, 0));
795 Srcv = Builder.CreateLoad(Srcv);
796
797 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
798 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
799
800 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
801 llvm::Value *F = getBlockObjectAssign();
802 Builder.CreateCall3(F, Dstv, Srcv, N);
803 }
804 }
805
Mike Stumpa4f668f2009-03-06 01:33:24 +0000806 CGF.FinishFunction();
807
808 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000809}
810
Mike Stumpcf62d392009-03-06 18:42:23 +0000811llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +0000812GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
813 const llvm::StructType* T,
814 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000815 QualType R = getContext().VoidTy;
816
817 FunctionArgList Args;
818 // FIXME: This leaks
819 ImplicitParamDecl *Src =
820 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
821 getContext().getPointerType(getContext().VoidTy));
822
823 Args.push_back(std::make_pair(Src, Src->getType()));
824
825 const CGFunctionInfo &FI =
826 CGM.getTypes().getFunctionInfo(R, Args);
827
828 std::string Name = std::string("__destroy_helper_block_");
829 CodeGenTypes &Types = CGM.getTypes();
830 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
831
832 llvm::Function *Fn =
833 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
834 Name,
835 &CGM.getModule());
836
837 IdentifierInfo *II
838 = &CGM.getContext().Idents.get("__destroy_helper_block_");
839
840 FunctionDecl *FD = FunctionDecl::Create(getContext(),
841 getContext().getTranslationUnitDecl(),
842 SourceLocation(), II, R,
843 FunctionDecl::Static, false,
844 true);
845 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +0000846
847 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
848 llvm::Type *PtrPtrT;
849 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
850 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
851 SrcObj = Builder.CreateLoad(SrcObj);
852
853 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
854 int flag = NoteForHelper[i].flag;
855 int index = NoteForHelper[i].index;
856
857 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
858 || NoteForHelper[i].RequiresCopying) {
859 llvm::Value *Srcv = SrcObj;
860 Srcv = Builder.CreateStructGEP(Srcv, index);
861 Srcv = Builder.CreateBitCast(Srcv,
862 llvm::PointerType::get(PtrToInt8Ty, 0));
863 Srcv = Builder.CreateLoad(Srcv);
864
865 BuildBlockRelease(Srcv, flag);
866 }
867 }
868
Mike Stumpa4f668f2009-03-06 01:33:24 +0000869 CGF.FinishFunction();
870
871 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
872}
873
Mike Stump08920992009-03-07 02:35:30 +0000874llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
875 std::vector<HelperInfo> &NoteForHelper) {
876 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
877 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +0000878}
879
Mike Stump08920992009-03-07 02:35:30 +0000880llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
881 std::vector<HelperInfo> &NoteForHelper) {
882 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
883 T, NoteForHelper);
Mike Stumpdab514f2009-03-04 03:23:46 +0000884}
Mike Stump797b6322009-03-05 01:23:13 +0000885
Mike Stumpee094222009-03-06 06:12:24 +0000886llvm::Constant *BlockFunction::
887GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000888 QualType R = getContext().VoidTy;
889
890 FunctionArgList Args;
891 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +0000892 ImplicitParamDecl *Dst =
893 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
894 getContext().getPointerType(getContext().VoidTy));
895 Args.push_back(std::make_pair(Dst, Dst->getType()));
896
897 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +0000898 ImplicitParamDecl *Src =
899 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
900 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +0000901 Args.push_back(std::make_pair(Src, Src->getType()));
902
903 const CGFunctionInfo &FI =
904 CGM.getTypes().getFunctionInfo(R, Args);
905
906 std::string Name = std::string("__Block_byref_id_object_copy_");
907 CodeGenTypes &Types = CGM.getTypes();
908 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
909
910 llvm::Function *Fn =
911 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
912 Name,
913 &CGM.getModule());
914
915 IdentifierInfo *II
916 = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
917
918 FunctionDecl *FD = FunctionDecl::Create(getContext(),
919 getContext().getTranslationUnitDecl(),
920 SourceLocation(), II, R,
921 FunctionDecl::Static, false,
922 true);
923 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stumpee094222009-03-06 06:12:24 +0000924
925 // dst->x
926 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
927 V = Builder.CreateBitCast(V, T);
928 V = Builder.CreateStructGEP(V, 6, "x");
929 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
930
931 // src->x
932 V = CGF.GetAddrOfLocalVar(Src);
933 V = Builder.CreateLoad(V);
934 V = Builder.CreateBitCast(V, T);
935 V = Builder.CreateStructGEP(V, 6, "x");
936 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
937 llvm::Value *SrcObj = Builder.CreateLoad(V);
938
939 flag |= BLOCK_BYREF_CALLER;
940
941 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
942 llvm::Value *F = getBlockObjectAssign();
943 Builder.CreateCall3(F, DstObj, SrcObj, N);
944
Mike Stump45031c02009-03-06 02:29:21 +0000945 CGF.FinishFunction();
946
947 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
948}
949
Mike Stump1851b682009-03-06 04:53:30 +0000950llvm::Constant *
951BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
952 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000953 QualType R = getContext().VoidTy;
954
955 FunctionArgList Args;
956 // FIXME: This leaks
957 ImplicitParamDecl *Src =
958 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
959 getContext().getPointerType(getContext().VoidTy));
960
961 Args.push_back(std::make_pair(Src, Src->getType()));
962
963 const CGFunctionInfo &FI =
964 CGM.getTypes().getFunctionInfo(R, Args);
965
966 std::string Name = std::string("__Block_byref_id_object_dispose_");
967 CodeGenTypes &Types = CGM.getTypes();
968 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
969
970 llvm::Function *Fn =
971 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
972 Name,
973 &CGM.getModule());
974
975 IdentifierInfo *II
976 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
977
978 FunctionDecl *FD = FunctionDecl::Create(getContext(),
979 getContext().getTranslationUnitDecl(),
980 SourceLocation(), II, R,
981 FunctionDecl::Static, false,
982 true);
983 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +0000984
985 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
986 V = Builder.CreateBitCast(V, T);
987 V = Builder.CreateStructGEP(V, 6, "x");
988 V = Builder.CreateBitCast(V, PtrToInt8Ty);
989
Mike Stump1851b682009-03-06 04:53:30 +0000990 flag |= BLOCK_BYREF_CALLER;
991 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000992 CGF.FinishFunction();
993
994 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
995}
996
Mike Stumpee094222009-03-06 06:12:24 +0000997llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
998 int flag) {
999 return CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +00001000}
1001
Mike Stump1851b682009-03-06 04:53:30 +00001002llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1003 int flag) {
1004 return CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +00001005}
1006
Mike Stump797b6322009-03-05 01:23:13 +00001007llvm::Value *BlockFunction::getBlockObjectDispose() {
1008 if (CGM.BlockObjectDispose == 0) {
1009 const llvm::FunctionType *FTy;
1010 std::vector<const llvm::Type*> ArgTys;
1011 const llvm::Type *ResultType = llvm::Type::VoidTy;
1012 ArgTys.push_back(PtrToInt8Ty);
1013 ArgTys.push_back(llvm::Type::Int32Ty);
1014 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump00470a12009-03-05 08:32:30 +00001015 CGM.BlockObjectDispose
Mike Stump797b6322009-03-05 01:23:13 +00001016 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1017 }
1018 return CGM.BlockObjectDispose;
1019}
1020
Mike Stumpee094222009-03-06 06:12:24 +00001021llvm::Value *BlockFunction::getBlockObjectAssign() {
1022 if (CGM.BlockObjectAssign == 0) {
1023 const llvm::FunctionType *FTy;
1024 std::vector<const llvm::Type*> ArgTys;
1025 const llvm::Type *ResultType = llvm::Type::VoidTy;
1026 ArgTys.push_back(PtrToInt8Ty);
1027 ArgTys.push_back(PtrToInt8Ty);
1028 ArgTys.push_back(llvm::Type::Int32Ty);
1029 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1030 CGM.BlockObjectAssign
1031 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1032 }
1033 return CGM.BlockObjectAssign;
1034}
1035
Mike Stump1851b682009-03-06 04:53:30 +00001036void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump797b6322009-03-05 01:23:13 +00001037 llvm::Value *F = getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001038 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001039 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump1851b682009-03-06 04:53:30 +00001040 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
Mike Stump797b6322009-03-05 01:23:13 +00001041 Builder.CreateCall2(F, V, N);
1042}
Mike Stump00470a12009-03-05 08:32:30 +00001043
1044ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001045
1046BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1047 CGBuilderTy &B)
1048 : CGM(cgm), CGF(cgf), Builder(B) {
1049 PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1050
1051 BlockHasCopyDispose = false;
1052}