blob: ba9480fa0e4eaa952b5cec2ea7713a6c3230b96a [file] [log] [blame]
Anders Carlsson2437cbf2009-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 Carlsson6a60fa22009-02-12 17:55:02 +000017#include "llvm/Target/TargetData.h"
Anders Carlsson2437cbf2009-02-12 00:39:25 +000018
19#include <algorithm>
20
21using namespace clang;
22using namespace CodeGen;
23
Anders Carlsson6a60fa22009-02-12 17:55:02 +000024enum {
Mike Stump85284ba2009-02-13 16:19:19 +000025 BLOCK_NEEDS_FREE = (1 << 24),
26 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
27 BLOCK_HAS_CXX_OBJ = (1 << 26),
28 BLOCK_IS_GC = (1 << 27),
29 BLOCK_IS_GLOBAL = (1 << 28),
30 BLOCK_HAS_DESCRIPTOR = (1 << 29)
Anders Carlsson6a60fa22009-02-12 17:55:02 +000031};
32
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000033llvm::Constant *CodeGenFunction::BuildDescriptorBlockDecl(uint64_t Size) {
Mike Stump85284ba2009-02-13 16:19:19 +000034 const llvm::PointerType *PtrToInt8Ty
35 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stumpc2c38332009-02-13 16:55:51 +000036 const llvm::Type *UnsignedLongTy
37 = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stump85284ba2009-02-13 16:19:19 +000038 llvm::Constant *C;
39 std::vector<llvm::Constant*> Elts;
40
41 // reserved
Mike Stumpc2c38332009-02-13 16:55:51 +000042 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000043 Elts.push_back(C);
44
45 // Size
Mike Stump2ac40a92009-02-21 20:07:44 +000046 // FIXME: What is the right way to say this doesn't fit? We should give
47 // a user diagnostic in that case. Better fix would be to change the
48 // API to size_t.
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000049 C = llvm::ConstantInt::get(UnsignedLongTy, Size);
Mike Stump85284ba2009-02-13 16:19:19 +000050 Elts.push_back(C);
51
52 if (BlockHasCopyDispose) {
53 // copy_func_helper_decl
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000054 // FIXME: implement
Mike Stumpc2c38332009-02-13 16:55:51 +000055 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000056 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
57 Elts.push_back(C);
58
59 // destroy_func_decl
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000060 // FIXME: implement
Mike Stumpc2c38332009-02-13 16:55:51 +000061 C = llvm::ConstantInt::get(UnsignedLongTy, 0);
Mike Stump85284ba2009-02-13 16:19:19 +000062 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
63 Elts.push_back(C);
64 }
65
66 C = llvm::ConstantStruct::get(Elts);
67
Mike Stump85284ba2009-02-13 16:19:19 +000068 C = new llvm::GlobalVariable(C->getType(), true,
69 llvm::GlobalValue::InternalLinkage,
Mike Stump499ae7e2009-02-13 20:17:16 +000070 C, "__block_descriptor_tmp", &CGM.getModule());
Mike Stump85284ba2009-02-13 16:19:19 +000071 return C;
72}
73
Mike Stump971f9b62009-02-13 17:23:42 +000074llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
75 if (NSConcreteGlobalBlock)
76 return NSConcreteGlobalBlock;
77
78 const llvm::PointerType *PtrToInt8Ty
79 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stump52d9c492009-02-13 19:38:12 +000080 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump971f9b62009-02-13 17:23:42 +000081 // same thing as CreateRuntimeFunction if there's already a variable with
82 // the same name.
83 NSConcreteGlobalBlock
84 = new llvm::GlobalVariable(PtrToInt8Ty, false,
85 llvm::GlobalValue::ExternalLinkage,
86 0, "_NSConcreteGlobalBlock",
87 &getModule());
88
89 return NSConcreteGlobalBlock;
90}
91
Mike Stump7ab278d2009-02-13 19:29:27 +000092llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
93 if (NSConcreteStackBlock)
94 return NSConcreteStackBlock;
95
96 const llvm::PointerType *PtrToInt8Ty
97 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stump52d9c492009-02-13 19:38:12 +000098 // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
Mike Stump7ab278d2009-02-13 19:29:27 +000099 // same thing as CreateRuntimeFunction if there's already a variable with
100 // the same name.
101 NSConcreteStackBlock
102 = new llvm::GlobalVariable(PtrToInt8Ty, false,
103 llvm::GlobalValue::ExternalLinkage,
104 0, "_NSConcreteStackBlock",
105 &getModule());
106
107 return NSConcreteStackBlock;
108}
109
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000110static void CollectBlockDeclRefInfo(const Stmt *S,
111 CodeGenFunction::BlockInfo &Info) {
112 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
113 I != E; ++I)
114 CollectBlockDeclRefInfo(*I, Info);
115
116 if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
117 // FIXME: Handle enums.
118 if (isa<FunctionDecl>(DE->getDecl()))
119 return;
120
121 if (DE->isByRef())
122 Info.ByRefDeclRefs.push_back(DE);
123 else
124 Info.ByCopyDeclRefs.push_back(DE);
125 }
126}
127
128/// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block
129/// can be declared as a global variable instead of on the stack.
130static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
131{
132 return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
133}
134
Anders Carlsson961763e2009-03-01 01:45:25 +0000135/// CanGenerateCodeForBlockExpr - Returns whether CodeGen for the block expr
136/// is supported. Will emit a diagnostic and return false if not.
137/// FIXME: Once we support everything this should of course be removed.
138static bool CanGenerateCodeForBlockExpr(CodeGenFunction &CGF,
139 const BlockExpr* BE,
140 const CodeGenFunction::BlockInfo &Info)
141{
142 if (!Info.ByRefDeclRefs.empty()) {
143 CGF.ErrorUnsupported(BE, "block expression with __block variables");
144 return false;
145 }
146
147 for (size_t I = 0, E = Info.ByCopyDeclRefs.size(); I != E; ++I) {
148 const BlockDeclRefExpr *E = Info.ByCopyDeclRefs[I];
149
150 E->getType()->dump();
151
152 if (E->getType()->isBlockPointerType()) {
153 CGF.ErrorUnsupported(BE, "block expression with imported block");
154 return false;
155 }
156
157 if (E->getDecl()->getAttr<ObjCNSObjectAttr>() ||
158 CGF.getContext().isObjCNSObjectType(E->getType())) {
159 CGF.ErrorUnsupported(BE, "block expression with __attribute__((NSObject))"
160 " variable");
161 return false;
162 }
163
164 if (CGF.getContext().isObjCObjectPointerType(E->getType())) {
165 CGF.ErrorUnsupported(BE, "block expression with Objective-C variable");
166 return false;
167 }
168 }
169
170 return true;
171}
172
Mike Stump5d2534ad2009-02-19 01:01:04 +0000173// FIXME: Push most into CGM, passing down a few bits, like current
174// function name.
Mike Stumpb750d922009-02-25 23:33:13 +0000175llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
Mike Stump85284ba2009-02-13 16:19:19 +0000176
Anders Carlssoned5e69f2009-03-01 01:09:12 +0000177 std::string Name = CurFn->getName();
178 CodeGenFunction::BlockInfo Info(0, Name.c_str());
179 CollectBlockDeclRefInfo(BE->getBody(), Info);
180
181 // Check if the block can be global.
182 if (CanBlockBeGlobal(Info))
183 return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
184
Anders Carlsson961763e2009-03-01 01:45:25 +0000185 if (!CanGenerateCodeForBlockExpr(*this, BE, Info))
186 return llvm::UndefValue::get(ConvertType(BE->getType()));
187
Mike Stump85284ba2009-02-13 16:19:19 +0000188 std::vector<llvm::Constant*> Elts;
189 llvm::Constant *C;
Mike Stumpb750d922009-02-25 23:33:13 +0000190 llvm::Value *V;
Mike Stump85284ba2009-02-13 16:19:19 +0000191
Mike Stump85284ba2009-02-13 16:19:19 +0000192 {
193 // C = BuildBlockStructInitlist();
194 unsigned int flags = BLOCK_HAS_DESCRIPTOR;
195
196 if (BlockHasCopyDispose)
197 flags |= BLOCK_HAS_COPY_DISPOSE;
198
Mike Stump499ae7e2009-02-13 20:17:16 +0000199 // __isa
Mike Stump7ab278d2009-02-13 19:29:27 +0000200 C = CGM.getNSConcreteStackBlock();
Mike Stump7ab278d2009-02-13 19:29:27 +0000201 const llvm::PointerType *PtrToInt8Ty
202 = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stump85284ba2009-02-13 16:19:19 +0000203 C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
204 Elts.push_back(C);
205
206 // __flags
207 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
208 CGM.getTypes().ConvertType(CGM.getContext().IntTy));
209 C = llvm::ConstantInt::get(IntTy, flags);
210 Elts.push_back(C);
211
212 // __reserved
213 C = llvm::ConstantInt::get(IntTy, 0);
214 Elts.push_back(C);
215
Mike Stump5d2534ad2009-02-19 01:01:04 +0000216 // __invoke
Mike Stumpb750d922009-02-25 23:33:13 +0000217 uint64_t subBlockSize, subBlockAlign;
Mike Stump1db7d042009-02-28 09:07:16 +0000218 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000219 llvm::Function *Fn
Mike Stumpb750d922009-02-25 23:33:13 +0000220 = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
221 subBlockAlign, subBlockDeclRefDecls);
Mike Stump2d5a2872009-02-14 22:16:35 +0000222 Elts.push_back(Fn);
Mike Stump85284ba2009-02-13 16:19:19 +0000223
224 // __descriptor
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000225 Elts.push_back(BuildDescriptorBlockDecl(subBlockSize));
Mike Stump85284ba2009-02-13 16:19:19 +0000226
Mike Stumpb750d922009-02-25 23:33:13 +0000227 if (subBlockDeclRefDecls.size() == 0) {
228 C = llvm::ConstantStruct::get(Elts);
229
230 char Name[32];
231 sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
232 C = new llvm::GlobalVariable(C->getType(), true,
233 llvm::GlobalValue::InternalLinkage,
234 C, Name, &CGM.getModule());
235 QualType BPT = BE->getType();
236 C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
237 return C;
238 }
239
240 std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
241 for (int i=0; i<5; ++i)
242 Types[i] = Elts[i]->getType();
243
Mike Stump1db7d042009-02-28 09:07:16 +0000244 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
245 const Expr *E = subBlockDeclRefDecls[i];
246 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
247 QualType Ty = E->getType();
248 if (BDRE && BDRE->isByRef())
249 Ty = getContext().getPointerType(Ty);
250 Types[i+5] = ConvertType(Ty);
251 }
Mike Stumpb750d922009-02-25 23:33:13 +0000252
253 llvm::Type *Ty = llvm::StructType::get(Types, true);
254
255 llvm::AllocaInst *A = CreateTempAlloca(Ty);
256 A->setAlignment(subBlockAlign);
257 V = A;
258
259 for (unsigned i=0; i<5; ++i)
260 Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
261
262 for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
263 {
Mike Stump1db7d042009-02-28 09:07:16 +0000264 // FIXME: Push const down.
265 Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
266 DeclRefExpr *DR;
267 ValueDecl *VD;
Mike Stumpb750d922009-02-25 23:33:13 +0000268
Mike Stump1db7d042009-02-28 09:07:16 +0000269 DR = dyn_cast<DeclRefExpr>(E);
270 // Skip padding.
271 if (DR) continue;
272
273 BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
274 VD = BDRE->getDecl();
275
276 // FIXME: I want a better way to do this.
277 if (LocalDeclMap[VD]) {
278 E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
279 VD->getType(), SourceLocation(),
280 false, false);
281 }
282 if (BDRE->isByRef())
283 E = new (getContext())
284 UnaryOperator(E, UnaryOperator::AddrOf,
285 getContext().getPointerType(E->getType()),
286 SourceLocation());
287
Mike Stumpb750d922009-02-25 23:33:13 +0000288 llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
Mike Stump1db7d042009-02-28 09:07:16 +0000289 RValue r = EmitAnyExpr(E, Addr, false);
Mike Stumpb750d922009-02-25 23:33:13 +0000290 if (r.isScalar())
291 Builder.CreateStore(r.getScalarVal(), Addr);
292 else if (r.isComplex())
293 // FIXME: implement
294 ErrorUnsupported(BE, "complex in block literal");
295 else if (r.isAggregate())
296 ; // Already created into the destination
297 else
298 assert (0 && "bad block variable");
299 // FIXME: Ensure that the offset created by the backend for
300 // the struct matches the previously computed offset in BlockDecls.
301 }
Mike Stump85284ba2009-02-13 16:19:19 +0000302 }
303
Mike Stump5d2534ad2009-02-19 01:01:04 +0000304 QualType BPT = BE->getType();
Mike Stumpb750d922009-02-25 23:33:13 +0000305 return Builder.CreateBitCast(V, ConvertType(BPT));
Mike Stump85284ba2009-02-13 16:19:19 +0000306}
307
308
Mike Stump650c9322009-02-13 15:16:56 +0000309const llvm::Type *CodeGenModule::getBlockDescriptorType() {
310 if (BlockDescriptorType)
311 return BlockDescriptorType;
312
Mike Stumpb7074c02009-02-13 15:32:32 +0000313 const llvm::Type *UnsignedLongTy =
Mike Stump650c9322009-02-13 15:16:56 +0000314 getTypes().ConvertType(getContext().UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000315
Mike Stump650c9322009-02-13 15:16:56 +0000316 // struct __block_descriptor {
317 // unsigned long reserved;
318 // unsigned long block_size;
319 // };
Mike Stumpb7074c02009-02-13 15:32:32 +0000320 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
321 UnsignedLongTy,
Mike Stump650c9322009-02-13 15:16:56 +0000322 NULL);
323
324 getModule().addTypeName("struct.__block_descriptor",
325 BlockDescriptorType);
326
327 return BlockDescriptorType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000328}
329
Mike Stump005c9a62009-02-13 15:25:34 +0000330const llvm::Type *
331CodeGenModule::getGenericBlockLiteralType() {
332 if (GenericBlockLiteralType)
333 return GenericBlockLiteralType;
334
Mike Stumpb7074c02009-02-13 15:32:32 +0000335 const llvm::Type *Int8PtrTy =
Mike Stump005c9a62009-02-13 15:25:34 +0000336 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Mike Stumpb7074c02009-02-13 15:32:32 +0000337
338 const llvm::Type *BlockDescPtrTy =
Mike Stump005c9a62009-02-13 15:25:34 +0000339 llvm::PointerType::getUnqual(getBlockDescriptorType());
Mike Stumpb7074c02009-02-13 15:32:32 +0000340
Mike Stump92bbd6d2009-02-13 16:01:35 +0000341 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
342 getTypes().ConvertType(getContext().IntTy));
343
Mike Stump005c9a62009-02-13 15:25:34 +0000344 // struct __block_literal_generic {
Mike Stump5d2534ad2009-02-19 01:01:04 +0000345 // void *__isa;
346 // int __flags;
347 // int __reserved;
348 // void (*__invoke)(void *);
349 // struct __block_descriptor *__descriptor;
Mike Stump005c9a62009-02-13 15:25:34 +0000350 // };
351 GenericBlockLiteralType = llvm::StructType::get(Int8PtrTy,
Mike Stump92bbd6d2009-02-13 16:01:35 +0000352 IntTy,
353 IntTy,
Mike Stump005c9a62009-02-13 15:25:34 +0000354 Int8PtrTy,
355 BlockDescPtrTy,
356 NULL);
Mike Stumpb7074c02009-02-13 15:32:32 +0000357
Mike Stump005c9a62009-02-13 15:25:34 +0000358 getModule().addTypeName("struct.__block_literal_generic",
359 GenericBlockLiteralType);
Mike Stumpb7074c02009-02-13 15:32:32 +0000360
Mike Stump005c9a62009-02-13 15:25:34 +0000361 return GenericBlockLiteralType;
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000362}
363
Mike Stump5d2534ad2009-02-19 01:01:04 +0000364const llvm::Type *
365CodeGenModule::getGenericExtendedBlockLiteralType() {
366 if (GenericExtendedBlockLiteralType)
367 return GenericExtendedBlockLiteralType;
368
369 const llvm::Type *Int8PtrTy =
370 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
371
372 const llvm::Type *BlockDescPtrTy =
373 llvm::PointerType::getUnqual(getBlockDescriptorType());
374
375 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
376 getTypes().ConvertType(getContext().IntTy));
377
378 // struct __block_literal_generic {
379 // void *__isa;
380 // int __flags;
381 // int __reserved;
382 // void (*__invoke)(void *);
383 // struct __block_descriptor *__descriptor;
384 // void *__copy_func_helper_decl;
385 // void *__destroy_func_decl;
386 // };
387 GenericExtendedBlockLiteralType = llvm::StructType::get(Int8PtrTy,
388 IntTy,
389 IntTy,
390 Int8PtrTy,
391 BlockDescPtrTy,
392 Int8PtrTy,
393 Int8PtrTy,
394 NULL);
395
396 getModule().addTypeName("struct.__block_literal_extended_generic",
397 GenericExtendedBlockLiteralType);
398
399 return GenericExtendedBlockLiteralType;
400}
401
Mike Stumpb7074c02009-02-13 15:32:32 +0000402/// getBlockFunctionType - Given a BlockPointerType, will return the
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000403/// function type for the block, including the first block literal argument.
404static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000405 const BlockPointerType *BPT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000406 const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
Mike Stumpb7074c02009-02-13 15:32:32 +0000407
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000408 llvm::SmallVector<QualType, 8> Types;
409 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
Mike Stumpb7074c02009-02-13 15:32:32 +0000410
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000411 for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000412 e = FTy->arg_type_end(); i != e; ++i)
413 Types.push_back(*i);
Mike Stumpb7074c02009-02-13 15:32:32 +0000414
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000415 return Ctx.getFunctionType(FTy->getResultType(),
Mike Stumpb7074c02009-02-13 15:32:32 +0000416 &Types[0], Types.size(),
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000417 FTy->isVariadic(), 0);
418}
419
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000420RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Mike Stumpb7074c02009-02-13 15:32:32 +0000421 const BlockPointerType *BPT =
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000422 E->getCallee()->getType()->getAsBlockPointerType();
Mike Stumpb7074c02009-02-13 15:32:32 +0000423
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000424 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
425
426 // Get a pointer to the generic block literal.
427 const llvm::Type *BlockLiteralTy =
Mike Stump005c9a62009-02-13 15:25:34 +0000428 llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000429
430 // Bitcast the callee to a block literal.
Mike Stumpb7074c02009-02-13 15:32:32 +0000431 llvm::Value *BlockLiteral =
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000432 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
433
434 // Get the function pointer from the literal.
435 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
Mike Stump624497c2009-02-22 13:27:11 +0000436 llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000437
438 // Cast the function pointer to the right type.
Mike Stumpb7074c02009-02-13 15:32:32 +0000439 const llvm::Type *BlockFTy =
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000440 ConvertType(getBlockFunctionType(getContext(), BPT));
441 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
442 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
443
Mike Stumpb7074c02009-02-13 15:32:32 +0000444 BlockLiteral =
445 Builder.CreateBitCast(BlockLiteral,
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000446 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
447 "tmp");
Mike Stumpb7074c02009-02-13 15:32:32 +0000448
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000449 // Add the block literal.
450 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
451 CallArgList Args;
452 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
Mike Stumpb7074c02009-02-13 15:32:32 +0000453
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000454 // And the rest of the arguments.
Mike Stumpb7074c02009-02-13 15:32:32 +0000455 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000456 i != e; ++i)
Mike Stumpb7074c02009-02-13 15:32:32 +0000457 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000458 i->getType()));
Mike Stumpb7074c02009-02-13 15:32:32 +0000459
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000460 // And call the block.
Mike Stumpb7074c02009-02-13 15:32:32 +0000461 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
Anders Carlsson2437cbf2009-02-12 00:39:25 +0000462 Func, Args);
463}
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000464
Mike Stump2d5a2872009-02-14 22:16:35 +0000465llvm::Constant *
Mike Stump0e7d7b62009-02-14 22:49:33 +0000466CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000467 // Generate the block descriptor.
468 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
Mike Stump92bbd6d2009-02-13 16:01:35 +0000469 const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
470 getTypes().ConvertType(getContext().IntTy));
Mike Stumpb7074c02009-02-13 15:32:32 +0000471
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000472 llvm::Constant *DescriptorFields[2];
Mike Stumpb7074c02009-02-13 15:32:32 +0000473
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000474 // Reserved
475 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000476
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000477 // Block literal size. For global blocks we just use the size of the generic
478 // block literal struct.
Mike Stumpb7074c02009-02-13 15:32:32 +0000479 uint64_t BlockLiteralSize =
Mike Stump005c9a62009-02-13 15:25:34 +0000480 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000481 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
Mike Stumpb7074c02009-02-13 15:32:32 +0000482
483 llvm::Constant *DescriptorStruct =
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000484 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
Mike Stumpb7074c02009-02-13 15:32:32 +0000485
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000486 llvm::GlobalVariable *Descriptor =
487 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
Mike Stumpb7074c02009-02-13 15:32:32 +0000488 llvm::GlobalVariable::InternalLinkage,
489 DescriptorStruct, "__block_descriptor_global",
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000490 &getModule());
Mike Stumpb7074c02009-02-13 15:32:32 +0000491
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000492 // Generate the constants for the block literal.
493 llvm::Constant *LiteralFields[5];
Mike Stumpb7074c02009-02-13 15:32:32 +0000494
Mike Stump2d5a2872009-02-14 22:16:35 +0000495 CodeGenFunction::BlockInfo Info(0, n);
Mike Stumpb750d922009-02-25 23:33:13 +0000496 uint64_t subBlockSize, subBlockAlign;
Mike Stump1db7d042009-02-28 09:07:16 +0000497 llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000498 llvm::Function *Fn
Mike Stumpb750d922009-02-25 23:33:13 +0000499 = CodeGenFunction(*this).GenerateBlockFunction(BE, Info, subBlockSize,
500 subBlockAlign,
501 subBlockDeclRefDecls);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000502 assert(subBlockSize == BlockLiteralSize
503 && "no imports allowed for global block");
Mike Stumpb7074c02009-02-13 15:32:32 +0000504
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000505 // isa
Mike Stump971f9b62009-02-13 17:23:42 +0000506 LiteralFields[0] = getNSConcreteGlobalBlock();
Mike Stumpb7074c02009-02-13 15:32:32 +0000507
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000508 // Flags
Mike Stump85284ba2009-02-13 16:19:19 +0000509 LiteralFields[1] = llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL);
Mike Stumpb7074c02009-02-13 15:32:32 +0000510
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000511 // Reserved
Mike Stump92bbd6d2009-02-13 16:01:35 +0000512 LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
Mike Stumpb7074c02009-02-13 15:32:32 +0000513
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000514 // Function
515 LiteralFields[3] = Fn;
Mike Stumpb7074c02009-02-13 15:32:32 +0000516
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000517 // Descriptor
518 LiteralFields[4] = Descriptor;
Mike Stumpb7074c02009-02-13 15:32:32 +0000519
520 llvm::Constant *BlockLiteralStruct =
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000521 llvm::ConstantStruct::get(&LiteralFields[0], 5);
Mike Stumpb7074c02009-02-13 15:32:32 +0000522
523 llvm::GlobalVariable *BlockLiteral =
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000524 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
Mike Stumpb7074c02009-02-13 15:32:32 +0000525 llvm::GlobalVariable::InternalLinkage,
526 BlockLiteralStruct, "__block_literal_global",
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000527 &getModule());
Mike Stumpb7074c02009-02-13 15:32:32 +0000528
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000529 return BlockLiteral;
530}
531
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000532llvm::Value *CodeGenFunction::LoadBlockStruct() {
533 return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
534}
535
Chris Lattner3385fe122009-02-28 19:01:03 +0000536llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000537 const BlockInfo& Info,
Mike Stumpb750d922009-02-25 23:33:13 +0000538 uint64_t &Size,
539 uint64_t &Align,
Mike Stump1db7d042009-02-28 09:07:16 +0000540 llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000541 const FunctionProtoType *FTy =
Chris Lattner3385fe122009-02-28 19:01:03 +0000542 cast<FunctionProtoType>(BExpr->getFunctionType());
Mike Stumpb7074c02009-02-13 15:32:32 +0000543
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000544 FunctionArgList Args;
Mike Stumpb7074c02009-02-13 15:32:32 +0000545
Chris Lattner3385fe122009-02-28 19:01:03 +0000546 const BlockDecl *BD = BExpr->getBlockDecl();
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000547
548 // FIXME: This leaks
Mike Stumpb7074c02009-02-13 15:32:32 +0000549 ImplicitParamDecl *SelfDecl =
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000550 ImplicitParamDecl::Create(getContext(), 0,
551 SourceLocation(), 0,
552 getContext().getPointerType(getContext().VoidTy));
Mike Stumpb7074c02009-02-13 15:32:32 +0000553
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000554 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000555 BlockStructDecl = SelfDecl;
Mike Stumpb7074c02009-02-13 15:32:32 +0000556
557 for (BlockDecl::param_iterator i = BD->param_begin(),
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000558 e = BD->param_end(); i != e; ++i)
Mike Stumpeecd39f2009-02-17 23:25:52 +0000559 Args.push_back(std::make_pair(*i, (*i)->getType()));
Mike Stumpb7074c02009-02-13 15:32:32 +0000560
561 const CGFunctionInfo &FI =
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000562 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
563
Mike Stump2d5a2872009-02-14 22:16:35 +0000564 std::string Name = std::string("__") + Info.Name + "_block_invoke_";
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000565 CodeGenTypes &Types = CGM.getTypes();
566 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
Mike Stumpb7074c02009-02-13 15:32:32 +0000567
568 llvm::Function *Fn =
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000569 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
570 Name,
571 &CGM.getModule());
Mike Stumpb7074c02009-02-13 15:32:32 +0000572
573 StartFunction(BD, FTy->getResultType(), Fn, Args,
Chris Lattner3385fe122009-02-28 19:01:03 +0000574 BExpr->getBody()->getLocEnd());
575 EmitStmt(BExpr->getBody());
576 FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000577
Mike Stumpb750d922009-02-25 23:33:13 +0000578 // The runtime needs a minimum alignment of a void *.
579 uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
580 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
581
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000582 Size = BlockOffset;
Mike Stumpb750d922009-02-25 23:33:13 +0000583 Align = BlockAlign;
584 subBlockDeclRefDecls = BlockDeclRefDecls;
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000585
Anders Carlsson6a60fa22009-02-12 17:55:02 +0000586 return Fn;
587}
Mike Stump1db7d042009-02-28 09:07:16 +0000588
589uint64_t CodeGenFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
590 const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
591
592 uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
593 uint64_t Align = getContext().getDeclAlignInBytes(D);
594
595 if (BDRE->isByRef()) {
596 Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
597 Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
598 }
599
600 assert ((Align > 0) && "alignment must be 1 byte or more");
601
602 uint64_t OldOffset = BlockOffset;
603
604 // Ensure proper alignment, even if it means we have to have a gap
605 BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
606 BlockAlign = std::max(Align, BlockAlign);
607
608 uint64_t Pad = BlockOffset - OldOffset;
609 if (Pad) {
610 llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
611 QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
612 llvm::APInt(32, Pad),
613 ArrayType::Normal, 0);
614 ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
615 0, QualType(PadTy), VarDecl::None,
616 SourceLocation());
617 Expr *E;
618 E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
619 SourceLocation(), false, false);
620 BlockDeclRefDecls.push_back(E);
621 }
622 BlockDeclRefDecls.push_back(BDRE);
623
624 BlockOffset += Size;
625 return BlockOffset-Size;
626}