blob: 89b2b5ff13a7bf28318573f67a3b7a8ddc01cf72 [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"
16#include "llvm/Module.h"
Anders Carlssond5cab542009-02-12 17:55:02 +000017#include "llvm/Target/TargetData.h"
Anders Carlssonacfde802009-02-12 00:39:25 +000018
19#include <algorithm>
20
21using namespace clang;
22using namespace CodeGen;
23
Mike Stump58919e12009-03-04 13:17:22 +000024// Temporary code to enable testing of __block variables
25// #include "clang/Frontend/CompileOptions.h"
26#include "llvm/Support/CommandLine.h"
27static llvm::cl::opt<bool>
28Enable__block("f__block",
29 // See all the FIXMEs for the various work that needs to be done
30 llvm::cl::desc("temporary option to turn on __block precessing "
31 "even though the code isn't done yet"),
32 llvm::cl::ValueDisallowed, llvm::cl::AllowInverse,
33 llvm::cl::ZeroOrMore);
34
35
Mike Stump4e7a1f72009-02-21 20:00:35 +000036llvm::Constant *CodeGenFunction::BuildDescriptorBlockDecl(uint64_t Size) {
Mike Stump56129b12009-02-13 16:55:51 +000037 const llvm::Type *UnsignedLongTy
38 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpe5fee252009-02-13 16:19:19 +000039 llvm::Constant *C;
40 std::vector<llvm::Constant*> Elts;
41
42 // reserved
Mike Stump56129b12009-02-13 16:55:51 +000043 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000044 Elts.push_back(C);
45
46 // Size
Mike Stumpd6840002009-02-21 20:07:44 +000047 // FIXME: What is the right way to say this doesn't fit? We should give
48 // a user diagnostic in that case. Better fix would be to change the
49 // API to size_t.
Mike Stump4e7a1f72009-02-21 20:00:35 +000050 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stumpe5fee252009-02-13 16:19:19 +000051 Elts.push_back(C);
52
53 if (BlockHasCopyDispose) {
54 // copy_func_helper_decl
Mike Stump4e7a1f72009-02-21 20:00:35 +000055 // FIXME: implement
Mike Stump56129b12009-02-13 16:55:51 +000056 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000057 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
58 Elts.push_back(C);
59
60 // destroy_func_decl
Mike Stump4e7a1f72009-02-21 20:00:35 +000061 // FIXME: implement
Mike Stump56129b12009-02-13 16:55:51 +000062 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stumpe5fee252009-02-13 16:19:19 +000063 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
64 Elts.push_back(C);
65 }
66
67 C = llvm::ConstantStruct::get(Elts);
68
Mike Stumpe5fee252009-02-13 16:19:19 +000069 C = new llvm::GlobalVariable(C->getType(), true,
70 llvm::GlobalValue::InternalLinkage,
Mike Stump7d6dc4f2009-02-13 20:17:16 +000071 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stumpe5fee252009-02-13 16:19:19 +000072 return C;
73}
74
Mike Stump2a998142009-03-04 18:17:45 +000075llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
Mike Stumpf99f1d02009-02-13 17:23:42 +000076 if (NSConcreteGlobalBlock)
77 return NSConcreteGlobalBlock;
78
Mike Stumpf7448952009-02-13 19:38:12 +000079 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000080 // same thing as CreateRuntimeFunction if there's already a variable with the
81 // same name.
Mike Stumpf99f1d02009-02-13 17:23:42 +000082 NSConcreteGlobalBlock
83 = new llvm::GlobalVariable(PtrToInt8Ty, false,
84 llvm::GlobalValue::ExternalLinkage,
85 0, "_NSConcreteGlobalBlock",
86 &getModule());
87
88 return NSConcreteGlobalBlock;
89}
90
Mike Stump2a998142009-03-04 18:17:45 +000091llvm::Constant *BlockModule::getNSConcreteStackBlock() {
Mike Stump59c5b112009-02-13 19:29:27 +000092 if (NSConcreteStackBlock)
93 return NSConcreteStackBlock;
94
Mike Stumpf7448952009-02-13 19:38:12 +000095 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump58a85142009-03-04 22:48:06 +000096 // same thing as CreateRuntimeFunction if there's already a variable with the
97 // same name.
Mike Stump59c5b112009-02-13 19:29:27 +000098 NSConcreteStackBlock
99 = new llvm::GlobalVariable(PtrToInt8Ty, false,
100 llvm::GlobalValue::ExternalLinkage,
101 0, "_NSConcreteStackBlock",
102 &getModule());
103
104 return NSConcreteStackBlock;
105}
106
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000107static void CollectBlockDeclRefInfo(const Stmt *S,
108 CodeGenFunction::BlockInfo &Info) {
109 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
110 I != E; ++I)
Daniel Dunbar82573ee2009-03-02 07:00:57 +0000111 if (*I)
112 CollectBlockDeclRefInfo(*I, Info);
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000113
114 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
115 // FIXME: Handle enums.
116 if (isa<FunctionDecl>(DE->getDecl()))
117 return;
118
119 if (DE->isByRef())
120 Info.ByRefDeclRefs.push_back(DE);
121 else
122 Info.ByCopyDeclRefs.push_back(DE);
123 }
124}
125
Mike Stump58a85142009-03-04 22:48:06 +0000126/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
127/// declared as a global variable instead of on the stack.
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000128static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
129{
130 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
131}
132
Mike Stump58a85142009-03-04 22:48:06 +0000133// FIXME: Push most into CGM, passing down a few bits, like current function
134// name.
Mike Stump8a2b4b12009-02-25 23:33:13 +0000135llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stumpe5fee252009-02-13 16:19:19 +0000136
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000137 std::string Name = CurFn->getName();
138 CodeGenFunction::BlockInfo Info(0, Name.c_str());
139 CollectBlockDeclRefInfo(BE->getBody(), Info);
140
141 // Check if the block can be global.
Mike Stump58a85142009-03-04 22:48:06 +0000142 // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like
143 // to just have one code path. We should move this function into CGM and pass
144 // CGF, then we can just check to see if CGF is 0.
Mike Stumpdab514f2009-03-04 03:23:46 +0000145 if (0 && CanBlockBeGlobal(Info))
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000146 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
147
Mike Stumpe5fee252009-02-13 16:19:19 +0000148 std::vector<llvm::Constant*> Elts;
149 llvm::Constant *C;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000150 llvm::Value *V;
Mike Stumpe5fee252009-02-13 16:19:19 +0000151
Mike Stumpe5fee252009-02-13 16:19:19 +0000152 {
153 // C = BuildBlockStructInitlist();
154 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
155
156 if (BlockHasCopyDispose)
157 flags |= BLOCK_HAS_COPY_DISPOSE;
158
Mike Stump7d6dc4f2009-02-13 20:17:16 +0000159 // __isa
Mike Stump59c5b112009-02-13 19:29:27 +0000160 C = CGM.getNSConcreteStackBlock();
Mike Stumpe5fee252009-02-13 16:19:19 +0000161 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
162 Elts.push_back(C);
163
164 // __flags
165 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
166 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
167 C = llvm::ConstantInt::get(IntTy, flags);
168 Elts.push_back(C);
169
170 // __reserved
171 C = llvm::ConstantInt::get(IntTy, 0);
172 Elts.push_back(C);
173
Mike Stumpbd65cac2009-02-19 01:01:04 +0000174 // __invoke
Mike Stump8a2b4b12009-02-25 23:33:13 +0000175 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000176 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000177 llvm::Function *Fn
Mike Stump8a2b4b12009-02-25 23:33:13 +0000178 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
179 subBlockAlign, subBlockDeclRefDecls);
Mike Stump67a64482009-02-14 22:16:35 +0000180 Elts.push_back(Fn);
Mike Stumpe5fee252009-02-13 16:19:19 +0000181
182 // __descriptor
Mike Stump4e7a1f72009-02-21 20:00:35 +0000183 Elts.push_back(BuildDescriptorBlockDecl(subBlockSize));
Mike Stumpe5fee252009-02-13 16:19:19 +0000184
Mike Stump8a2b4b12009-02-25 23:33:13 +0000185 if (subBlockDeclRefDecls.size() == 0) {
Mike Stump5570cfe2009-03-01 20:07:53 +0000186 // Optimize to being a global block.
187 Elts[0] = CGM.getNSConcreteGlobalBlock();
188 Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
189
Mike Stump8a2b4b12009-02-25 23:33:13 +0000190 C = llvm::ConstantStruct::get(Elts);
191
192 char Name[32];
193 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
194 C = new llvm::GlobalVariable(C->getType(), true,
195 llvm::GlobalValue::InternalLinkage,
196 C, Name, &CGM.getModule());
197 QualType BPT = BE->getType();
198 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
199 return C;
200 }
201
202 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
203 for (int i=0; i<5; ++i)
204 Types[i] = Elts[i]->getType();
205
Mike Stumpa99038c2009-02-28 09:07:16 +0000206 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
207 const Expr *E = subBlockDeclRefDecls[i];
208 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
209 QualType Ty = E->getType();
Mike Stumpdab514f2009-03-04 03:23:46 +0000210 if (BDRE && BDRE->isByRef()) {
211 uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
212 Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
213 } else
214 Types[i+5] = ConvertType(Ty);
Mike Stumpa99038c2009-02-28 09:07:16 +0000215 }
Mike Stump8a2b4b12009-02-25 23:33:13 +0000216
217 llvm::Type *Ty = llvm::StructType::get(Types, true);
218
219 llvm::AllocaInst *A = CreateTempAlloca(Ty);
220 A->setAlignment(subBlockAlign);
221 V = A;
222
223 for (unsigned i=0; i<5; ++i)
224 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
225
226 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
227 {
Mike Stumpa99038c2009-02-28 09:07:16 +0000228 // FIXME: Push const down.
229 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
230 DeclRefExpr *DR;
231 ValueDecl *VD;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000232
Mike Stumpa99038c2009-02-28 09:07:16 +0000233 DR = dyn_cast<DeclRefExpr>(E);
234 // Skip padding.
235 if (DR) continue;
236
237 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
238 VD = BDRE->getDecl();
239
Mike Stumpdab514f2009-03-04 03:23:46 +0000240 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stumpa99038c2009-02-28 09:07:16 +0000241 // FIXME: I want a better way to do this.
242 if (LocalDeclMap[VD]) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000243 if (BDRE->isByRef()) {
244 const llvm::Type *Ty = Types[i+5];
245 llvm::Value *Loc = LocalDeclMap[VD];
246 Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
247 Loc = Builder.CreateLoad(Loc, false);
248 Loc = Builder.CreateBitCast(Loc, Ty);
249 Builder.CreateStore(Loc, Addr);
250 continue;
251 } else
252 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
253 VD->getType(), SourceLocation(),
254 false, false);
Mike Stumpa99038c2009-02-28 09:07:16 +0000255 }
Mike Stumpdab514f2009-03-04 03:23:46 +0000256 if (BDRE->isByRef()) {
257 // FIXME: __block in nested literals
Mike Stumpa99038c2009-02-28 09:07:16 +0000258 E = new (getContext())
259 UnaryOperator(E, UnaryOperator::AddrOf,
260 getContext().getPointerType(E->getType()),
261 SourceLocation());
Mike Stumpdab514f2009-03-04 03:23:46 +0000262 }
Mike Stumpa99038c2009-02-28 09:07:16 +0000263
Mike Stumpa99038c2009-02-28 09:07:16 +0000264 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpdab514f2009-03-04 03:23:46 +0000265 if (r.isScalar()) {
266 llvm::Value *Loc = r.getScalarVal();
267 const llvm::Type *Ty = Types[i+5];
268 if (BDRE->isByRef()) {
Mike Stump58a85142009-03-04 22:48:06 +0000269 // E is now the address of the value field, instead, we want the
270 // address of the actual ByRef struct. We optimize this slightly
271 // compared to gcc by not grabbing the forwarding slot as this must
272 // be done during Block_copy for us, and we can postpone the work
273 // until then.
274 uint64_t offset = BlockDecls[BDRE->getDecl()];
275
276 llvm::Value *BlockLiteral = LoadBlockStruct();
277
278 Loc = Builder.CreateGEP(BlockLiteral,
279 llvm::ConstantInt::get(llvm::Type::Int64Ty,
280 offset),
281 "block.literal");
282 Ty = llvm::PointerType::get(Ty, 0);
Mike Stumpdab514f2009-03-04 03:23:46 +0000283 Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stump58a85142009-03-04 22:48:06 +0000284 Loc = Builder.CreateLoad(Loc, false);
285 // Loc = Builder.CreateBitCast(Loc, Ty);
Mike Stumpdab514f2009-03-04 03:23:46 +0000286 }
287 Builder.CreateStore(Loc, Addr);
288 } else if (r.isComplex())
Mike Stump8a2b4b12009-02-25 23:33:13 +0000289 // FIXME: implement
290 ErrorUnsupported(BE, "complex in block literal");
291 else if (r.isAggregate())
292 ; // Already created into the destination
293 else
294 assert (0 && "bad block variable");
295 // FIXME: Ensure that the offset created by the backend for
296 // the struct matches the previously computed offset in BlockDecls.
297 }
Mike Stumpe5fee252009-02-13 16:19:19 +0000298 }
299
Mike Stumpbd65cac2009-02-19 01:01:04 +0000300 QualType BPT = BE->getType();
Mike Stump8a2b4b12009-02-25 23:33:13 +0000301 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stumpe5fee252009-02-13 16:19:19 +0000302}
303
304
Mike Stump2a998142009-03-04 18:17:45 +0000305const llvm::Type *BlockModule::getBlockDescriptorType() {
Mike Stumpab695142009-02-13 15:16:56 +0000306 if (BlockDescriptorType)
307 return BlockDescriptorType;
308
Mike Stumpa5448542009-02-13 15:32:32 +0000309 const llvm::Type *UnsignedLongTy =
Mike Stumpab695142009-02-13 15:16:56 +0000310 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000311
Mike Stumpab695142009-02-13 15:16:56 +0000312 // struct __block_descriptor {
313 // unsigned long reserved;
314 // unsigned long block_size;
315 // };
Mike Stumpa5448542009-02-13 15:32:32 +0000316 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
317 UnsignedLongTy,
Mike Stumpab695142009-02-13 15:16:56 +0000318 NULL);
319
320 getModule().addTypeName("struct.__block_descriptor",
321 BlockDescriptorType);
322
323 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000324}
325
Mike Stump2a998142009-03-04 18:17:45 +0000326const llvm::Type *BlockModule::getGenericBlockLiteralType() {
Mike Stump9b8a7972009-02-13 15:25:34 +0000327 if (GenericBlockLiteralType)
328 return GenericBlockLiteralType;
329
Mike Stumpa5448542009-02-13 15:32:32 +0000330 const llvm::Type *BlockDescPtrTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000331 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpa5448542009-02-13 15:32:32 +0000332
Mike Stump7cbb3602009-02-13 16:01:35 +0000333 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
334 getTypes().ConvertType(getContext().IntTy));
335
Mike Stump9b8a7972009-02-13 15:25:34 +0000336 // struct __block_literal_generic {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000337 // void *__isa;
338 // int __flags;
339 // int __reserved;
340 // void (*__invoke)(void *);
341 // struct __block_descriptor *__descriptor;
Mike Stump9b8a7972009-02-13 15:25:34 +0000342 // };
Mike Stump797b6322009-03-05 01:23:13 +0000343 GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stump7cbb3602009-02-13 16:01:35 +0000344 IntTy,
345 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000346 PtrToInt8Ty,
Mike Stump9b8a7972009-02-13 15:25:34 +0000347 BlockDescPtrTy,
348 NULL);
Mike Stumpa5448542009-02-13 15:32:32 +0000349
Mike Stump9b8a7972009-02-13 15:25:34 +0000350 getModule().addTypeName("struct.__block_literal_generic",
351 GenericBlockLiteralType);
Mike Stumpa5448542009-02-13 15:32:32 +0000352
Mike Stump9b8a7972009-02-13 15:25:34 +0000353 return GenericBlockLiteralType;
Anders Carlssonacfde802009-02-12 00:39:25 +0000354}
355
Mike Stump2a998142009-03-04 18:17:45 +0000356const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
Mike Stumpbd65cac2009-02-19 01:01:04 +0000357 if (GenericExtendedBlockLiteralType)
358 return GenericExtendedBlockLiteralType;
359
Mike Stumpbd65cac2009-02-19 01:01:04 +0000360 const llvm::Type *BlockDescPtrTy =
361 llvm::PointerType::getUnqual(getBlockDescriptorType());
362
363 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
364 getTypes().ConvertType(getContext().IntTy));
365
366 // struct __block_literal_generic {
367 // void *__isa;
368 // int __flags;
369 // int __reserved;
370 // void (*__invoke)(void *);
371 // struct __block_descriptor *__descriptor;
372 // void *__copy_func_helper_decl;
373 // void *__destroy_func_decl;
374 // };
Mike Stump797b6322009-03-05 01:23:13 +0000375 GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000376 IntTy,
377 IntTy,
Mike Stump797b6322009-03-05 01:23:13 +0000378 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000379 BlockDescPtrTy,
Mike Stump797b6322009-03-05 01:23:13 +0000380 PtrToInt8Ty,
381 PtrToInt8Ty,
Mike Stumpbd65cac2009-02-19 01:01:04 +0000382 NULL);
383
384 getModule().addTypeName("struct.__block_literal_extended_generic",
385 GenericExtendedBlockLiteralType);
386
387 return GenericExtendedBlockLiteralType;
388}
389
Mike Stumpa5448542009-02-13 15:32:32 +0000390/// getBlockFunctionType - Given a BlockPointerType, will return the
Anders Carlssonacfde802009-02-12 00:39:25 +0000391/// function type for the block, including the first block literal argument.
392static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlssond5cab542009-02-12 17:55:02 +0000393 const BlockPointerType *BPT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000394 const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
Mike Stumpa5448542009-02-13 15:32:32 +0000395
Anders Carlssonacfde802009-02-12 00:39:25 +0000396 llvm::SmallVector<QualType, 8> Types;
397 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000398
Douglas Gregor72564e72009-02-26 23:50:07 +0000399 for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000400 e = FTy->arg_type_end(); i != e; ++i)
401 Types.push_back(*i);
Mike Stumpa5448542009-02-13 15:32:32 +0000402
Anders Carlssonacfde802009-02-12 00:39:25 +0000403 return Ctx.getFunctionType(FTy->getResultType(),
Mike Stumpa5448542009-02-13 15:32:32 +0000404 &Types[0], Types.size(),
Anders Carlssonacfde802009-02-12 00:39:25 +0000405 FTy->isVariadic(), 0);
406}
407
Anders Carlssond5cab542009-02-12 17:55:02 +0000408RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpa5448542009-02-13 15:32:32 +0000409 const BlockPointerType *BPT =
Anders Carlssonacfde802009-02-12 00:39:25 +0000410 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpa5448542009-02-13 15:32:32 +0000411
Anders Carlssonacfde802009-02-12 00:39:25 +0000412 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
413
414 // Get a pointer to the generic block literal.
415 const llvm::Type *BlockLiteralTy =
Mike Stump9b8a7972009-02-13 15:25:34 +0000416 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlssonacfde802009-02-12 00:39:25 +0000417
418 // Bitcast the callee to a block literal.
Mike Stumpa5448542009-02-13 15:32:32 +0000419 llvm::Value *BlockLiteral =
Anders Carlssonacfde802009-02-12 00:39:25 +0000420 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
421
422 // Get the function pointer from the literal.
423 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump20733cd2009-02-22 13:27:11 +0000424 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlssonacfde802009-02-12 00:39:25 +0000425
426 // Cast the function pointer to the right type.
Mike Stumpa5448542009-02-13 15:32:32 +0000427 const llvm::Type *BlockFTy =
Anders Carlssonacfde802009-02-12 00:39:25 +0000428 ConvertType(getBlockFunctionType(getContext(), BPT));
429 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
430 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
431
Mike Stumpa5448542009-02-13 15:32:32 +0000432 BlockLiteral =
433 Builder.CreateBitCast(BlockLiteral,
Anders Carlssonacfde802009-02-12 00:39:25 +0000434 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
435 "tmp");
Mike Stumpa5448542009-02-13 15:32:32 +0000436
Anders Carlssonacfde802009-02-12 00:39:25 +0000437 // Add the block literal.
438 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
439 CallArgList Args;
440 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000441
Anders Carlssonacfde802009-02-12 00:39:25 +0000442 // And the rest of the arguments.
Mike Stumpa5448542009-02-13 15:32:32 +0000443 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlssonacfde802009-02-12 00:39:25 +0000444 i != e; ++i)
Mike Stumpa5448542009-02-13 15:32:32 +0000445 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlssonacfde802009-02-12 00:39:25 +0000446 i->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000447
Anders Carlssonacfde802009-02-12 00:39:25 +0000448 // And call the block.
Mike Stumpa5448542009-02-13 15:32:32 +0000449 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
Anders Carlssonacfde802009-02-12 00:39:25 +0000450 Func, Args);
451}
Anders Carlssond5cab542009-02-12 17:55:02 +0000452
Mike Stumpdab514f2009-03-04 03:23:46 +0000453llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
454 uint64_t &offset = BlockDecls[E->getDecl()];
455
456 const llvm::Type *Ty;
457 Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
458
459 // FIXME: add support for copy/dispose helpers.
Mike Stump58919e12009-03-04 13:17:22 +0000460 if (!Enable__block && E->isByRef())
Mike Stumpdab514f2009-03-04 03:23:46 +0000461 ErrorUnsupported(E, "__block variable in block literal");
462 else if (E->getType()->isBlockPointerType())
463 ErrorUnsupported(E, "block pointer in block literal");
464 else if (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
465 getContext().isObjCNSObjectType(E->getType()))
466 ErrorUnsupported(E, "__attribute__((NSObject)) variable in block "
467 "literal");
468 else if (getContext().isObjCObjectPointerType(E->getType()))
469 ErrorUnsupported(E, "Objective-C variable in block literal");
470
471 // See if we have already allocated an offset for this variable.
472 if (offset == 0) {
473 // if not, allocate one now.
474 offset = getBlockOffset(E);
475 }
476
477 llvm::Value *BlockLiteral = LoadBlockStruct();
478 llvm::Value *V = Builder.CreateGEP(BlockLiteral,
479 llvm::ConstantInt::get(llvm::Type::Int64Ty,
480 offset),
Mike Stump58a85142009-03-04 22:48:06 +0000481 "block.literal");
Mike Stumpdab514f2009-03-04 03:23:46 +0000482 if (E->isByRef()) {
483 bool needsCopyDispose = BlockRequiresCopying(E->getType());
484 uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
485 const llvm::Type *PtrStructTy
486 = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
487 Ty = PtrStructTy;
488 Ty = llvm::PointerType::get(Ty, 0);
489 V = Builder.CreateBitCast(V, Ty);
490 V = Builder.CreateLoad(V, false);
491 V = Builder.CreateStructGEP(V, 1, "forwarding");
492 V = Builder.CreateLoad(V, false);
493 V = Builder.CreateBitCast(V, PtrStructTy);
494 V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
495 } else {
496 Ty = llvm::PointerType::get(Ty, 0);
497 V = Builder.CreateBitCast(V, Ty);
498 }
499 return V;
500}
501
Mike Stump67a64482009-02-14 22:16:35 +0000502llvm::Constant *
Mike Stump90a90432009-03-04 18:47:42 +0000503BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlssond5cab542009-02-12 17:55:02 +0000504 // Generate the block descriptor.
505 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump7cbb3602009-02-13 16:01:35 +0000506 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
507 getTypes().ConvertType(getContext().IntTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000508
Anders Carlssond5cab542009-02-12 17:55:02 +0000509 llvm::Constant *DescriptorFields[2];
Mike Stumpa5448542009-02-13 15:32:32 +0000510
Anders Carlssond5cab542009-02-12 17:55:02 +0000511 // Reserved
512 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000513
Anders Carlssond5cab542009-02-12 17:55:02 +0000514 // Block literal size. For global blocks we just use the size of the generic
515 // block literal struct.
Mike Stumpa5448542009-02-13 15:32:32 +0000516 uint64_t BlockLiteralSize =
Mike Stump9b8a7972009-02-13 15:25:34 +0000517 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlssond5cab542009-02-12 17:55:02 +0000518 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpa5448542009-02-13 15:32:32 +0000519
520 llvm::Constant *DescriptorStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000521 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpa5448542009-02-13 15:32:32 +0000522
Anders Carlssond5cab542009-02-12 17:55:02 +0000523 llvm::GlobalVariable *Descriptor =
524 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000525 llvm::GlobalVariable::InternalLinkage,
526 DescriptorStruct, "__block_descriptor_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000527 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000528
Anders Carlssond5cab542009-02-12 17:55:02 +0000529 // Generate the constants for the block literal.
530 llvm::Constant *LiteralFields[5];
Mike Stumpa5448542009-02-13 15:32:32 +0000531
Mike Stump67a64482009-02-14 22:16:35 +0000532 CodeGenFunction::BlockInfo Info(0, n);
Mike Stump8a2b4b12009-02-25 23:33:13 +0000533 uint64_t subBlockSize, subBlockAlign;
Mike Stumpa99038c2009-02-28 09:07:16 +0000534 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000535 llvm::Function *Fn
Mike Stump90a90432009-03-04 18:47:42 +0000536 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
537 subBlockAlign,
538 subBlockDeclRefDecls);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000539 assert(subBlockSize == BlockLiteralSize
540 && "no imports allowed for global block");
Mike Stumpa5448542009-02-13 15:32:32 +0000541
Anders Carlssond5cab542009-02-12 17:55:02 +0000542 // isa
Mike Stumpf99f1d02009-02-13 17:23:42 +0000543 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpa5448542009-02-13 15:32:32 +0000544
Anders Carlssond5cab542009-02-12 17:55:02 +0000545 // Flags
Anders Carlsson8045ee02009-03-01 21:09:29 +0000546 LiteralFields[1] =
547 llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
Mike Stumpa5448542009-02-13 15:32:32 +0000548
Anders Carlssond5cab542009-02-12 17:55:02 +0000549 // Reserved
Mike Stump7cbb3602009-02-13 16:01:35 +0000550 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpa5448542009-02-13 15:32:32 +0000551
Anders Carlssond5cab542009-02-12 17:55:02 +0000552 // Function
553 LiteralFields[3] = Fn;
Mike Stumpa5448542009-02-13 15:32:32 +0000554
Anders Carlssond5cab542009-02-12 17:55:02 +0000555 // Descriptor
556 LiteralFields[4] = Descriptor;
Mike Stumpa5448542009-02-13 15:32:32 +0000557
558 llvm::Constant *BlockLiteralStruct =
Anders Carlssond5cab542009-02-12 17:55:02 +0000559 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpa5448542009-02-13 15:32:32 +0000560
561 llvm::GlobalVariable *BlockLiteral =
Anders Carlssond5cab542009-02-12 17:55:02 +0000562 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpa5448542009-02-13 15:32:32 +0000563 llvm::GlobalVariable::InternalLinkage,
564 BlockLiteralStruct, "__block_literal_global",
Anders Carlssond5cab542009-02-12 17:55:02 +0000565 &getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000566
Anders Carlssond5cab542009-02-12 17:55:02 +0000567 return BlockLiteral;
568}
569
Mike Stump4e7a1f72009-02-21 20:00:35 +0000570llvm::Value *CodeGenFunction::LoadBlockStruct() {
571 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
572}
573
Chris Lattner161d36d2009-02-28 19:01:03 +0000574llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
Mike Stump4e7a1f72009-02-21 20:00:35 +0000575 const BlockInfo& Info,
Mike Stump8a2b4b12009-02-25 23:33:13 +0000576 uint64_t &Size,
577 uint64_t &Align,
Mike Stumpa99038c2009-02-28 09:07:16 +0000578 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000579 const FunctionProtoType *FTy =
Chris Lattner161d36d2009-02-28 19:01:03 +0000580 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpa5448542009-02-13 15:32:32 +0000581
Anders Carlssond5cab542009-02-12 17:55:02 +0000582 FunctionArgList Args;
Mike Stumpa5448542009-02-13 15:32:32 +0000583
Chris Lattner161d36d2009-02-28 19:01:03 +0000584 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlssond5cab542009-02-12 17:55:02 +0000585
586 // FIXME: This leaks
Mike Stumpa5448542009-02-13 15:32:32 +0000587 ImplicitParamDecl *SelfDecl =
Anders Carlssond5cab542009-02-12 17:55:02 +0000588 ImplicitParamDecl::Create(getContext(), 0,
589 SourceLocation(), 0,
590 getContext().getPointerType(getContext().VoidTy));
Mike Stumpa5448542009-02-13 15:32:32 +0000591
Anders Carlssond5cab542009-02-12 17:55:02 +0000592 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stump4e7a1f72009-02-21 20:00:35 +0000593 BlockStructDecl = SelfDecl;
Mike Stumpa5448542009-02-13 15:32:32 +0000594
595 for (BlockDecl::param_iterator i = BD->param_begin(),
Anders Carlssond5cab542009-02-12 17:55:02 +0000596 e = BD->param_end(); i != e; ++i)
Mike Stump19050612009-02-17 23:25:52 +0000597 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpa5448542009-02-13 15:32:32 +0000598
599 const CGFunctionInfo &FI =
Anders Carlssond5cab542009-02-12 17:55:02 +0000600 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
601
Mike Stump67a64482009-02-14 22:16:35 +0000602 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlssond5cab542009-02-12 17:55:02 +0000603 CodeGenTypes &Types = CGM.getTypes();
604 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpa5448542009-02-13 15:32:32 +0000605
606 llvm::Function *Fn =
Anders Carlssond5cab542009-02-12 17:55:02 +0000607 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
608 Name,
609 &CGM.getModule());
Mike Stumpa5448542009-02-13 15:32:32 +0000610
611 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner161d36d2009-02-28 19:01:03 +0000612 BExpr->getBody()->getLocEnd());
613 EmitStmt(BExpr->getBody());
614 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlssond5cab542009-02-12 17:55:02 +0000615
Mike Stump8a2b4b12009-02-25 23:33:13 +0000616 // The runtime needs a minimum alignment of a void *.
617 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
618 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
619
Mike Stump4e7a1f72009-02-21 20:00:35 +0000620 Size = BlockOffset;
Mike Stump8a2b4b12009-02-25 23:33:13 +0000621 Align = BlockAlign;
622 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stump4e7a1f72009-02-21 20:00:35 +0000623
Anders Carlssond5cab542009-02-12 17:55:02 +0000624 return Fn;
625}
Mike Stumpa99038c2009-02-28 09:07:16 +0000626
627uint64_t CodeGenFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
628 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
629
630 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
631 uint64_t Align = getContext().getDeclAlignInBytes(D);
632
633 if (BDRE->isByRef()) {
634 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
635 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
636 }
637
638 assert ((Align > 0) && "alignment must be 1 byte or more");
639
640 uint64_t OldOffset = BlockOffset;
641
642 // Ensure proper alignment, even if it means we have to have a gap
643 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
644 BlockAlign = std::max(Align, BlockAlign);
645
646 uint64_t Pad = BlockOffset - OldOffset;
647 if (Pad) {
648 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
649 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
650 llvm::APInt(32, Pad),
651 ArrayType::Normal, 0);
652 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
653 0, QualType(PadTy), VarDecl::None,
654 SourceLocation());
655 Expr *E;
656 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
657 SourceLocation(), false, false);
658 BlockDeclRefDecls.push_back(E);
659 }
660 BlockDeclRefDecls.push_back(BDRE);
661
662 BlockOffset += Size;
663 return BlockOffset-Size;
664}
Mike Stumpdab514f2009-03-04 03:23:46 +0000665
Mike Stump3947de52009-03-04 18:57:26 +0000666llvm::Value *BlockFunction::BuildCopyHelper(int flag) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000667 // FIXME: implement
668 llvm::Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty, 43);
669 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "tmp");
670 V = Builder.CreateBitCast(V, PtrToInt8Ty, "tmp");
671 return V;
672}
673
Mike Stump3947de52009-03-04 18:57:26 +0000674llvm::Value *BlockFunction::BuildDestroyHelper(int flag) {
Mike Stumpdab514f2009-03-04 03:23:46 +0000675 // FIXME: implement
676 llvm::Value *V = llvm::ConstantInt::get(llvm::Type::Int32Ty, 44);
677 V = Builder.CreateIntToPtr(V, PtrToInt8Ty, "tmp");
678 V = Builder.CreateBitCast(V, PtrToInt8Ty, "tmp");
679 return V;
680}
Mike Stump797b6322009-03-05 01:23:13 +0000681
682llvm::Value *BlockFunction::getBlockObjectDispose() {
683 if (CGM.BlockObjectDispose == 0) {
684 const llvm::FunctionType *FTy;
685 std::vector<const llvm::Type*> ArgTys;
686 const llvm::Type *ResultType = llvm::Type::VoidTy;
687 ArgTys.push_back(PtrToInt8Ty);
688 ArgTys.push_back(llvm::Type::Int32Ty);
689 FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
690 CGM.BlockObjectDispose
691 = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
692 }
693 return CGM.BlockObjectDispose;
694}
695
696void BlockFunction::BuildBlockRelease(const VarDecl &D, llvm::Value *DeclPtr) {
697 llvm::Value *F = getBlockObjectDispose();
698 llvm::Value *N, *V;
699 V = Builder.CreateStructGEP(DeclPtr, 1, "forwarding");
700 V = Builder.CreateLoad(V, false);
701 V = Builder.CreateBitCast(V, PtrToInt8Ty);
702 N = llvm::ConstantInt::get(llvm::Type::Int32Ty, BLOCK_FIELD_IS_BYREF);
703 Builder.CreateCall2(F, V, N);
704}