blob: c233ff38545f18f53b6fd3a64646105468846388 [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 Stump08920992009-03-07 02:35:30 +000038BuildDescriptorBlockDecl(uint64_t Size, const llvm::StructType* Ty,
39 std::vector<HelperInfo> *NoteForHelper) {
Mike Stump56129b12009-02-13 16:55:51 +000040 const llvm::Type *UnsignedLongTy
41 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000042 llvm::Constant *C;
43 std::vector<llvm::Constant*> Elts;
44
45 // reserved
Mike Stump56129b12009-02-13 16:55:51 +000046 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000047 Elts.push_back(C);
48
49 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000050 // FIXME: What is the right way to say this doesn't fit? We should give
51 // a user diagnostic in that case. Better fix would be to change the
52 // API to size_t.
Mike Stump4e7a1f72009-02-21 20:00:35 +000053 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpe5fee252009-02-13 16:19:19 +000054 Elts.push_back(C);
55
56 if (BlockHasCopyDispose) {
57 // copy_func_helper_decl
Mike Stump08920992009-03-07 02:35:30 +000058 Elts.push_back(BuildCopyHelper(Ty, *NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000059
60 // destroy_func_decl
Mike Stump08920992009-03-07 02:35:30 +000061 Elts.push_back(BuildDestroyHelper(Ty, *NoteForHelper));
Mike Stumpe5fee252009-02-13 16:19:19 +000062 }
63
64 C = llvm::ConstantStruct::get(Elts);
65
Mike Stumpe5fee252009-02-13 16:19:19 +000066 C = new llvm::GlobalVariable(C->getType(), true,
67 llvm::GlobalValue::InternalLinkage,
Mike Stump7d6dc4f2009-02-13 20:17:16 +000068 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpe5fee252009-02-13 16:19:19 +000069 return C;
70}
71
Mike Stump2a998142009-03-04 18:17:45 +000072llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Mike Stumpf99f1d02009-02-13 17:23:42 +000073 if (NSConcreteGlobalBlock)
74 return NSConcreteGlobalBlock;
75
Mike Stumpf7448952009-02-13 19:38:12 +000076 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000077 // same thing as CreateRuntimeFunction if there's already a variable with the
78 // same name.
Mike Stumpf99f1d02009-02-13 17:23:42 +000079 NSConcreteGlobalBlock
Mike Stump00470a12009-03-05 08:32:30 +000080 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stumpf99f1d02009-02-13 17:23:42 +000081 llvm::GlobalValue::ExternalLinkage,
82 0, "_NSConcreteGlobalBlock",
83 &getModule());
84
85 return NSConcreteGlobalBlock;
86}
87
Mike Stump2a998142009-03-04 18:17:45 +000088llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Mike Stump59c5b112009-02-13 19:29:27 +000089 if (NSConcreteStackBlock)
90 return NSConcreteStackBlock;
91
Mike Stumpf7448952009-02-13 19:38:12 +000092 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000093 // same thing as CreateRuntimeFunction if there's already a variable with the
94 // same name.
Mike Stump59c5b112009-02-13 19:29:27 +000095 NSConcreteStackBlock
Mike Stump00470a12009-03-05 08:32:30 +000096 = new llvm::GlobalVariable(PtrToInt8Ty, false,
Mike Stump59c5b112009-02-13 19:29:27 +000097 llvm::GlobalValue::ExternalLinkage,
98 0, "_NSConcreteStackBlock",
99 &getModule());
100
101 return NSConcreteStackBlock;
102}
103
Mike Stump00470a12009-03-05 08:32:30 +0000104static void CollectBlockDeclRefInfo(const Stmt *S,
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000105 CodeGenFunction::BlockInfo &Info) {
106 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
107 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000108 if (*I)
109 CollectBlockDeclRefInfo(*I, Info);
Mike Stump00470a12009-03-05 08:32:30 +0000110
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000111 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
112 // FIXME: Handle enums.
113 if (isa<FunctionDecl>(DE->getDecl()))
114 return;
Mike Stump00470a12009-03-05 08:32:30 +0000115
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000116 if (DE->isByRef())
117 Info.ByRefDeclRefs.push_back(DE);
118 else
119 Info.ByCopyDeclRefs.push_back(DE);
120 }
121}
122
Mike Stump58a85142009-03-04 22:48:06 +0000123/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
124/// declared as a global variable instead of on the stack.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000125static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
126{
127 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
128}
129
Mike Stump58a85142009-03-04 22:48:06 +0000130// FIXME: Push most into CGM, passing down a few bits, like current function
131// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000132llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpe5fee252009-02-13 16:19:19 +0000133
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000134 std::string Name = CurFn->getName();
135 CodeGenFunction::BlockInfo Info(0, Name.c_str());
136 CollectBlockDeclRefInfo(BE->getBody(), Info);
137
138 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000139 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
140 // to just have one code path. We should move this function into CGM and pass
141 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000142 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000143 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
Mike Stump00470a12009-03-05 08:32:30 +0000144
145 std::vector<llvm::Constant*> Elts(5);
Mike Stumpe5fee252009-02-13 16:19:19 +0000146 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000147 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000148
Mike Stumpe5fee252009-02-13 16:19:19 +0000149 {
150 // C = BuildBlockStructInitlist();
151 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
152
Mike Stump00470a12009-03-05 08:32:30 +0000153 // We run this first so that we set BlockHasCopyDispose from the entire
154 // block literal.
155 // __invoke
156 uint64_t subBlockSize, subBlockAlign;
157 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
158 llvm::Function *Fn
Mike Stump6cc88f72009-03-20 21:53:12 +0000159 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl, LocalDeclMap,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000160 subBlockSize,
Mike Stump00470a12009-03-05 08:32:30 +0000161 subBlockAlign,
162 subBlockDeclRefDecls,
163 BlockHasCopyDispose);
164 Elts[3] = Fn;
165
166 if (!Enable__block && BlockHasCopyDispose)
167 ErrorUnsupported(BE, "block literal that requires copy/dispose");
168
Mike Stumpe5fee252009-02-13 16:19:19 +0000169 if (BlockHasCopyDispose)
170 flags |= BLOCK_HAS_COPY_DISPOSE;
171
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000172 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000173 C = CGM.getNSConcreteStackBlock();
Mike Stumpe5fee252009-02-13 16:19:19 +0000174 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
Mike Stump00470a12009-03-05 08:32:30 +0000175 Elts[0] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000176
177 // __flags
178 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
179 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
180 C = llvm::ConstantInt::get(IntTy, flags);
Mike Stump00470a12009-03-05 08:32:30 +0000181 Elts[1] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000182
183 // __reserved
184 C = llvm::ConstantInt::get(IntTy, 0);
Mike Stump00470a12009-03-05 08:32:30 +0000185 Elts[2] = C;
Mike Stumpe5fee252009-02-13 16:19:19 +0000186
Mike Stump8a2b4b12009-02-25 23:33:13 +0000187 if (subBlockDeclRefDecls.size() == 0) {
Mike Stumpcf62d392009-03-06 18:42:23 +0000188 // __descriptor
Mike Stump08920992009-03-07 02:35:30 +0000189 Elts[4] = BuildDescriptorBlockDecl(subBlockSize, 0, 0);
Mike Stumpcf62d392009-03-06 18:42:23 +0000190
Mike Stump5570cfe2009-03-01 20:07:53 +0000191 // Optimize to being a global block.
192 Elts[0] = CGM.getNSConcreteGlobalBlock();
193 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
194
Mike Stump8a2b4b12009-02-25 23:33:13 +0000195 C = llvm::ConstantStruct::get(Elts);
196
197 char Name[32];
198 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
199 C = new llvm::GlobalVariable(C->getType(), true,
200 llvm::GlobalValue::InternalLinkage,
201 C, Name, &CGM.getModule());
202 QualType BPT = BE->getType();
203 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
204 return C;
205 }
Mike Stump00470a12009-03-05 08:32:30 +0000206
Mike Stump8a2b4b12009-02-25 23:33:13 +0000207 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
Mike Stump08920992009-03-07 02:35:30 +0000208 for (int i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000209 Types[i] = Elts[i]->getType();
Mike Stump08920992009-03-07 02:35:30 +0000210 Types[4] = PtrToInt8Ty;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000211
Mike Stumpa99038c2009-02-28 09:07:16 +0000212 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
213 const Expr *E = subBlockDeclRefDecls[i];
214 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
215 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000216 if (BDRE && BDRE->isByRef()) {
217 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
218 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
219 } else
220 Types[i+5] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000221 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000222
Mike Stump08920992009-03-07 02:35:30 +0000223 llvm::StructType *Ty = llvm::StructType::get(Types, true);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000224
225 llvm::AllocaInst *A = CreateTempAlloca(Ty);
226 A->setAlignment(subBlockAlign);
227 V = A;
228
Mike Stump08920992009-03-07 02:35:30 +0000229 std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
230 int helpersize = 0;
231
232 for (unsigned i=0; i<4; ++i)
Mike Stump8a2b4b12009-02-25 23:33:13 +0000233 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
Mike Stump00470a12009-03-05 08:32:30 +0000234
Mike Stump8a2b4b12009-02-25 23:33:13 +0000235 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
236 {
Mike Stumpa99038c2009-02-28 09:07:16 +0000237 // FIXME: Push const down.
238 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
239 DeclRefExpr *DR;
240 ValueDecl *VD;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000241
Mike Stumpa99038c2009-02-28 09:07:16 +0000242 DR = dyn_cast<DeclRefExpr>(E);
243 // Skip padding.
244 if (DR) continue;
245
246 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
247 VD = BDRE->getDecl();
248
Mike Stumpdab514f2009-03-04 03:23:46 +0000249 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stump08920992009-03-07 02:35:30 +0000250 NoteForHelper[helpersize].index = i+5;
251 NoteForHelper[helpersize].RequiresCopying = BlockRequiresCopying(VD->getType());
252 NoteForHelper[helpersize].flag
253 = VD->getType()->isBlockPointerType() ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT;
254
Mike Stumpa99038c2009-02-28 09:07:16 +0000255 if (LocalDeclMap[VD]) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000256 if (BDRE->isByRef()) {
Mike Stump08920992009-03-07 02:35:30 +0000257 // FIXME: For only local, or all byrefs?
258 NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
Mike Stumpf4bc3122009-03-07 06:04:31 +0000259 // FIXME: Someone double check this.
260 (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000261 const llvm::Type *Ty = Types[i+5];
262 llvm::Value *Loc = LocalDeclMap[VD];
263 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
264 Loc = Builder.CreateLoad(Loc, false);
265 Loc = Builder.CreateBitCast(Loc, Ty);
266 Builder.CreateStore(Loc, Addr);
Mike Stump08920992009-03-07 02:35:30 +0000267 ++helpersize;
Mike Stumpdab514f2009-03-04 03:23:46 +0000268 continue;
269 } else
270 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
271 VD->getType(), SourceLocation(),
272 false, false);
Mike Stumpa99038c2009-02-28 09:07:16 +0000273 }
Mike Stumpdab514f2009-03-04 03:23:46 +0000274 if (BDRE->isByRef()) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000275 E = new (getContext())
276 UnaryOperator(E, UnaryOperator::AddrOf,
277 getContext().getPointerType(E->getType()),
278 SourceLocation());
Mike Stumpdab514f2009-03-04 03:23:46 +0000279 }
Mike Stump08920992009-03-07 02:35:30 +0000280 ++helpersize;
Mike Stumpa99038c2009-02-28 09:07:16 +0000281
Mike Stumpa99038c2009-02-28 09:07:16 +0000282 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpdab514f2009-03-04 03:23:46 +0000283 if (r.isScalar()) {
284 llvm::Value *Loc = r.getScalarVal();
285 const llvm::Type *Ty = Types[i+5];
286 if (BDRE->isByRef()) {
Mike Stump58a85142009-03-04 22:48:06 +0000287 // E is now the address of the value field, instead, we want the
288 // address of the actual ByRef struct. We optimize this slightly
289 // compared to gcc by not grabbing the forwarding slot as this must
290 // be done during Block_copy for us, and we can postpone the work
291 // until then.
292 uint64_t offset = BlockDecls[BDRE->getDecl()];
Mike Stump00470a12009-03-05 08:32:30 +0000293
Mike Stump58a85142009-03-04 22:48:06 +0000294 llvm::Value *BlockLiteral = LoadBlockStruct();
Mike Stump00470a12009-03-05 08:32:30 +0000295
Mike Stump58a85142009-03-04 22:48:06 +0000296 Loc = Builder.CreateGEP(BlockLiteral,
297 llvm::ConstantInt::get(llvm::Type::Int64Ty,
298 offset),
299 "block.literal");
300 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000301 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stump58a85142009-03-04 22:48:06 +0000302 Loc = Builder.CreateLoad(Loc, false);
303 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000304 }
305 Builder.CreateStore(Loc, Addr);
306 } else if (r.isComplex())
Mike Stump8a2b4b12009-02-25 23:33:13 +0000307 // FIXME: implement
308 ErrorUnsupported(BE, "complex in block literal");
309 else if (r.isAggregate())
310 ; // Already created into the destination
311 else
312 assert (0 && "bad block variable");
313 // FIXME: Ensure that the offset created by the backend for
314 // the struct matches the previously computed offset in BlockDecls.
315 }
Mike Stump08920992009-03-07 02:35:30 +0000316 NoteForHelper.resize(helpersize);
Mike Stumpcf62d392009-03-06 18:42:23 +0000317
318 // __descriptor
Mike Stump08920992009-03-07 02:35:30 +0000319 llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockSize, Ty,
320 &NoteForHelper);
321 Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
322 Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
Mike Stumpe5fee252009-02-13 16:19:19 +0000323 }
Mike Stump00470a12009-03-05 08:32:30 +0000324
Mike Stumpbd65cac2009-02-19 01:01:04 +0000325 QualType BPT = BE->getType();
Mike Stump8a2b4b12009-02-25 23:33:13 +0000326 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpe5fee252009-02-13 16:19:19 +0000327}
328
329
Mike Stump2a998142009-03-04 18:17:45 +0000330const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000331 if (BlockDescriptorType)
332 return BlockDescriptorType;
333
Mike Stumpa5448542009-02-13 15:32:32 +0000334 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000335 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000336
Mike Stumpab695142009-02-13 15:16:56 +0000337 // struct __block_descriptor {
338 // unsigned long reserved;
339 // unsigned long block_size;
340 // };
Mike Stumpa5448542009-02-13 15:32:32 +0000341 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
342 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000343 NULL);
344
345 getModule().addTypeName("struct.__block_descriptor",
346 BlockDescriptorType);
347
348 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000349}
350
Mike Stump2a998142009-03-04 18:17:45 +0000351const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000352 if (GenericBlockLiteralType)
353 return GenericBlockLiteralType;
354
Mike Stumpa5448542009-02-13 15:32:32 +0000355 const llvm::Type *BlockDescPtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000356 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000357
Mike Stump7cbb3602009-02-13 16:01:35 +0000358 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
359 getTypes().ConvertType(getContext().IntTy));
360
Mike Stump9b8a7972009-02-13 15:25:34 +0000361 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000362 // void *__isa;
363 // int __flags;
364 // int __reserved;
365 // void (*__invoke)(void *);
366 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000367 // };
Mike Stump797b6322009-03-05 01:23:13 +0000368 GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000369 IntTy,
370 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000371 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000372 BlockDescPtrTy,
373 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000374
Mike Stump9b8a7972009-02-13 15:25:34 +0000375 getModule().addTypeName("struct.__block_literal_generic",
376 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000377
Mike Stump9b8a7972009-02-13 15:25:34 +0000378 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000379}
380
Mike Stump2a998142009-03-04 18:17:45 +0000381const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000382 if (GenericExtendedBlockLiteralType)
383 return GenericExtendedBlockLiteralType;
384
Mike Stumpbd65cac2009-02-19 01:01:04 +0000385 const llvm::Type *BlockDescPtrTy =
386 llvm::PointerType::getUnqual(getBlockDescriptorType());
387
388 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
389 getTypes().ConvertType(getContext().IntTy));
390
391 // struct __block_literal_generic {
392 // void *__isa;
393 // int __flags;
394 // int __reserved;
395 // void (*__invoke)(void *);
396 // struct __block_descriptor *__descriptor;
397 // void *__copy_func_helper_decl;
398 // void *__destroy_func_decl;
399 // };
Mike Stump797b6322009-03-05 01:23:13 +0000400 GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000401 IntTy,
402 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000403 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000404 BlockDescPtrTy,
Mike Stump797b6322009-03-05 01:23:13 +0000405 PtrToInt8Ty,
406 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000407 NULL);
408
409 getModule().addTypeName("struct.__block_literal_extended_generic",
410 GenericExtendedBlockLiteralType);
411
412 return GenericExtendedBlockLiteralType;
413}
414
Mike Stumpa5448542009-02-13 15:32:32 +0000415/// getBlockFunctionType - Given a BlockPointerType, will return the
Anders Carlssonacfde802009-02-12 00:39:25 +0000416/// function type for the block, including the first block literal argument.
417static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlssond5cab542009-02-12 17:55:02 +0000418 const BlockPointerType *BPT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000419 const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
Mike Stumpa5448542009-02-13 15:32:32 +0000420
Anders Carlssonacfde802009-02-12 00:39:25 +0000421 llvm::SmallVector<QualType, 8> Types;
422 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000423
Douglas Gregor72564e72009-02-26 23:50:07 +0000424 for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000425 e = FTy->arg_type_end(); i != e; ++i)
426 Types.push_back(*i);
Mike Stumpa5448542009-02-13 15:32:32 +0000427
Anders Carlssonacfde802009-02-12 00:39:25 +0000428 return Ctx.getFunctionType(FTy->getResultType(),
Mike Stumpa5448542009-02-13 15:32:32 +0000429 &Types[0], Types.size(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000430 FTy->isVariadic(), 0);
431}
432
Anders Carlssond5cab542009-02-12 17:55:02 +0000433RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpa5448542009-02-13 15:32:32 +0000434 const BlockPointerType *BPT =
Anders Carlssonacfde802009-02-12 00:39:25 +0000435 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpa5448542009-02-13 15:32:32 +0000436
Anders Carlssonacfde802009-02-12 00:39:25 +0000437 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
438
439 // Get a pointer to the generic block literal.
440 const llvm::Type *BlockLiteralTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000441 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000442
443 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000444 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000445 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
446
447 // Get the function pointer from the literal.
448 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump20733cd2009-02-22 13:27:11 +0000449 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000450
451 // Cast the function pointer to the right type.
Mike Stumpa5448542009-02-13 15:32:32 +0000452 const llvm::Type *BlockFTy =
Anders Carlssonacfde802009-02-12 00:39:25 +0000453 ConvertType(getBlockFunctionType(getContext(), BPT));
454 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
455 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
456
Mike Stumpa5448542009-02-13 15:32:32 +0000457 BlockLiteral =
458 Builder.CreateBitCast(BlockLiteral,
Anders Carlssonacfde802009-02-12 00:39:25 +0000459 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
460 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000461
Anders Carlssonacfde802009-02-12 00:39:25 +0000462 // Add the block literal.
463 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
464 CallArgList Args;
465 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000466
Anders Carlssonacfde802009-02-12 00:39:25 +0000467 // And the rest of the arguments.
Mike Stumpa5448542009-02-13 15:32:32 +0000468 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssonacfde802009-02-12 00:39:25 +0000469 i != e; ++i)
Mike Stumpa5448542009-02-13 15:32:32 +0000470 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssonacfde802009-02-12 00:39:25 +0000471 i->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000472
Anders Carlssonacfde802009-02-12 00:39:25 +0000473 // And call the block.
Mike Stumpa5448542009-02-13 15:32:32 +0000474 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
Anders Carlssonacfde802009-02-12 00:39:25 +0000475 Func, Args);
476}
Anders Carlssond5cab542009-02-12 17:55:02 +0000477
Mike Stumpdab514f2009-03-04 03:23:46 +0000478llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
479 uint64_t &offset = BlockDecls[E->getDecl()];
480
481 const llvm::Type *Ty;
482 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
483
Mike Stump58919e12009-03-04 13:17:22 +0000484 if (!Enable__block && E->isByRef())
Mike Stumpdab514f2009-03-04 03:23:46 +0000485 ErrorUnsupported(E, "__block variable in block literal");
Mike Stumpa4f668f2009-03-06 01:33:24 +0000486 else if (!Enable__block && E->getType()->isBlockPointerType())
Mike Stumpdab514f2009-03-04 03:23:46 +0000487 ErrorUnsupported(E, "block pointer in block literal");
Mike Stump8e5d9f12009-03-07 14:53:10 +0000488 else if (!Enable__block && (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
489 getContext().isObjCNSObjectType(E->getType())))
Mike Stumpdab514f2009-03-04 03:23:46 +0000490 ErrorUnsupported(E, "__attribute__((NSObject)) variable in block "
491 "literal");
Mike Stumpa4f668f2009-03-06 01:33:24 +0000492 else if (!Enable__block && getContext().isObjCObjectPointerType(E->getType()))
Mike Stumpdab514f2009-03-04 03:23:46 +0000493 ErrorUnsupported(E, "Objective-C variable in block literal");
494
495 // See if we have already allocated an offset for this variable.
496 if (offset == 0) {
Mike Stump00470a12009-03-05 08:32:30 +0000497 // Don't run the expensive check, unless we have to.
498 if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
499 BlockHasCopyDispose = true;
Mike Stumpdab514f2009-03-04 03:23:46 +0000500 // if not, allocate one now.
501 offset = getBlockOffset(E);
502 }
503
504 llvm::Value *BlockLiteral = LoadBlockStruct();
505 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
506 llvm::ConstantInt::get(llvm::Type::Int64Ty,
507 offset),
Mike Stump58a85142009-03-04 22:48:06 +0000508 "block.literal");
Mike Stumpdab514f2009-03-04 03:23:46 +0000509 if (E->isByRef()) {
510 bool needsCopyDispose = BlockRequiresCopying(E->getType());
511 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
512 const llvm::Type *PtrStructTy
513 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
514 Ty = PtrStructTy;
515 Ty = llvm::PointerType::get(Ty, 0);
516 V = Builder.CreateBitCast(V, Ty);
517 V = Builder.CreateLoad(V, false);
518 V = Builder.CreateStructGEP(V, 1, "forwarding");
519 V = Builder.CreateLoad(V, false);
520 V = Builder.CreateBitCast(V, PtrStructTy);
521 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
522 } else {
523 Ty = llvm::PointerType::get(Ty, 0);
524 V = Builder.CreateBitCast(V, Ty);
525 }
526 return V;
527}
528
Mike Stump6cc88f72009-03-20 21:53:12 +0000529void CodeGenFunction::BlockForwardSelf() {
530 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
531 ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
532 llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
533 if (DMEntry)
534 return;
535 // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
536 BlockDeclRefExpr *BDRE = new (getContext())
537 BlockDeclRefExpr(SelfDecl,
538 SelfDecl->getType(), SourceLocation(), false);
539 DMEntry = GetAddrOfBlockDecl(BDRE);
540}
541
Mike Stump67a64482009-02-14 22:16:35 +0000542llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000543BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000544 // Generate the block descriptor.
545 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000546 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
547 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000548
Anders Carlssond5cab542009-02-12 17:55:02 +0000549 llvm::Constant *DescriptorFields[2];
Mike Stumpa5448542009-02-13 15:32:32 +0000550
Anders Carlssond5cab542009-02-12 17:55:02 +0000551 // Reserved
552 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000553
Anders Carlssond5cab542009-02-12 17:55:02 +0000554 // Block literal size. For global blocks we just use the size of the generic
555 // block literal struct.
Mike Stumpa5448542009-02-13 15:32:32 +0000556 uint64_t BlockLiteralSize =
Mike Stump9b8a7972009-02-13 15:25:34 +0000557 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlssond5cab542009-02-12 17:55:02 +0000558 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpa5448542009-02-13 15:32:32 +0000559
560 llvm::Constant *DescriptorStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000561 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpa5448542009-02-13 15:32:32 +0000562
Anders Carlssond5cab542009-02-12 17:55:02 +0000563 llvm::GlobalVariable *Descriptor =
564 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000565 llvm::GlobalVariable::InternalLinkage,
566 DescriptorStruct, "__block_descriptor_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000567 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000568
Anders Carlssond5cab542009-02-12 17:55:02 +0000569 // Generate the constants for the block literal.
570 llvm::Constant *LiteralFields[5];
Mike Stumpa5448542009-02-13 15:32:32 +0000571
Mike Stump67a64482009-02-14 22:16:35 +0000572 CodeGenFunction::BlockInfo Info(0, n);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000573 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000574 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Daniel Dunbard67b09a2009-03-12 03:07:24 +0000575 bool subBlockHasCopyDispose = false;
Mike Stump7f28a9c2009-03-13 23:34:28 +0000576 llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000577 llvm::Function *Fn
Mike Stump6cc88f72009-03-20 21:53:12 +0000578 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000579 subBlockSize,
Mike Stump90a90432009-03-04 18:47:42 +0000580 subBlockAlign,
Mike Stump00470a12009-03-05 08:32:30 +0000581 subBlockDeclRefDecls,
582 subBlockHasCopyDispose);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000583 assert(subBlockSize == BlockLiteralSize
584 && "no imports allowed for global block");
Daniel Dunbard67b09a2009-03-12 03:07:24 +0000585 assert(!subBlockHasCopyDispose && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000586
Anders Carlssond5cab542009-02-12 17:55:02 +0000587 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000588 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000589
Anders Carlssond5cab542009-02-12 17:55:02 +0000590 // Flags
Mike Stump00470a12009-03-05 08:32:30 +0000591 LiteralFields[1] =
Anders Carlsson8045ee02009-03-01 21:09:29 +0000592 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpa5448542009-02-13 15:32:32 +0000593
Anders Carlssond5cab542009-02-12 17:55:02 +0000594 // Reserved
Mike Stump7cbb3602009-02-13 16:01:35 +0000595 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000596
Anders Carlssond5cab542009-02-12 17:55:02 +0000597 // Function
598 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000599
Anders Carlssond5cab542009-02-12 17:55:02 +0000600 // Descriptor
601 LiteralFields[4] = Descriptor;
Mike Stumpa5448542009-02-13 15:32:32 +0000602
603 llvm::Constant *BlockLiteralStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000604 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpa5448542009-02-13 15:32:32 +0000605
606 llvm::GlobalVariable *BlockLiteral =
Anders Carlssond5cab542009-02-12 17:55:02 +0000607 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000608 llvm::GlobalVariable::InternalLinkage,
609 BlockLiteralStruct, "__block_literal_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000610 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000611
Anders Carlssond5cab542009-02-12 17:55:02 +0000612 return BlockLiteral;
613}
614
Mike Stump4e7a1f72009-02-21 20:00:35 +0000615llvm::Value *CodeGenFunction::LoadBlockStruct() {
616 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
617}
618
Mike Stump00470a12009-03-05 08:32:30 +0000619llvm::Function *
620CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
621 const BlockInfo& Info,
Mike Stump6cc88f72009-03-20 21:53:12 +0000622 const Decl *OuterFuncDecl,
Mike Stump7f28a9c2009-03-13 23:34:28 +0000623 llvm::DenseMap<const Decl*, llvm::Value*> ldm,
Mike Stump00470a12009-03-05 08:32:30 +0000624 uint64_t &Size,
625 uint64_t &Align,
626 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
627 bool &subBlockHasCopyDispose) {
Mike Stump7f28a9c2009-03-13 23:34:28 +0000628 // Arrange for local static and local extern declarations to appear
629 // to be local to this function as well, as they are directly referenced
630 // in a block.
631 for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
632 i != ldm.end();
633 ++i) {
634 const VarDecl *VD = dyn_cast<VarDecl>(i->first);
635
636 if (VD->getStorageClass() == VarDecl::Static
637 || VD->getStorageClass() == VarDecl::Extern)
638 LocalDeclMap[VD] = i->second;
639 }
640
Douglas Gregor72564e72009-02-26 23:50:07 +0000641 const FunctionProtoType *FTy =
Chris Lattner161d36d2009-02-28 19:01:03 +0000642 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpa5448542009-02-13 15:32:32 +0000643
Anders Carlssond5cab542009-02-12 17:55:02 +0000644 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000645
Chris Lattner161d36d2009-02-28 19:01:03 +0000646 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000647
648 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000649 ImplicitParamDecl *SelfDecl =
Anders Carlssond5cab542009-02-12 17:55:02 +0000650 ImplicitParamDecl::Create(getContext(), 0,
651 SourceLocation(), 0,
652 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000653
Anders Carlssond5cab542009-02-12 17:55:02 +0000654 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000655 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000656
Steve Naroffe78b8092009-03-13 16:56:44 +0000657 for (BlockDecl::param_const_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000658 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000659 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000660
661 const CGFunctionInfo &FI =
Anders Carlssond5cab542009-02-12 17:55:02 +0000662 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
663
Mike Stump67a64482009-02-14 22:16:35 +0000664 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlssond5cab542009-02-12 17:55:02 +0000665 CodeGenTypes &Types = CGM.getTypes();
666 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000667
668 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000669 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
670 Name,
671 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000672
673 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000674 BExpr->getBody()->getLocEnd());
Mike Stump6cc88f72009-03-20 21:53:12 +0000675 CurFuncDecl = OuterFuncDecl;
Chris Lattner161d36d2009-02-28 19:01:03 +0000676 EmitStmt(BExpr->getBody());
677 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000678
Mike Stump8a2b4b12009-02-25 23:33:13 +0000679 // The runtime needs a minimum alignment of a void *.
680 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
681 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
682
Mike Stump4e7a1f72009-02-21 20:00:35 +0000683 Size = BlockOffset;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000684 Align = BlockAlign;
685 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump00470a12009-03-05 08:32:30 +0000686 subBlockHasCopyDispose |= BlockHasCopyDispose;
Anders Carlssond5cab542009-02-12 17:55:02 +0000687 return Fn;
688}
Mike Stumpa99038c2009-02-28 09:07:16 +0000689
Mike Stump08920992009-03-07 02:35:30 +0000690uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
Mike Stumpa99038c2009-02-28 09:07:16 +0000691 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
692
693 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
694 uint64_t Align = getContext().getDeclAlignInBytes(D);
695
696 if (BDRE->isByRef()) {
697 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
698 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
699 }
700
701 assert ((Align > 0) && "alignment must be 1 byte or more");
702
703 uint64_t OldOffset = BlockOffset;
704
705 // Ensure proper alignment, even if it means we have to have a gap
706 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
707 BlockAlign = std::max(Align, BlockAlign);
Mike Stump00470a12009-03-05 08:32:30 +0000708
Mike Stumpa99038c2009-02-28 09:07:16 +0000709 uint64_t Pad = BlockOffset - OldOffset;
710 if (Pad) {
711 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
712 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
713 llvm::APInt(32, Pad),
714 ArrayType::Normal, 0);
715 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
716 0, QualType(PadTy), VarDecl::None,
717 SourceLocation());
718 Expr *E;
719 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
720 SourceLocation(), false, false);
721 BlockDeclRefDecls.push_back(E);
722 }
723 BlockDeclRefDecls.push_back(BDRE);
724
725 BlockOffset += Size;
726 return BlockOffset-Size;
727}
Mike Stumpdab514f2009-03-04 03:23:46 +0000728
Mike Stump08920992009-03-07 02:35:30 +0000729llvm::Constant *BlockFunction::
730GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
731 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000732 QualType R = getContext().VoidTy;
733
734 FunctionArgList Args;
735 // FIXME: This leaks
Mike Stump08920992009-03-07 02:35:30 +0000736 ImplicitParamDecl *Dst =
737 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
738 getContext().getPointerType(getContext().VoidTy));
739 Args.push_back(std::make_pair(Dst, Dst->getType()));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000740 ImplicitParamDecl *Src =
741 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
742 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa4f668f2009-03-06 01:33:24 +0000743 Args.push_back(std::make_pair(Src, Src->getType()));
744
745 const CGFunctionInfo &FI =
746 CGM.getTypes().getFunctionInfo(R, Args);
747
748 std::string Name = std::string("__copy_helper_block_");
749 CodeGenTypes &Types = CGM.getTypes();
750 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
751
752 llvm::Function *Fn =
753 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
754 Name,
755 &CGM.getModule());
756
757 IdentifierInfo *II
758 = &CGM.getContext().Idents.get("__copy_helper_block_");
759
760 FunctionDecl *FD = FunctionDecl::Create(getContext(),
761 getContext().getTranslationUnitDecl(),
762 SourceLocation(), II, R,
763 FunctionDecl::Static, false,
764 true);
765 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump08920992009-03-07 02:35:30 +0000766
767 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
768 llvm::Type *PtrPtrT;
769 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
770 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
771 SrcObj = Builder.CreateLoad(SrcObj);
772
773 llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
774 DstObj = Builder.CreateBitCast(DstObj, llvm::PointerType::get(T, 0));
775
776 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
777 int flag = NoteForHelper[i].flag;
778 int index = NoteForHelper[i].index;
779
780 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
781 || NoteForHelper[i].RequiresCopying) {
782 llvm::Value *Srcv = SrcObj;
783 Srcv = Builder.CreateStructGEP(Srcv, index);
784 Srcv = Builder.CreateBitCast(Srcv,
785 llvm::PointerType::get(PtrToInt8Ty, 0));
786 Srcv = Builder.CreateLoad(Srcv);
787
788 llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
789 Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
790
791 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
792 llvm::Value *F = getBlockObjectAssign();
793 Builder.CreateCall3(F, Dstv, Srcv, N);
794 }
795 }
796
Mike Stumpa4f668f2009-03-06 01:33:24 +0000797 CGF.FinishFunction();
798
799 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000800}
801
Mike Stumpcf62d392009-03-06 18:42:23 +0000802llvm::Constant *BlockFunction::
Mike Stump08920992009-03-07 02:35:30 +0000803GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
804 const llvm::StructType* T,
805 std::vector<HelperInfo> &NoteForHelper) {
Mike Stumpa4f668f2009-03-06 01:33:24 +0000806 QualType R = getContext().VoidTy;
807
808 FunctionArgList Args;
809 // FIXME: This leaks
810 ImplicitParamDecl *Src =
811 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
812 getContext().getPointerType(getContext().VoidTy));
813
814 Args.push_back(std::make_pair(Src, Src->getType()));
815
816 const CGFunctionInfo &FI =
817 CGM.getTypes().getFunctionInfo(R, Args);
818
819 std::string Name = std::string("__destroy_helper_block_");
820 CodeGenTypes &Types = CGM.getTypes();
821 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
822
823 llvm::Function *Fn =
824 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
825 Name,
826 &CGM.getModule());
827
828 IdentifierInfo *II
829 = &CGM.getContext().Idents.get("__destroy_helper_block_");
830
831 FunctionDecl *FD = FunctionDecl::Create(getContext(),
832 getContext().getTranslationUnitDecl(),
833 SourceLocation(), II, R,
834 FunctionDecl::Static, false,
835 true);
836 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1edf6b62009-03-07 02:53:18 +0000837
838 llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
839 llvm::Type *PtrPtrT;
840 PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
841 SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
842 SrcObj = Builder.CreateLoad(SrcObj);
843
844 for (unsigned i=0; i < NoteForHelper.size(); ++i) {
845 int flag = NoteForHelper[i].flag;
846 int index = NoteForHelper[i].index;
847
848 if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
849 || NoteForHelper[i].RequiresCopying) {
850 llvm::Value *Srcv = SrcObj;
851 Srcv = Builder.CreateStructGEP(Srcv, index);
852 Srcv = Builder.CreateBitCast(Srcv,
853 llvm::PointerType::get(PtrToInt8Ty, 0));
854 Srcv = Builder.CreateLoad(Srcv);
855
856 BuildBlockRelease(Srcv, flag);
857 }
858 }
859
Mike Stumpa4f668f2009-03-06 01:33:24 +0000860 CGF.FinishFunction();
861
862 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
863}
864
Mike Stump08920992009-03-07 02:35:30 +0000865llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
866 std::vector<HelperInfo> &NoteForHelper) {
867 return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
868 T, NoteForHelper);
Mike Stumpa4f668f2009-03-06 01:33:24 +0000869}
870
Mike Stump08920992009-03-07 02:35:30 +0000871llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
872 std::vector<HelperInfo> &NoteForHelper) {
873 return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
874 T, NoteForHelper);
Mike Stumpdab514f2009-03-04 03:23:46 +0000875}
Mike Stump797b6322009-03-05 01:23:13 +0000876
Mike Stumpee094222009-03-06 06:12:24 +0000877llvm::Constant *BlockFunction::
878GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000879 QualType R = getContext().VoidTy;
880
881 FunctionArgList Args;
882 // FIXME: This leaks
Mike Stumpee094222009-03-06 06:12:24 +0000883 ImplicitParamDecl *Dst =
884 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
885 getContext().getPointerType(getContext().VoidTy));
886 Args.push_back(std::make_pair(Dst, Dst->getType()));
887
888 // FIXME: This leaks
Mike Stump45031c02009-03-06 02:29:21 +0000889 ImplicitParamDecl *Src =
890 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
891 getContext().getPointerType(getContext().VoidTy));
Mike Stump45031c02009-03-06 02:29:21 +0000892 Args.push_back(std::make_pair(Src, Src->getType()));
893
894 const CGFunctionInfo &FI =
895 CGM.getTypes().getFunctionInfo(R, Args);
896
897 std::string Name = std::string("__Block_byref_id_object_copy_");
898 CodeGenTypes &Types = CGM.getTypes();
899 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
900
901 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 Stumpee094222009-03-06 06:12:24 +0000915
916 // dst->x
917 llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
918 V = Builder.CreateBitCast(V, T);
919 V = Builder.CreateStructGEP(V, 6, "x");
920 llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
921
922 // src->x
923 V = CGF.GetAddrOfLocalVar(Src);
924 V = Builder.CreateLoad(V);
925 V = Builder.CreateBitCast(V, T);
926 V = Builder.CreateStructGEP(V, 6, "x");
927 V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
928 llvm::Value *SrcObj = Builder.CreateLoad(V);
929
930 flag |= BLOCK_BYREF_CALLER;
931
932 llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
933 llvm::Value *F = getBlockObjectAssign();
934 Builder.CreateCall3(F, DstObj, SrcObj, N);
935
Mike Stump45031c02009-03-06 02:29:21 +0000936 CGF.FinishFunction();
937
938 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
939}
940
Mike Stump1851b682009-03-06 04:53:30 +0000941llvm::Constant *
942BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
943 int flag) {
Mike Stump45031c02009-03-06 02:29:21 +0000944 QualType R = getContext().VoidTy;
945
946 FunctionArgList Args;
947 // FIXME: This leaks
948 ImplicitParamDecl *Src =
949 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
950 getContext().getPointerType(getContext().VoidTy));
951
952 Args.push_back(std::make_pair(Src, Src->getType()));
953
954 const CGFunctionInfo &FI =
955 CGM.getTypes().getFunctionInfo(R, Args);
956
957 std::string Name = std::string("__Block_byref_id_object_dispose_");
958 CodeGenTypes &Types = CGM.getTypes();
959 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
960
961 llvm::Function *Fn =
962 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
963 Name,
964 &CGM.getModule());
965
966 IdentifierInfo *II
967 = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
968
969 FunctionDecl *FD = FunctionDecl::Create(getContext(),
970 getContext().getTranslationUnitDecl(),
971 SourceLocation(), II, R,
972 FunctionDecl::Static, false,
973 true);
974 CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
Mike Stump1851b682009-03-06 04:53:30 +0000975
976 llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
977 V = Builder.CreateBitCast(V, T);
978 V = Builder.CreateStructGEP(V, 6, "x");
979 V = Builder.CreateBitCast(V, PtrToInt8Ty);
980
Mike Stump1851b682009-03-06 04:53:30 +0000981 flag |= BLOCK_BYREF_CALLER;
982 BuildBlockRelease(V, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000983 CGF.FinishFunction();
984
985 return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
986}
987
Mike Stumpee094222009-03-06 06:12:24 +0000988llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
989 int flag) {
990 return CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000991}
992
Mike Stump1851b682009-03-06 04:53:30 +0000993llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
994 int flag) {
995 return CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
Mike Stump45031c02009-03-06 02:29:21 +0000996}
997
Mike Stump797b6322009-03-05 01:23:13 +0000998llvm::Value *BlockFunction::getBlockObjectDispose() {
999 if (CGM.BlockObjectDispose == 0) {
1000 const llvm::FunctionType *FTy;
1001 std::vector<const llvm::Type*> ArgTys;
1002 const llvm::Type *ResultType = llvm::Type::VoidTy;
1003 ArgTys.push_back(PtrToInt8Ty);
1004 ArgTys.push_back(llvm::Type::Int32Ty);
1005 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
Mike Stump00470a12009-03-05 08:32:30 +00001006 CGM.BlockObjectDispose
Mike Stump797b6322009-03-05 01:23:13 +00001007 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1008 }
1009 return CGM.BlockObjectDispose;
1010}
1011
Mike Stumpee094222009-03-06 06:12:24 +00001012llvm::Value *BlockFunction::getBlockObjectAssign() {
1013 if (CGM.BlockObjectAssign == 0) {
1014 const llvm::FunctionType *FTy;
1015 std::vector<const llvm::Type*> ArgTys;
1016 const llvm::Type *ResultType = llvm::Type::VoidTy;
1017 ArgTys.push_back(PtrToInt8Ty);
1018 ArgTys.push_back(PtrToInt8Ty);
1019 ArgTys.push_back(llvm::Type::Int32Ty);
1020 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1021 CGM.BlockObjectAssign
1022 = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1023 }
1024 return CGM.BlockObjectAssign;
1025}
1026
Mike Stump1851b682009-03-06 04:53:30 +00001027void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
Mike Stump797b6322009-03-05 01:23:13 +00001028 llvm::Value *F = getBlockObjectDispose();
Mike Stump1851b682009-03-06 04:53:30 +00001029 llvm::Value *N;
Mike Stump797b6322009-03-05 01:23:13 +00001030 V = Builder.CreateBitCast(V, PtrToInt8Ty);
Mike Stump1851b682009-03-06 04:53:30 +00001031 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
Mike Stump797b6322009-03-05 01:23:13 +00001032 Builder.CreateCall2(F, V, N);
1033}
Mike Stump00470a12009-03-05 08:32:30 +00001034
1035ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
Mike Stump08920992009-03-07 02:35:30 +00001036
1037BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1038 CGBuilderTy &B)
1039 : CGM(cgm), CGF(cgf), Builder(B) {
1040 PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1041
1042 BlockHasCopyDispose = false;
1043}