blob: cb096fcacc0c35cc4b3a732d5bd147575e729b1c [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
Anders Carlssond5cab542009-02-12 17:55:02 +000024// Block flags
25enum {
26 IsGlobal = 1 << 28
27};
28
Mike Stumpab695142009-02-13 15:16:56 +000029const llvm::Type *CodeGenModule::getBlockDescriptorType() {
30 if (BlockDescriptorType)
31 return BlockDescriptorType;
32
33 const llvm::Type *UnsignedLongTy =
34 getTypes().ConvertType(getContext().UnsignedLongTy);
Anders Carlssonacfde802009-02-12 00:39:25 +000035
Mike Stumpab695142009-02-13 15:16:56 +000036 // struct __block_descriptor {
37 // unsigned long reserved;
38 // unsigned long block_size;
39 // };
40 BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
41 UnsignedLongTy,
42 NULL);
43
44 getModule().addTypeName("struct.__block_descriptor",
45 BlockDescriptorType);
46
47 return BlockDescriptorType;
Anders Carlssonacfde802009-02-12 00:39:25 +000048}
49
Anders Carlssond5cab542009-02-12 17:55:02 +000050static const llvm::Type *getGenericBlockLiteralType(CodeGenModule &CGM) {
Anders Carlssonacfde802009-02-12 00:39:25 +000051 static const llvm::Type *Ty = 0;
52
53 if (!Ty) {
54 const llvm::Type *Int8PtrTy =
55 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
56
57 const llvm::Type *BlockDescPtrTy =
Mike Stumpab695142009-02-13 15:16:56 +000058 llvm::PointerType::getUnqual(CGM.getBlockDescriptorType());
Anders Carlssonacfde802009-02-12 00:39:25 +000059
60 // struct __block_literal_generic {
61 // void *isa;
62 // int flags;
63 // int reserved;
64 // void (*invoke)(void *);
65 // struct __block_descriptor *descriptor;
66 // };
67 Ty = llvm::StructType::get(Int8PtrTy,
68 llvm::Type::Int32Ty,
69 llvm::Type::Int32Ty,
70 Int8PtrTy,
71 BlockDescPtrTy,
72 NULL);
73
Anders Carlssond5cab542009-02-12 17:55:02 +000074 CGM.getModule().addTypeName("struct.__block_literal_generic", Ty);
Anders Carlssonacfde802009-02-12 00:39:25 +000075 }
76
77 return Ty;
78}
79
80/// getBlockFunctionType - Given a BlockPointerType, will return the
81/// function type for the block, including the first block literal argument.
82static QualType getBlockFunctionType(ASTContext &Ctx,
Anders Carlssond5cab542009-02-12 17:55:02 +000083 const BlockPointerType *BPT) {
Anders Carlssonacfde802009-02-12 00:39:25 +000084 const FunctionTypeProto *FTy = cast<FunctionTypeProto>(BPT->getPointeeType());
85
86 llvm::SmallVector<QualType, 8> Types;
87 Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
88
89 for (FunctionTypeProto::arg_type_iterator i = FTy->arg_type_begin(),
90 e = FTy->arg_type_end(); i != e; ++i)
91 Types.push_back(*i);
92
93 return Ctx.getFunctionType(FTy->getResultType(),
94 &Types[0], Types.size(),
95 FTy->isVariadic(), 0);
96}
97
Anders Carlssond5cab542009-02-12 17:55:02 +000098RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
Anders Carlssonacfde802009-02-12 00:39:25 +000099 const BlockPointerType *BPT =
100 E->getCallee()->getType()->getAsBlockPointerType();
101
102 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
103
104 // Get a pointer to the generic block literal.
105 const llvm::Type *BlockLiteralTy =
Anders Carlssond5cab542009-02-12 17:55:02 +0000106 llvm::PointerType::getUnqual(getGenericBlockLiteralType(CGM));
Anders Carlssonacfde802009-02-12 00:39:25 +0000107
108 // Bitcast the callee to a block literal.
109 llvm::Value *BlockLiteral =
110 Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
111
112 // Get the function pointer from the literal.
113 llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
114 llvm::Value *Func = Builder.CreateLoad(FuncPtr, FuncPtr, "tmp");
115
116 // Cast the function pointer to the right type.
117 const llvm::Type *BlockFTy =
118 ConvertType(getBlockFunctionType(getContext(), BPT));
119 const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
120 Func = Builder.CreateBitCast(Func, BlockFTyPtr);
121
122 BlockLiteral =
123 Builder.CreateBitCast(BlockLiteral,
124 llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
125 "tmp");
126
127 // Add the block literal.
128 QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
129 CallArgList Args;
130 Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
131
132 // And the rest of the arguments.
133 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
134 i != e; ++i)
135 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
136 i->getType()));
137
138 // And call the block.
139 return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
140 Func, Args);
141}
Anders Carlssond5cab542009-02-12 17:55:02 +0000142
143llvm::Constant *CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE) {
144 if (!NSConcreteGlobalBlock) {
145 const llvm::Type *Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
146
147 // FIXME: Wee should have a CodeGenModule::AddRuntimeVariable that does the
148 // same thing as CreateRuntimeFunction if there's already a variable with
149 // the same name.
150 NSConcreteGlobalBlock =
151 new llvm::GlobalVariable(Ty, false,
152 llvm::GlobalVariable::ExternalLinkage, 0,
153 "_NSConcreteGlobalBlock", &getModule());
154 }
155
156 // Generate the block descriptor.
157 const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
158
159 llvm::Constant *DescriptorFields[2];
160
161 // Reserved
162 DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
163
164 // Block literal size. For global blocks we just use the size of the generic
165 // block literal struct.
166 uint64_t BlockLiteralSize =
167 TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType(*this)) / 8;
168 DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
169
170 llvm::Constant *DescriptorStruct =
171 llvm::ConstantStruct::get(&DescriptorFields[0], 2);
172
173 llvm::GlobalVariable *Descriptor =
174 new llvm::GlobalVariable(DescriptorStruct->getType(), true,
175 llvm::GlobalVariable::InternalLinkage,
176 DescriptorStruct, "__block_descriptor_global",
177 &getModule());
178
179 // Generate the constants for the block literal.
180 llvm::Constant *LiteralFields[5];
181
182 CodeGenFunction::BlockInfo Info(0, "global");
183 llvm::Function *Fn = CodeGenFunction(*this).GenerateBlockFunction(BE, Info);
184
185 // isa
186 LiteralFields[0] = NSConcreteGlobalBlock;
187
188 // Flags
189 LiteralFields[1] = llvm::ConstantInt::get(llvm::Type::Int32Ty, IsGlobal);
190
191 // Reserved
192 LiteralFields[2] = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
193
194 // Function
195 LiteralFields[3] = Fn;
196
197 // Descriptor
198 LiteralFields[4] = Descriptor;
199
200 llvm::Constant *BlockLiteralStruct =
201 llvm::ConstantStruct::get(&LiteralFields[0], 5);
202
203 llvm::GlobalVariable *BlockLiteral =
204 new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
205 llvm::GlobalVariable::InternalLinkage,
206 BlockLiteralStruct, "__block_literal_global",
207 &getModule());
208
209 return BlockLiteral;
210}
211
212llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *Expr,
213 const BlockInfo& Info)
214{
215 const FunctionTypeProto *FTy =
216 cast<FunctionTypeProto>(Expr->getFunctionType());
217
218 FunctionArgList Args;
219
220 const BlockDecl *BD = Expr->getBlockDecl();
221
222 // FIXME: This leaks
223 ImplicitParamDecl *SelfDecl =
224 ImplicitParamDecl::Create(getContext(), 0,
225 SourceLocation(), 0,
226 getContext().getPointerType(getContext().VoidTy));
227
228 Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
229
230 for (BlockDecl::param_iterator i = BD->param_begin(),
231 e = BD->param_end(); i != e; ++i)
232 Args.push_back(std::make_pair(*e, (*e)->getType()));
233
234 const CGFunctionInfo &FI =
235 CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
236
237 std::string Name = std::string("__block_function_") + Info.NameSuffix;
238
239 CodeGenTypes &Types = CGM.getTypes();
240 const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
241
242 llvm::Function *Fn =
243 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
244 Name,
245 &CGM.getModule());
246
247 StartFunction(BD, FTy->getResultType(), Fn, Args,
248 Expr->getBody()->getLocEnd());
249 EmitStmt(Expr->getBody());
250 FinishFunction(cast<CompoundStmt>(Expr->getBody())->getRBracLoc());
251
252 return Fn;
253}
254
255