12437cbfaSAnders Carlsson //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
22437cbfaSAnders Carlsson //
32437cbfaSAnders Carlsson //                     The LLVM Compiler Infrastructure
42437cbfaSAnders Carlsson //
52437cbfaSAnders Carlsson // This file is distributed under the University of Illinois Open Source
62437cbfaSAnders Carlsson // License. See LICENSE.TXT for details.
72437cbfaSAnders Carlsson //
82437cbfaSAnders Carlsson //===----------------------------------------------------------------------===//
92437cbfaSAnders Carlsson //
102437cbfaSAnders Carlsson // This contains code to emit blocks.
112437cbfaSAnders Carlsson //
122437cbfaSAnders Carlsson //===----------------------------------------------------------------------===//
132437cbfaSAnders Carlsson 
142437cbfaSAnders Carlsson #include "CodeGenFunction.h"
152437cbfaSAnders Carlsson #include "CodeGenModule.h"
162437cbfaSAnders Carlsson #include "llvm/Module.h"
176a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
182437cbfaSAnders Carlsson 
192437cbfaSAnders Carlsson #include <algorithm>
202437cbfaSAnders Carlsson 
212437cbfaSAnders Carlsson using namespace clang;
222437cbfaSAnders Carlsson using namespace CodeGen;
232437cbfaSAnders Carlsson 
246a60fa24SAnders Carlsson enum {
2585284bacSMike Stump   BLOCK_NEEDS_FREE =        (1 << 24),
2685284bacSMike Stump   BLOCK_HAS_COPY_DISPOSE =  (1 << 25),
2785284bacSMike Stump   BLOCK_HAS_CXX_OBJ =       (1 << 26),
2885284bacSMike Stump   BLOCK_IS_GC =             (1 << 27),
2985284bacSMike Stump   BLOCK_IS_GLOBAL =         (1 << 28),
3085284bacSMike Stump   BLOCK_HAS_DESCRIPTOR =    (1 << 29)
316a60fa24SAnders Carlsson };
326a60fa24SAnders Carlsson 
33cb2fbcb0SMike Stump llvm::Constant *CodeGenFunction::BuildDescriptorBlockDecl(uint64_t Size) {
3485284bacSMike Stump   const llvm::PointerType *PtrToInt8Ty
3585284bacSMike Stump     = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
36c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
37c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
3885284bacSMike Stump   llvm::Constant *C;
3985284bacSMike Stump   std::vector<llvm::Constant*> Elts;
4085284bacSMike Stump 
4185284bacSMike Stump   // reserved
42c2c38331SMike Stump   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
4385284bacSMike Stump   Elts.push_back(C);
4485284bacSMike Stump 
4585284bacSMike Stump   // Size
462ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
472ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
482ac40a9fSMike Stump   // API to size_t.
49cb2fbcb0SMike Stump   C = llvm::ConstantInt::get(UnsignedLongTy, Size);
5085284bacSMike Stump   Elts.push_back(C);
5185284bacSMike Stump 
5285284bacSMike Stump   if (BlockHasCopyDispose) {
5385284bacSMike Stump     // copy_func_helper_decl
54cb2fbcb0SMike Stump     // FIXME: implement
55c2c38331SMike Stump     C = llvm::ConstantInt::get(UnsignedLongTy, 0);
5685284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
5785284bacSMike Stump     Elts.push_back(C);
5885284bacSMike Stump 
5985284bacSMike Stump     // destroy_func_decl
60cb2fbcb0SMike Stump     // FIXME: implement
61c2c38331SMike Stump     C = llvm::ConstantInt::get(UnsignedLongTy, 0);
6285284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
6385284bacSMike Stump     Elts.push_back(C);
6485284bacSMike Stump   }
6585284bacSMike Stump 
6685284bacSMike Stump   C = llvm::ConstantStruct::get(Elts);
6785284bacSMike Stump 
6885284bacSMike Stump   C = new llvm::GlobalVariable(C->getType(), true,
6985284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
70499ae7ecSMike Stump                                C, "__block_descriptor_tmp", &CGM.getModule());
7185284bacSMike Stump   return C;
7285284bacSMike Stump }
7385284bacSMike Stump 
74971f9b66SMike Stump llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() {
75971f9b66SMike Stump   if (NSConcreteGlobalBlock)
76971f9b66SMike Stump     return NSConcreteGlobalBlock;
77971f9b66SMike Stump 
78971f9b66SMike Stump   const llvm::PointerType *PtrToInt8Ty
79971f9b66SMike Stump     = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
8052d9c49dSMike Stump   // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
81971f9b66SMike Stump   // same thing as CreateRuntimeFunction if there's already a variable with
82971f9b66SMike Stump   // the same name.
83971f9b66SMike Stump   NSConcreteGlobalBlock
84971f9b66SMike Stump     = new llvm::GlobalVariable(PtrToInt8Ty, false,
85971f9b66SMike Stump                                llvm::GlobalValue::ExternalLinkage,
86971f9b66SMike Stump                                0, "_NSConcreteGlobalBlock",
87971f9b66SMike Stump                                &getModule());
88971f9b66SMike Stump 
89971f9b66SMike Stump   return NSConcreteGlobalBlock;
90971f9b66SMike Stump }
91971f9b66SMike Stump 
927ab278dbSMike Stump llvm::Constant *CodeGenModule::getNSConcreteStackBlock() {
937ab278dbSMike Stump   if (NSConcreteStackBlock)
947ab278dbSMike Stump     return NSConcreteStackBlock;
957ab278dbSMike Stump 
967ab278dbSMike Stump   const llvm::PointerType *PtrToInt8Ty
977ab278dbSMike Stump     = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
9852d9c49dSMike Stump   // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
997ab278dbSMike Stump   // same thing as CreateRuntimeFunction if there's already a variable with
1007ab278dbSMike Stump   // the same name.
1017ab278dbSMike Stump   NSConcreteStackBlock
1027ab278dbSMike Stump     = new llvm::GlobalVariable(PtrToInt8Ty, false,
1037ab278dbSMike Stump                                llvm::GlobalValue::ExternalLinkage,
1047ab278dbSMike Stump                                0, "_NSConcreteStackBlock",
1057ab278dbSMike Stump                                &getModule());
1067ab278dbSMike Stump 
1077ab278dbSMike Stump   return NSConcreteStackBlock;
1087ab278dbSMike Stump }
1097ab278dbSMike Stump 
1105d2534adSMike Stump // FIXME: Push most into CGM, passing down a few bits, like current
1115d2534adSMike Stump // function name.
112b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
11385284bacSMike Stump   bool insideFunction = false;
11485284bacSMike Stump   bool BlockRefDeclList = false;
11585284bacSMike Stump   bool BlockByrefDeclList = false;
11685284bacSMike Stump 
11785284bacSMike Stump   std::vector<llvm::Constant*> Elts;
11885284bacSMike Stump   llvm::Constant *C;
119b750d928SMike Stump   llvm::Value *V;
12085284bacSMike Stump 
12185284bacSMike Stump   {
12285284bacSMike Stump     // C = BuildBlockStructInitlist();
12385284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
12485284bacSMike Stump 
12585284bacSMike Stump     if (BlockHasCopyDispose)
12685284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
12785284bacSMike Stump 
128499ae7ecSMike Stump     // __isa
1297ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
13085284bacSMike Stump     if (!insideFunction ||
13185284bacSMike Stump         (!BlockRefDeclList && !BlockByrefDeclList)) {
132971f9b66SMike Stump       C = CGM.getNSConcreteGlobalBlock();
13385284bacSMike Stump       flags |= BLOCK_IS_GLOBAL;
13485284bacSMike Stump     }
1357ab278dbSMike Stump     const llvm::PointerType *PtrToInt8Ty
1367ab278dbSMike Stump       = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
13785284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
13885284bacSMike Stump     Elts.push_back(C);
13985284bacSMike Stump 
14085284bacSMike Stump     // __flags
14185284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
14285284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
14385284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, flags);
14485284bacSMike Stump     Elts.push_back(C);
14585284bacSMike Stump 
14685284bacSMike Stump     // __reserved
14785284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, 0);
14885284bacSMike Stump     Elts.push_back(C);
14985284bacSMike Stump 
1505d2534adSMike Stump     // __invoke
15103868f4eSMike Stump     const char *Name = "";
1522d5a2878SMike Stump     if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurFuncDecl))
153eecd39f2SMike Stump       if (ND->getIdentifier())
1540e7d7b68SMike Stump         Name = ND->getNameAsCString();
1552d5a2878SMike Stump     BlockInfo Info(0, Name);
156b750d928SMike Stump     uint64_t subBlockSize, subBlockAlign;
157b750d928SMike Stump     llvm::SmallVector<ValueDecl *, 8> subBlockDeclRefDecls;
158cb2fbcb0SMike Stump     llvm::Function *Fn
159b750d928SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, subBlockSize,
160b750d928SMike Stump                                                    subBlockAlign, subBlockDeclRefDecls);
1612d5a2878SMike Stump     Elts.push_back(Fn);
16285284bacSMike Stump 
16385284bacSMike Stump     // __descriptor
164cb2fbcb0SMike Stump     Elts.push_back(BuildDescriptorBlockDecl(subBlockSize));
16585284bacSMike Stump 
166b750d928SMike Stump     // FIXME: Also check to make sure there are no byref variables
167b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
16885284bacSMike Stump       C = llvm::ConstantStruct::get(Elts);
16985284bacSMike Stump 
17085284bacSMike Stump       char Name[32];
1719319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
17285284bacSMike Stump       C = new llvm::GlobalVariable(C->getType(), true,
17385284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
17485284bacSMike Stump                                    C, Name, &CGM.getModule());
1755d2534adSMike Stump       QualType BPT = BE->getType();
1765d2534adSMike Stump       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
17785284bacSMike Stump       return C;
17885284bacSMike Stump     }
17985284bacSMike Stump 
180b750d928SMike Stump     std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
181b750d928SMike Stump     for (int i=0; i<5; ++i)
182b750d928SMike Stump       Types[i] = Elts[i]->getType();
18385284bacSMike Stump 
184b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
185b750d928SMike Stump       Types[i+5] = ConvertType(subBlockDeclRefDecls[i]->getType());
186b750d928SMike Stump 
187b750d928SMike Stump     llvm::Type *Ty = llvm::StructType::get(Types, true);
188b750d928SMike Stump 
189b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
190b750d928SMike Stump     A->setAlignment(subBlockAlign);
191b750d928SMike Stump     V = A;
192b750d928SMike Stump 
193b750d928SMike Stump     for (unsigned i=0; i<5; ++i)
194b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
195b750d928SMike Stump 
196b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
197b750d928SMike Stump       {
198b750d928SMike Stump         ValueDecl *VD = subBlockDeclRefDecls[i];
199b750d928SMike Stump 
200b750d928SMike Stump         if (VD->getIdentifier() == 0)
201b750d928SMike Stump             continue;
202b750d928SMike Stump         SourceLocation Loc = VD->getLocation();
203b750d928SMike Stump         DeclRefExpr D(VD, VD->getType(), Loc);
204b750d928SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
205b750d928SMike Stump         RValue r = EmitAnyExpr(&D, Addr, false);
206b750d928SMike Stump         if (r.isScalar())
207b750d928SMike Stump           Builder.CreateStore(r.getScalarVal(), Addr);
208b750d928SMike Stump         else if (r.isComplex())
209b750d928SMike Stump           // FIXME: implement
210b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
211b750d928SMike Stump         else if (r.isAggregate())
212b750d928SMike Stump           ; // Already created into the destination
213b750d928SMike Stump         else
214b750d928SMike Stump           assert (0 && "bad block variable");
215b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
216b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
217b750d928SMike Stump       }
218b750d928SMike Stump 
219b750d928SMike Stump     // FIXME: Add block_byref_decl_list.
220b750d928SMike Stump   }
221b750d928SMike Stump 
222b750d928SMike Stump   QualType BPT = BE->getType();
223b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
224b750d928SMike Stump }
22585284bacSMike Stump 
22685284bacSMike Stump 
227650c932dSMike Stump const llvm::Type *CodeGenModule::getBlockDescriptorType() {
228650c932dSMike Stump   if (BlockDescriptorType)
229650c932dSMike Stump     return BlockDescriptorType;
2302437cbfaSAnders Carlsson 
2312437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
232650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
2332437cbfaSAnders Carlsson 
2342437cbfaSAnders Carlsson   // struct __block_descriptor {
2352437cbfaSAnders Carlsson   //   unsigned long reserved;
2362437cbfaSAnders Carlsson   //   unsigned long block_size;
2372437cbfaSAnders Carlsson   // };
238650c932dSMike Stump   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
2392437cbfaSAnders Carlsson                                               UnsignedLongTy,
2402437cbfaSAnders Carlsson                                               NULL);
2412437cbfaSAnders Carlsson 
242650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
243650c932dSMike Stump                           BlockDescriptorType);
2442437cbfaSAnders Carlsson 
245650c932dSMike Stump   return BlockDescriptorType;
2462437cbfaSAnders Carlsson }
2472437cbfaSAnders Carlsson 
248005c9a62SMike Stump const llvm::Type *
249005c9a62SMike Stump CodeGenModule::getGenericBlockLiteralType() {
250005c9a62SMike Stump   if (GenericBlockLiteralType)
251005c9a62SMike Stump     return GenericBlockLiteralType;
2522437cbfaSAnders Carlsson 
2532437cbfaSAnders Carlsson   const llvm::Type *Int8PtrTy =
2542437cbfaSAnders Carlsson     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2552437cbfaSAnders Carlsson 
2562437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
257005c9a62SMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
2582437cbfaSAnders Carlsson 
25992bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
26092bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
26192bbd6d4SMike Stump 
2622437cbfaSAnders Carlsson   // struct __block_literal_generic {
2635d2534adSMike Stump   //   void *__isa;
2645d2534adSMike Stump   //   int __flags;
2655d2534adSMike Stump   //   int __reserved;
2665d2534adSMike Stump   //   void (*__invoke)(void *);
2675d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
2682437cbfaSAnders Carlsson   // };
269005c9a62SMike Stump   GenericBlockLiteralType = llvm::StructType::get(Int8PtrTy,
27092bbd6d4SMike Stump                                                   IntTy,
27192bbd6d4SMike Stump                                                   IntTy,
2722437cbfaSAnders Carlsson                                                   Int8PtrTy,
2732437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
2742437cbfaSAnders Carlsson                                                   NULL);
2752437cbfaSAnders Carlsson 
276005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
277005c9a62SMike Stump                           GenericBlockLiteralType);
2782437cbfaSAnders Carlsson 
279005c9a62SMike Stump   return GenericBlockLiteralType;
2802437cbfaSAnders Carlsson }
2812437cbfaSAnders Carlsson 
2825d2534adSMike Stump const llvm::Type *
2835d2534adSMike Stump CodeGenModule::getGenericExtendedBlockLiteralType() {
2845d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
2855d2534adSMike Stump     return GenericExtendedBlockLiteralType;
2865d2534adSMike Stump 
2875d2534adSMike Stump   const llvm::Type *Int8PtrTy =
2885d2534adSMike Stump     llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2895d2534adSMike Stump 
2905d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
2915d2534adSMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
2925d2534adSMike Stump 
2935d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
2945d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
2955d2534adSMike Stump 
2965d2534adSMike Stump   // struct __block_literal_generic {
2975d2534adSMike Stump   //   void *__isa;
2985d2534adSMike Stump   //   int __flags;
2995d2534adSMike Stump   //   int __reserved;
3005d2534adSMike Stump   //   void (*__invoke)(void *);
3015d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3025d2534adSMike Stump   //   void *__copy_func_helper_decl;
3035d2534adSMike Stump   //   void *__destroy_func_decl;
3045d2534adSMike Stump   // };
3055d2534adSMike Stump   GenericExtendedBlockLiteralType = llvm::StructType::get(Int8PtrTy,
3065d2534adSMike Stump                                                           IntTy,
3075d2534adSMike Stump                                                           IntTy,
3085d2534adSMike Stump                                                           Int8PtrTy,
3095d2534adSMike Stump                                                           BlockDescPtrTy,
3105d2534adSMike Stump                                                           Int8PtrTy,
3115d2534adSMike Stump                                                           Int8PtrTy,
3125d2534adSMike Stump                                                           NULL);
3135d2534adSMike Stump 
3145d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
3155d2534adSMike Stump                           GenericExtendedBlockLiteralType);
3165d2534adSMike Stump 
3175d2534adSMike Stump   return GenericExtendedBlockLiteralType;
3185d2534adSMike Stump }
3195d2534adSMike Stump 
3202437cbfaSAnders Carlsson /// getBlockFunctionType - Given a BlockPointerType, will return the
3212437cbfaSAnders Carlsson /// function type for the block, including the first block literal argument.
3222437cbfaSAnders Carlsson static QualType getBlockFunctionType(ASTContext &Ctx,
3236a60fa24SAnders Carlsson                                      const BlockPointerType *BPT) {
324*deaad8ccSDouglas Gregor   const FunctionProtoType *FTy = cast<FunctionProtoType>(BPT->getPointeeType());
3252437cbfaSAnders Carlsson 
3262437cbfaSAnders Carlsson   llvm::SmallVector<QualType, 8> Types;
3272437cbfaSAnders Carlsson   Types.push_back(Ctx.getPointerType(Ctx.VoidTy));
3282437cbfaSAnders Carlsson 
329*deaad8ccSDouglas Gregor   for (FunctionProtoType::arg_type_iterator i = FTy->arg_type_begin(),
3302437cbfaSAnders Carlsson        e = FTy->arg_type_end(); i != e; ++i)
3312437cbfaSAnders Carlsson     Types.push_back(*i);
3322437cbfaSAnders Carlsson 
3332437cbfaSAnders Carlsson   return Ctx.getFunctionType(FTy->getResultType(),
3342437cbfaSAnders Carlsson                              &Types[0], Types.size(),
3352437cbfaSAnders Carlsson                              FTy->isVariadic(), 0);
3362437cbfaSAnders Carlsson }
3372437cbfaSAnders Carlsson 
3386a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
3392437cbfaSAnders Carlsson   const BlockPointerType *BPT =
3402437cbfaSAnders Carlsson     E->getCallee()->getType()->getAsBlockPointerType();
3412437cbfaSAnders Carlsson 
3422437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
3432437cbfaSAnders Carlsson 
3442437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
3452437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
346005c9a62SMike Stump     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
3472437cbfaSAnders Carlsson 
3482437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
3492437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
3502437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
3512437cbfaSAnders Carlsson 
3522437cbfaSAnders Carlsson   // Get the function pointer from the literal.
3532437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
354624497c2SMike Stump   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
3552437cbfaSAnders Carlsson 
3562437cbfaSAnders Carlsson   // Cast the function pointer to the right type.
3572437cbfaSAnders Carlsson   const llvm::Type *BlockFTy =
3582437cbfaSAnders Carlsson     ConvertType(getBlockFunctionType(getContext(), BPT));
3592437cbfaSAnders Carlsson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
3602437cbfaSAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
3612437cbfaSAnders Carlsson 
3622437cbfaSAnders Carlsson   BlockLiteral =
3632437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
3642437cbfaSAnders Carlsson                           llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
3652437cbfaSAnders Carlsson                           "tmp");
3662437cbfaSAnders Carlsson 
3672437cbfaSAnders Carlsson   // Add the block literal.
3682437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
3692437cbfaSAnders Carlsson   CallArgList Args;
3702437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
3712437cbfaSAnders Carlsson 
3722437cbfaSAnders Carlsson   // And the rest of the arguments.
3732437cbfaSAnders Carlsson   for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
3742437cbfaSAnders Carlsson        i != e; ++i)
3752437cbfaSAnders Carlsson     Args.push_back(std::make_pair(EmitAnyExprToTemp(*i),
3762437cbfaSAnders Carlsson                                   i->getType()));
3772437cbfaSAnders Carlsson 
3782437cbfaSAnders Carlsson   // And call the block.
3792437cbfaSAnders Carlsson   return EmitCall(CGM.getTypes().getFunctionInfo(E->getType(), Args),
3802437cbfaSAnders Carlsson                   Func, Args);
3812437cbfaSAnders Carlsson }
3826a60fa24SAnders Carlsson 
3832d5a2878SMike Stump llvm::Constant *
3840e7d7b68SMike Stump CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
3856a60fa24SAnders Carlsson   // Generate the block descriptor.
3866a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
38792bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
38892bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
3896a60fa24SAnders Carlsson 
3906a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
3916a60fa24SAnders Carlsson 
3926a60fa24SAnders Carlsson   // Reserved
3936a60fa24SAnders Carlsson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
3946a60fa24SAnders Carlsson 
3956a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
3966a60fa24SAnders Carlsson   // block literal struct.
3976a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
398005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
3996a60fa24SAnders Carlsson   DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
4006a60fa24SAnders Carlsson 
4016a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
4026a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&DescriptorFields[0], 2);
4036a60fa24SAnders Carlsson 
4046a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
4056a60fa24SAnders Carlsson     new llvm::GlobalVariable(DescriptorStruct->getType(), true,
4066a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
4076a60fa24SAnders Carlsson                              DescriptorStruct, "__block_descriptor_global",
4086a60fa24SAnders Carlsson                              &getModule());
4096a60fa24SAnders Carlsson 
4106a60fa24SAnders Carlsson   // Generate the constants for the block literal.
4116a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
4126a60fa24SAnders Carlsson 
4132d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
414b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
415b750d928SMike Stump   llvm::SmallVector<ValueDecl *, 8> subBlockDeclRefDecls;
416cb2fbcb0SMike Stump   llvm::Function *Fn
417b750d928SMike Stump     = CodeGenFunction(*this).GenerateBlockFunction(BE, Info, subBlockSize,
418b750d928SMike Stump                                                    subBlockAlign,
419b750d928SMike Stump                                                    subBlockDeclRefDecls);
420cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
421cb2fbcb0SMike Stump          && "no imports allowed for global block");
4226a60fa24SAnders Carlsson 
4236a60fa24SAnders Carlsson   // isa
424971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
4256a60fa24SAnders Carlsson 
4266a60fa24SAnders Carlsson   // Flags
42785284bacSMike Stump   LiteralFields[1] = llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL);
4286a60fa24SAnders Carlsson 
4296a60fa24SAnders Carlsson   // Reserved
43092bbd6d4SMike Stump   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
4316a60fa24SAnders Carlsson 
4326a60fa24SAnders Carlsson   // Function
4336a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
4346a60fa24SAnders Carlsson 
4356a60fa24SAnders Carlsson   // Descriptor
4366a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
4376a60fa24SAnders Carlsson 
4386a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
4396a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&LiteralFields[0], 5);
4406a60fa24SAnders Carlsson 
4416a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
4426a60fa24SAnders Carlsson     new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
4436a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
4446a60fa24SAnders Carlsson                              BlockLiteralStruct, "__block_literal_global",
4456a60fa24SAnders Carlsson                              &getModule());
4466a60fa24SAnders Carlsson 
4476a60fa24SAnders Carlsson   return BlockLiteral;
4486a60fa24SAnders Carlsson }
4496a60fa24SAnders Carlsson 
450cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
451cb2fbcb0SMike Stump   return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
452cb2fbcb0SMike Stump }
453cb2fbcb0SMike Stump 
4546a60fa24SAnders Carlsson llvm::Function *CodeGenFunction::GenerateBlockFunction(const BlockExpr *Expr,
455cb2fbcb0SMike Stump                                                        const BlockInfo& Info,
456b750d928SMike Stump                                                        uint64_t &Size,
457b750d928SMike Stump                                                        uint64_t &Align,
458b750d928SMike Stump                     llvm::SmallVector<ValueDecl *, 8> &subBlockDeclRefDecls) {
459*deaad8ccSDouglas Gregor   const FunctionProtoType *FTy =
460*deaad8ccSDouglas Gregor     cast<FunctionProtoType>(Expr->getFunctionType());
4616a60fa24SAnders Carlsson 
4626a60fa24SAnders Carlsson   FunctionArgList Args;
4636a60fa24SAnders Carlsson 
4646a60fa24SAnders Carlsson   const BlockDecl *BD = Expr->getBlockDecl();
4656a60fa24SAnders Carlsson 
4666a60fa24SAnders Carlsson   // FIXME: This leaks
4676a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
4686a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
4696a60fa24SAnders Carlsson                               SourceLocation(), 0,
4706a60fa24SAnders Carlsson                               getContext().getPointerType(getContext().VoidTy));
4716a60fa24SAnders Carlsson 
4726a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
473cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
4746a60fa24SAnders Carlsson 
4756a60fa24SAnders Carlsson   for (BlockDecl::param_iterator i = BD->param_begin(),
4766a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
477eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
4786a60fa24SAnders Carlsson 
4796a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
4806a60fa24SAnders Carlsson     CGM.getTypes().getFunctionInfo(FTy->getResultType(), Args);
4816a60fa24SAnders Carlsson 
4822d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
4836a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
4846a60fa24SAnders Carlsson   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, FTy->isVariadic());
4856a60fa24SAnders Carlsson 
4866a60fa24SAnders Carlsson   llvm::Function *Fn =
4876a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
4886a60fa24SAnders Carlsson                            Name,
4896a60fa24SAnders Carlsson                            &CGM.getModule());
4906a60fa24SAnders Carlsson 
4916a60fa24SAnders Carlsson   StartFunction(BD, FTy->getResultType(), Fn, Args,
4926a60fa24SAnders Carlsson                 Expr->getBody()->getLocEnd());
4936a60fa24SAnders Carlsson   EmitStmt(Expr->getBody());
4946a60fa24SAnders Carlsson   FinishFunction(cast<CompoundStmt>(Expr->getBody())->getRBracLoc());
4956a60fa24SAnders Carlsson 
496b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
497b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
498b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
499b750d928SMike Stump 
500cb2fbcb0SMike Stump   Size = BlockOffset;
501b750d928SMike Stump   Align = BlockAlign;
502b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
503cb2fbcb0SMike Stump 
5046a60fa24SAnders Carlsson   return Fn;
5056a60fa24SAnders Carlsson }
506