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 
142e722b91SMike Stump #include "CGDebugInfo.h"
152437cbfaSAnders Carlsson #include "CodeGenFunction.h"
162437cbfaSAnders Carlsson #include "CodeGenModule.h"
17692c6e37SMike Stump #include "clang/AST/DeclObjC.h"
182437cbfaSAnders Carlsson #include "llvm/Module.h"
196a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
202437cbfaSAnders Carlsson #include <algorithm>
21db714924STorok Edwin #include <cstdio>
22db714924STorok Edwin 
232437cbfaSAnders Carlsson using namespace clang;
242437cbfaSAnders Carlsson using namespace CodeGen;
252437cbfaSAnders Carlsson 
26d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
27d2142cffSMike Stump BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size,
28d2142cffSMike Stump                          const llvm::StructType* Ty,
29aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
30c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
31c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
3285284bacSMike Stump   llvm::Constant *C;
3385284bacSMike Stump   std::vector<llvm::Constant*> Elts;
3485284bacSMike Stump 
3585284bacSMike Stump   // reserved
36b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
3785284bacSMike Stump   Elts.push_back(C);
3885284bacSMike Stump 
3985284bacSMike Stump   // Size
402ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
412ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
422ac40a9fSMike Stump   // API to size_t.
43b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, Size);
4485284bacSMike Stump   Elts.push_back(C);
4585284bacSMike Stump 
4685284bacSMike Stump   if (BlockHasCopyDispose) {
4785284bacSMike Stump     // copy_func_helper_decl
4867645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
4985284bacSMike Stump 
5085284bacSMike Stump     // destroy_func_decl
5167645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
5285284bacSMike Stump   }
5385284bacSMike Stump 
5441eaf0acSNick Lewycky   C = llvm::ConstantStruct::get(VMContext, Elts, false);
5585284bacSMike Stump 
56c10c8d3eSOwen Anderson   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
5785284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
58c10c8d3eSOwen Anderson                                C, "__block_descriptor_tmp");
5985284bacSMike Stump   return C;
6085284bacSMike Stump }
6185284bacSMike Stump 
6295435674SMike Stump llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
6346813bbfSChris Lattner   if (NSConcreteGlobalBlock == 0)
6446813bbfSChris Lattner     NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
6546813bbfSChris Lattner                                                       "_NSConcreteGlobalBlock");
66971f9b66SMike Stump   return NSConcreteGlobalBlock;
67971f9b66SMike Stump }
68971f9b66SMike Stump 
6995435674SMike Stump llvm::Constant *BlockModule::getNSConcreteStackBlock() {
7046813bbfSChris Lattner   if (NSConcreteStackBlock == 0)
7146813bbfSChris Lattner     NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
7246813bbfSChris Lattner                                                      "_NSConcreteStackBlock");
737ab278dbSMike Stump   return NSConcreteStackBlock;
747ab278dbSMike Stump }
757ab278dbSMike Stump 
76ed5e69feSAnders Carlsson static void CollectBlockDeclRefInfo(const Stmt *S,
77ed5e69feSAnders Carlsson                                     CodeGenFunction::BlockInfo &Info) {
78ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
79ed5e69feSAnders Carlsson        I != E; ++I)
80dd942713SDaniel Dunbar     if (*I)
81ed5e69feSAnders Carlsson       CollectBlockDeclRefInfo(*I, Info);
82ed5e69feSAnders Carlsson 
83ed5e69feSAnders Carlsson   if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
84ed5e69feSAnders Carlsson     // FIXME: Handle enums.
85ed5e69feSAnders Carlsson     if (isa<FunctionDecl>(DE->getDecl()))
86ed5e69feSAnders Carlsson       return;
87ed5e69feSAnders Carlsson 
88ed5e69feSAnders Carlsson     if (DE->isByRef())
89ed5e69feSAnders Carlsson       Info.ByRefDeclRefs.push_back(DE);
90ed5e69feSAnders Carlsson     else
91ed5e69feSAnders Carlsson       Info.ByCopyDeclRefs.push_back(DE);
92ed5e69feSAnders Carlsson   }
93ed5e69feSAnders Carlsson }
94ed5e69feSAnders Carlsson 
952d33d630SMike Stump /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
962d33d630SMike Stump /// declared as a global variable instead of on the stack.
9746813bbfSChris Lattner static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
98ed5e69feSAnders Carlsson   return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
99ed5e69feSAnders Carlsson }
100ed5e69feSAnders Carlsson 
1012d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
1022d33d630SMike Stump // name.
103b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
104ed5e69feSAnders Carlsson 
105ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
106ed5e69feSAnders Carlsson   CodeGenFunction::BlockInfo Info(0, Name.c_str());
107ed5e69feSAnders Carlsson   CollectBlockDeclRefInfo(BE->getBody(), Info);
108ed5e69feSAnders Carlsson 
109ed5e69feSAnders Carlsson   // Check if the block can be global.
1102d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
1112d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
1122d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
11397d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
114ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
11585284bacSMike Stump 
1164446dcf0SMike Stump   std::vector<llvm::Constant*> Elts(5);
11785284bacSMike Stump   llvm::Constant *C;
118b750d928SMike Stump   llvm::Value *V;
11985284bacSMike Stump 
12085284bacSMike Stump   {
12185284bacSMike Stump     // C = BuildBlockStructInitlist();
12285284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
12385284bacSMike Stump 
1244446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1254446dcf0SMike Stump     // block literal.
1264446dcf0SMike Stump     // __invoke
1274446dcf0SMike Stump     uint64_t subBlockSize, subBlockAlign;
1284446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
129d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1304446dcf0SMike Stump     llvm::Function *Fn
131d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
132d2a3e617SMike Stump                                                    LocalDeclMap,
1335469f29aSMike Stump                                                    subBlockSize,
1344446dcf0SMike Stump                                                    subBlockAlign,
1354446dcf0SMike Stump                                                    subBlockDeclRefDecls,
136d2142cffSMike Stump                                                    subBlockHasCopyDispose);
137d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1384446dcf0SMike Stump     Elts[3] = Fn;
1394446dcf0SMike Stump 
14018bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
14118bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
142d2142cffSMike Stump     if (subBlockHasCopyDispose)
14385284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
14485284bacSMike Stump 
145499ae7ecSMike Stump     // __isa
1467ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
147ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1484446dcf0SMike Stump     Elts[0] = C;
14985284bacSMike Stump 
15085284bacSMike Stump     // __flags
15185284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
15285284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
153b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
1544446dcf0SMike Stump     Elts[1] = C;
15585284bacSMike Stump 
15685284bacSMike Stump     // __reserved
157b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
1584446dcf0SMike Stump     Elts[2] = C;
15985284bacSMike Stump 
160b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
161d6ef62f0SMike Stump       // __descriptor
162d2142cffSMike Stump       Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize, 0, 0);
163d6ef62f0SMike Stump 
1643a139f37SMike Stump       // Optimize to being a global block.
1653a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
166b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
1673a139f37SMike Stump 
16841eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
16985284bacSMike Stump 
17085284bacSMike Stump       char Name[32];
1719319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
172c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
17385284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
174c10c8d3eSOwen Anderson                                    C, Name);
1755d2534adSMike Stump       QualType BPT = BE->getType();
176ade90fd1SOwen Anderson       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());
181aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
182b750d928SMike Stump       Types[i] = Elts[i]->getType();
183aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
18485284bacSMike Stump 
1851db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
1861db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
1871db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
1881db7d04bSMike Stump       QualType Ty = E->getType();
18997d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
19071d1d92dSAnders Carlsson         Types[i+5] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
19197d01d50SMike Stump       } else
1921db7d04bSMike Stump         Types[i+5] = ConvertType(Ty);
1931db7d04bSMike Stump     }
194b750d928SMike Stump 
195758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
196b750d928SMike Stump 
197b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
198b750d928SMike Stump     A->setAlignment(subBlockAlign);
199b750d928SMike Stump     V = A;
200b750d928SMike Stump 
201aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
202aeb0ffd5SMike Stump     int helpersize = 0;
203aeb0ffd5SMike Stump 
204aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
205b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
206b750d928SMike Stump 
207b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
208b750d928SMike Stump       {
2091db7d04bSMike Stump         // FIXME: Push const down.
2101db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2111db7d04bSMike Stump         DeclRefExpr *DR;
2121db7d04bSMike Stump         ValueDecl *VD;
213b750d928SMike Stump 
2141db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2151db7d04bSMike Stump         // Skip padding.
2161db7d04bSMike Stump         if (DR) continue;
2171db7d04bSMike Stump 
2181db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2191db7d04bSMike Stump         VD = BDRE->getDecl();
2201db7d04bSMike Stump 
22197d01d50SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
222aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
2232114d7c2SMike Stump         NoteForHelper[helpersize].RequiresCopying
2242114d7c2SMike Stump           = BlockRequiresCopying(VD->getType());
225aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
2262114d7c2SMike Stump           = (VD->getType()->isBlockPointerType()
2272114d7c2SMike Stump              ? BLOCK_FIELD_IS_BLOCK
2282114d7c2SMike Stump              : BLOCK_FIELD_IS_OBJECT);
229aeb0ffd5SMike Stump 
2301db7d04bSMike Stump         if (LocalDeclMap[VD]) {
23197d01d50SMike Stump           if (BDRE->isByRef()) {
232aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
23390d8daf5SMike Stump               // FIXME: Someone double check this.
23490d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
23597d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
23697d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
23797d01d50SMike Stump             Loc = Builder.CreateLoad(Loc, false);
23897d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
239aeb0ffd5SMike Stump             ++helpersize;
24097d01d50SMike Stump             continue;
24197d01d50SMike Stump           } else
2421db7d04bSMike Stump             E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
2431db7d04bSMike Stump                                                 VD->getType(), SourceLocation(),
2441db7d04bSMike Stump                                                 false, false);
2451db7d04bSMike Stump         }
24697d01d50SMike Stump         if (BDRE->isByRef()) {
247efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
248efd7caa8SMike Stump             // FIXME: Someone double check this.
249efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
2501db7d04bSMike Stump           E = new (getContext())
2511db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
2521db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
2531db7d04bSMike Stump                           SourceLocation());
25497d01d50SMike Stump         }
255aeb0ffd5SMike Stump         ++helpersize;
2561db7d04bSMike Stump 
2571db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
25897d01d50SMike Stump         if (r.isScalar()) {
25997d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
26097d01d50SMike Stump           const llvm::Type *Ty = Types[i+5];
26197d01d50SMike Stump           if  (BDRE->isByRef()) {
2622d33d630SMike Stump             // E is now the address of the value field, instead, we want the
2632d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
2642d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
2652d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
2662d33d630SMike Stump             // until then.
2672d33d630SMike Stump             uint64_t offset = BlockDecls[BDRE->getDecl()];
2682d33d630SMike Stump 
2692d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
2702d33d630SMike Stump 
2712d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
27241a75027SOwen Anderson                                     llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
2732d33d630SMike Stump                                                            offset),
2742d33d630SMike Stump                                     "block.literal");
2759793f0e4SOwen Anderson             Ty = llvm::PointerType::get(Ty, 0);
27697d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
2772d33d630SMike Stump             Loc = Builder.CreateLoad(Loc, false);
2782d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
27997d01d50SMike Stump           }
28097d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
28197d01d50SMike Stump         } else if (r.isComplex())
282b750d928SMike Stump           // FIXME: implement
283b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
284b750d928SMike Stump         else if (r.isAggregate())
285b750d928SMike Stump           ; // Already created into the destination
286b750d928SMike Stump         else
287b750d928SMike Stump           assert (0 && "bad block variable");
288b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
289b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
290b750d928SMike Stump       }
291aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
292d6ef62f0SMike Stump 
293d6ef62f0SMike Stump     // __descriptor
294d2142cffSMike Stump     llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
295d2142cffSMike Stump                                                        subBlockSize, Ty,
296aeb0ffd5SMike Stump                                                        &NoteForHelper);
297aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
298aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
299b750d928SMike Stump   }
300b750d928SMike Stump 
301b750d928SMike Stump   QualType BPT = BE->getType();
302b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
303b750d928SMike Stump }
30485284bacSMike Stump 
30585284bacSMike Stump 
30695435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
307650c932dSMike Stump   if (BlockDescriptorType)
308650c932dSMike Stump     return BlockDescriptorType;
3092437cbfaSAnders Carlsson 
3102437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
311650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3122437cbfaSAnders Carlsson 
3132437cbfaSAnders Carlsson   // struct __block_descriptor {
3142437cbfaSAnders Carlsson   //   unsigned long reserved;
3152437cbfaSAnders Carlsson   //   unsigned long block_size;
3162437cbfaSAnders Carlsson   // };
317758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
318758428f4SOwen Anderson                                               UnsignedLongTy,
3192437cbfaSAnders Carlsson                                               UnsignedLongTy,
3202437cbfaSAnders Carlsson                                               NULL);
3212437cbfaSAnders Carlsson 
322650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
323650c932dSMike Stump                           BlockDescriptorType);
3242437cbfaSAnders Carlsson 
325650c932dSMike Stump   return BlockDescriptorType;
3262437cbfaSAnders Carlsson }
3272437cbfaSAnders Carlsson 
32895435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
329005c9a62SMike Stump   if (GenericBlockLiteralType)
330005c9a62SMike Stump     return GenericBlockLiteralType;
3312437cbfaSAnders Carlsson 
3322437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
3339793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3342437cbfaSAnders Carlsson 
33592bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
33692bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
33792bbd6d4SMike Stump 
3382437cbfaSAnders Carlsson   // struct __block_literal_generic {
3395d2534adSMike Stump   //   void *__isa;
3405d2534adSMike Stump   //   int __flags;
3415d2534adSMike Stump   //   int __reserved;
3425d2534adSMike Stump   //   void (*__invoke)(void *);
3435d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3442437cbfaSAnders Carlsson   // };
345758428f4SOwen Anderson   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
346758428f4SOwen Anderson                                                   PtrToInt8Ty,
34792bbd6d4SMike Stump                                                   IntTy,
34892bbd6d4SMike Stump                                                   IntTy,
349626aecc4SMike Stump                                                   PtrToInt8Ty,
3502437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
3512437cbfaSAnders Carlsson                                                   NULL);
3522437cbfaSAnders Carlsson 
353005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
354005c9a62SMike Stump                           GenericBlockLiteralType);
3552437cbfaSAnders Carlsson 
356005c9a62SMike Stump   return GenericBlockLiteralType;
3572437cbfaSAnders Carlsson }
3582437cbfaSAnders Carlsson 
35995435674SMike Stump const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
3605d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
3615d2534adSMike Stump     return GenericExtendedBlockLiteralType;
3625d2534adSMike Stump 
3635d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
3649793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3655d2534adSMike Stump 
3665d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
3675d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
3685d2534adSMike Stump 
3695d2534adSMike Stump   // struct __block_literal_generic {
3705d2534adSMike Stump   //   void *__isa;
3715d2534adSMike Stump   //   int __flags;
3725d2534adSMike Stump   //   int __reserved;
3735d2534adSMike Stump   //   void (*__invoke)(void *);
3745d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3755d2534adSMike Stump   //   void *__copy_func_helper_decl;
3765d2534adSMike Stump   //   void *__destroy_func_decl;
3775d2534adSMike Stump   // };
378758428f4SOwen Anderson   GenericExtendedBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
379758428f4SOwen Anderson                                                           PtrToInt8Ty,
3805d2534adSMike Stump                                                           IntTy,
3815d2534adSMike Stump                                                           IntTy,
382626aecc4SMike Stump                                                           PtrToInt8Ty,
3835d2534adSMike Stump                                                           BlockDescPtrTy,
384626aecc4SMike Stump                                                           PtrToInt8Ty,
385626aecc4SMike Stump                                                           PtrToInt8Ty,
3865d2534adSMike Stump                                                           NULL);
3875d2534adSMike Stump 
3885d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
3895d2534adSMike Stump                           GenericExtendedBlockLiteralType);
3905d2534adSMike Stump 
3915d2534adSMike Stump   return GenericExtendedBlockLiteralType;
3925d2534adSMike Stump }
3935d2534adSMike Stump 
3942114d7c2SMike Stump bool BlockFunction::BlockRequiresCopying(QualType Ty) {
3952114d7c2SMike Stump   return CGM.BlockRequiresCopying(Ty);
3962114d7c2SMike Stump }
3972114d7c2SMike Stump 
3986a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
3992437cbfaSAnders Carlsson   const BlockPointerType *BPT =
400c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
4012437cbfaSAnders Carlsson 
4022437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4032437cbfaSAnders Carlsson 
4042437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4052437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
4069793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4072437cbfaSAnders Carlsson 
4082437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4092437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4102437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4112437cbfaSAnders Carlsson 
4122437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4132437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4142437cbfaSAnders Carlsson 
4152437cbfaSAnders Carlsson   BlockLiteral =
4162437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
417abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
4182437cbfaSAnders Carlsson                           "tmp");
4192437cbfaSAnders Carlsson 
4202437cbfaSAnders Carlsson   // Add the block literal.
4212437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4222437cbfaSAnders Carlsson   CallArgList Args;
4232437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4242437cbfaSAnders Carlsson 
425479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
426479e6fc7SAnders Carlsson 
4272437cbfaSAnders Carlsson   // And the rest of the arguments.
4289dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
429479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4302437cbfaSAnders Carlsson 
4315f50c651SAnders Carlsson   // Load the function.
4325f50c651SAnders Carlsson   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
4335f50c651SAnders Carlsson 
4349dd450bbSJohn McCall   QualType ResultType = FnType->getAs<FunctionType>()->getResultType();
435a60cbcdfSAnders Carlsson 
436a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
437a60cbcdfSAnders Carlsson     CGM.getTypes().getFunctionInfo(ResultType, Args);
4385f50c651SAnders Carlsson 
4395f50c651SAnders Carlsson   // Cast the function pointer to the right type.
4405f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
441a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
4425f50c651SAnders Carlsson 
4439793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
4445f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4455f50c651SAnders Carlsson 
4462437cbfaSAnders Carlsson   // And call the block.
447350da607SAnders Carlsson   return EmitCall(FnInfo, Func, Args);
4482437cbfaSAnders Carlsson }
4496a60fa24SAnders Carlsson 
45097d01d50SMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
4510168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
45297d01d50SMike Stump 
4530168f4b2SAnders Carlsson   uint64_t &offset = BlockDecls[VD];
4540168f4b2SAnders Carlsson 
45597d01d50SMike Stump 
45697d01d50SMike Stump   // See if we have already allocated an offset for this variable.
45797d01d50SMike Stump   if (offset == 0) {
4584446dcf0SMike Stump     // Don't run the expensive check, unless we have to.
4594446dcf0SMike Stump     if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
4604446dcf0SMike Stump       BlockHasCopyDispose = true;
46197d01d50SMike Stump     // if not, allocate one now.
46297d01d50SMike Stump     offset = getBlockOffset(E);
46397d01d50SMike Stump   }
46497d01d50SMike Stump 
46597d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
46697d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
46741a75027SOwen Anderson                                   llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
46897d01d50SMike Stump                                                          offset),
4692d33d630SMike Stump                                      "block.literal");
47097d01d50SMike Stump   if (E->isByRef()) {
47197d01d50SMike Stump     const llvm::Type *PtrStructTy
4720168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
473efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
474efd7caa8SMike Stump     BlockHasCopyDispose = true;
4750168f4b2SAnders Carlsson 
4760168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
4779793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
47897d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
47997d01d50SMike Stump     V = Builder.CreateLoad(V, false);
48097d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
48197d01d50SMike Stump     V = Builder.CreateLoad(V, false);
48297d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
4830168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
4840168f4b2SAnders Carlsson                                 VD->getNameAsString());
48597d01d50SMike Stump   } else {
4860168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
4870168f4b2SAnders Carlsson 
4889793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
48997d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
49097d01d50SMike Stump   }
49197d01d50SMike Stump   return V;
49297d01d50SMike Stump }
49397d01d50SMike Stump 
494692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
495692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
496692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
497692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
498692c6e37SMike Stump   if (DMEntry)
499692c6e37SMike Stump     return;
500692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
501692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
502692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
503692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
504692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
505692c6e37SMike Stump }
506692c6e37SMike Stump 
5072d5a2878SMike Stump llvm::Constant *
5086c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
5096a60fa24SAnders Carlsson   // Generate the block descriptor.
5106a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
51192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
51292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5136a60fa24SAnders Carlsson 
5146a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
5156a60fa24SAnders Carlsson 
5166a60fa24SAnders Carlsson   // Reserved
5170b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
5186a60fa24SAnders Carlsson 
5196a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5206a60fa24SAnders Carlsson   // block literal struct.
5216a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
522005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
523170229f6SOwen Anderson   DescriptorFields[1] =
524b7a2fe6fSOwen Anderson                       llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
5256a60fa24SAnders Carlsson 
5266a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
52741eaf0acSNick Lewycky     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 2, false);
5286a60fa24SAnders Carlsson 
5296a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
530c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
5316a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
532c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
5336a60fa24SAnders Carlsson 
5346a60fa24SAnders Carlsson   // Generate the constants for the block literal.
5356a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
5366a60fa24SAnders Carlsson 
5372d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
538b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
5391db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
540a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
5415469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
542cb2fbcb0SMike Stump   llvm::Function *Fn
543692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
5445469f29aSMike Stump                                                  subBlockSize,
545b750d928SMike Stump                                                  subBlockAlign,
5464446dcf0SMike Stump                                                  subBlockDeclRefDecls,
5474446dcf0SMike Stump                                                  subBlockHasCopyDispose);
548cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
549cb2fbcb0SMike Stump          && "no imports allowed for global block");
5506a60fa24SAnders Carlsson 
5516a60fa24SAnders Carlsson   // isa
552971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
5536a60fa24SAnders Carlsson 
5546a60fa24SAnders Carlsson   // Flags
5555878c797SAnders Carlsson   LiteralFields[1] =
556b7a2fe6fSOwen Anderson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
5576a60fa24SAnders Carlsson 
5586a60fa24SAnders Carlsson   // Reserved
5590b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
5606a60fa24SAnders Carlsson 
5616a60fa24SAnders Carlsson   // Function
5626a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
5636a60fa24SAnders Carlsson 
5646a60fa24SAnders Carlsson   // Descriptor
5656a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
5666a60fa24SAnders Carlsson 
5676a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
56841eaf0acSNick Lewycky     llvm::ConstantStruct::get(VMContext, &LiteralFields[0], 5, false);
5696a60fa24SAnders Carlsson 
5706a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
571c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
5726a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
573c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
5746a60fa24SAnders Carlsson 
5756a60fa24SAnders Carlsson   return BlockLiteral;
5766a60fa24SAnders Carlsson }
5776a60fa24SAnders Carlsson 
578cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
579*38382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
580*38382028SMike Stump                                       "self");
581*38382028SMike Stump   // For now, we codegen based upon byte offsets.
582*38382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
583cb2fbcb0SMike Stump }
584cb2fbcb0SMike Stump 
5854446dcf0SMike Stump llvm::Function *
5864446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
587cb2fbcb0SMike Stump                                        const BlockInfo& Info,
588692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
5895469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
590b750d928SMike Stump                                        uint64_t &Size,
591b750d928SMike Stump                                        uint64_t &Align,
5924446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
5934446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
5949074ed8cSDevang Patel 
5959074ed8cSDevang Patel   // Check if we should generate debug info for this block.
5969074ed8cSDevang Patel   if (CGM.getDebugInfo())
5979074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
5989074ed8cSDevang Patel 
5995469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
6005469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
6015469f29aSMike Stump   // in a block.
6025469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
6035469f29aSMike Stump        i != ldm.end();
6045469f29aSMike Stump        ++i) {
6055469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
6065469f29aSMike Stump 
6070ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
6085469f29aSMike Stump       LocalDeclMap[VD] = i->second;
6095469f29aSMike Stump   }
6105469f29aSMike Stump 
61109a9b6e3SEli Friedman   // FIXME: We need to rearrange the code for copy/dispose so we have this
61209a9b6e3SEli Friedman   // sooner, so we can calculate offsets correctly.
61309a9b6e3SEli Friedman   if (!BlockHasCopyDispose)
61409a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
61509a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
61609a9b6e3SEli Friedman   else
61709a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
61809a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
61909a9b6e3SEli Friedman   BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
62009a9b6e3SEli Friedman 
621aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
622aae4349dSFariborz Jahanian   QualType ResultType;
623aae4349dSFariborz Jahanian   bool IsVariadic;
624a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
625a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
626aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
627aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
628658fe02dSMike Stump   } else {
629aae4349dSFariborz Jahanian     // K&R style block.
630aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
631aae4349dSFariborz Jahanian     IsVariadic = false;
632aae4349dSFariborz Jahanian   }
6336a60fa24SAnders Carlsson 
6346a60fa24SAnders Carlsson   FunctionArgList Args;
6356a60fa24SAnders Carlsson 
6363385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
6376a60fa24SAnders Carlsson 
638d015328fSMike Stump   IdentifierInfo *II
639d015328fSMike Stump     = &CGM.getContext().Idents.get(".block_descriptor");
640d015328fSMike Stump 
641d015328fSMike Stump   QualType ParmTy = getContext().getBlockParmType();
6426a60fa24SAnders Carlsson   // FIXME: This leaks
6436a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
6446a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
645d015328fSMike Stump                               SourceLocation(), II,
646d015328fSMike Stump                               ParmTy);
6476a60fa24SAnders Carlsson 
6486a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
649cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
6506a60fa24SAnders Carlsson 
651c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
6526a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
653eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
6546a60fa24SAnders Carlsson 
6556a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
656aae4349dSFariborz Jahanian     CGM.getTypes().getFunctionInfo(ResultType, Args);
6576a60fa24SAnders Carlsson 
6582d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
6596a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
660aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
6616a60fa24SAnders Carlsson 
6626a60fa24SAnders Carlsson   llvm::Function *Fn =
6636a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
6646a60fa24SAnders Carlsson                            Name,
6656a60fa24SAnders Carlsson                            &CGM.getModule());
6666a60fa24SAnders Carlsson 
667c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
668c3e7cff6SDaniel Dunbar 
669324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
6703385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
6712e722b91SMike Stump 
672324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
67328ec0cf8SChris Lattner   CurCodeDecl = BD;
674017460abSMike Stump 
675017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
676017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
677017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
678017460abSMike Stump   --entry_ptr;
679017460abSMike Stump 
6803385fe12SChris Lattner   EmitStmt(BExpr->getBody());
681017460abSMike Stump 
6827d69911aSMike Stump   // Remember where we were...
6837d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
684017460abSMike Stump 
6857d69911aSMike Stump   // Go back to the entry.
686017460abSMike Stump   ++entry_ptr;
687017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
688017460abSMike Stump 
6892e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
6902e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
6912e722b91SMike Stump     for (unsigned i=0; i < BlockDeclRefDecls.size(); ++i) {
6922e722b91SMike Stump       const Expr *E = BlockDeclRefDecls[i];
6932e722b91SMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
6942e722b91SMike Stump       if (BDRE) {
6952e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
6962e722b91SMike Stump         DI->setLocation(D->getLocation());
6972e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
6982e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
6992e722b91SMike Stump                                               Builder, this);
7002e722b91SMike Stump       }
7012e722b91SMike Stump     }
7022e722b91SMike Stump   }
7037d69911aSMike Stump   // And resume where we left off.
7047d69911aSMike Stump   if (resume == 0)
7057d69911aSMike Stump     Builder.ClearInsertionPoint();
7067d69911aSMike Stump   else
7077d69911aSMike Stump     Builder.SetInsertPoint(resume);
7082e722b91SMike Stump 
7093385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
7106a60fa24SAnders Carlsson 
711d015328fSMike Stump   // And now finish off the type for the parameter, since now we know
712d015328fSMike Stump   // BlockDeclRefDecls is complete.
713d015328fSMike Stump   getContext().completeBlockParmType(ParmTy, BlockDeclRefDecls);
714d015328fSMike Stump 
715d015328fSMike Stump #define REV2
716d015328fSMike Stump #ifdef REV2
717d015328fSMike Stump   TagDecl *TD = ParmTy->getPointeeType()->getAs<RecordType>()->getDecl();
718d015328fSMike Stump   CGM.UpdateCompletedType(TD);
719d015328fSMike Stump #else
720d015328fSMike Stump   TagDecl *TD = ParmTy->getPointeeType()->getAs<RecordType>()->getDecl();
721d015328fSMike Stump   TagDecl::redecl_iterator rdi = TD->redecls_begin();
722d015328fSMike Stump   ++rdi;
723d015328fSMike Stump   TD = *rdi;
724d015328fSMike Stump   CGM.UpdateCompletedType(TD);
725d015328fSMike Stump #endif
726d015328fSMike Stump 
727b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
728b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
729b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
730b750d928SMike Stump 
731cb2fbcb0SMike Stump   Size = BlockOffset;
732b750d928SMike Stump   Align = BlockAlign;
733b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
7344446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
7356a60fa24SAnders Carlsson   return Fn;
7366a60fa24SAnders Carlsson }
7371db7d04bSMike Stump 
738aeb0ffd5SMike Stump uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
7391db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
7401db7d04bSMike Stump 
7411db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
7421db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
7431db7d04bSMike Stump 
7441db7d04bSMike Stump   if (BDRE->isByRef()) {
7451db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
7461db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
7471db7d04bSMike Stump   }
7481db7d04bSMike Stump 
7491db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
7501db7d04bSMike Stump 
7511db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
7521db7d04bSMike Stump 
7531db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
7541db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
7551db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
7561db7d04bSMike Stump 
7571db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
7581db7d04bSMike Stump   if (Pad) {
75941a75027SOwen Anderson     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad);
7601db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
7611db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
7621db7d04bSMike Stump                                                        ArrayType::Normal, 0);
7631db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
7646032ef1aSArgyrios Kyrtzidis                                          0, QualType(PadTy), 0, VarDecl::None);
7651db7d04bSMike Stump     Expr *E;
7661db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
7671db7d04bSMike Stump                                        SourceLocation(), false, false);
7681db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
7691db7d04bSMike Stump   }
7701db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
7711db7d04bSMike Stump 
7721db7d04bSMike Stump   BlockOffset += Size;
7731db7d04bSMike Stump   return BlockOffset-Size;
7741db7d04bSMike Stump }
77597d01d50SMike Stump 
776aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
777aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
77867645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
7790c743277SMike Stump   QualType R = getContext().VoidTy;
7800c743277SMike Stump 
7810c743277SMike Stump   FunctionArgList Args;
7820c743277SMike Stump   // FIXME: This leaks
783aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
784aeb0ffd5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
785aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
786aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
7870c743277SMike Stump   ImplicitParamDecl *Src =
7880c743277SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
7890c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
7900c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
7910c743277SMike Stump 
7920c743277SMike Stump   const CGFunctionInfo &FI =
7930c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
7940c743277SMike Stump 
795cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
796cbc2bcafSMike Stump   // internal linkage.
7970c743277SMike Stump   std::string Name = std::string("__copy_helper_block_");
7980c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
7990c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8000c743277SMike Stump 
8010c743277SMike Stump   llvm::Function *Fn =
8020c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
8030c743277SMike Stump                            Name,
8040c743277SMike Stump                            &CGM.getModule());
8050c743277SMike Stump 
8060c743277SMike Stump   IdentifierInfo *II
8070c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
8080c743277SMike Stump 
8090c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8100c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
81160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
8120c743277SMike Stump                                           FunctionDecl::Static, false,
8130c743277SMike Stump                                           true);
8140c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
815aeb0ffd5SMike Stump 
816aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
817aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
81867645930SMike Stump 
81967645930SMike Stump   if (NoteForHelperp) {
82067645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
82167645930SMike Stump 
8229793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
823aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
824aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
825aeb0ffd5SMike Stump 
826aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
8273b65ac26SMike Stump     llvm::Type *PtrPtrT;
8289793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
8293b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
8303b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
831aeb0ffd5SMike Stump 
832aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
833aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
834aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
835aeb0ffd5SMike Stump 
836aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
837aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
838aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
839aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
840aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
8419793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
842aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
843aeb0ffd5SMike Stump 
844aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
845aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
846aeb0ffd5SMike Stump 
84741a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
84841a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
849aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
850aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
851aeb0ffd5SMike Stump       }
852aeb0ffd5SMike Stump     }
85367645930SMike Stump   }
854aeb0ffd5SMike Stump 
8550c743277SMike Stump   CGF.FinishFunction();
8560c743277SMike Stump 
857ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
85897d01d50SMike Stump }
85997d01d50SMike Stump 
860d6ef62f0SMike Stump llvm::Constant *BlockFunction::
861aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
862aeb0ffd5SMike Stump                               const llvm::StructType* T,
86367645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
8640c743277SMike Stump   QualType R = getContext().VoidTy;
8650c743277SMike Stump 
8660c743277SMike Stump   FunctionArgList Args;
8670c743277SMike Stump   // FIXME: This leaks
8680c743277SMike Stump   ImplicitParamDecl *Src =
8690c743277SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
8700c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8710c743277SMike Stump 
8720c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8730c743277SMike Stump 
8740c743277SMike Stump   const CGFunctionInfo &FI =
8750c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
8760c743277SMike Stump 
877cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
878cbc2bcafSMike Stump   // internal linkage.
8790c743277SMike Stump   std::string Name = std::string("__destroy_helper_block_");
8800c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8810c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8820c743277SMike Stump 
8830c743277SMike Stump   llvm::Function *Fn =
8840c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
8850c743277SMike Stump                            Name,
8860c743277SMike Stump                            &CGM.getModule());
8870c743277SMike Stump 
8880c743277SMike Stump   IdentifierInfo *II
8890c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
8900c743277SMike Stump 
8910c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8920c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
89360ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
8940c743277SMike Stump                                           FunctionDecl::Static, false,
8950c743277SMike Stump                                           true);
8960c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
8976f7d9f87SMike Stump 
89867645930SMike Stump   if (NoteForHelperp) {
89967645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
90067645930SMike Stump 
9016f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
9026f7d9f87SMike Stump     llvm::Type *PtrPtrT;
9039793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9046f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
9056f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
9066f7d9f87SMike Stump 
9076f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
9086f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
9096f7d9f87SMike Stump       int index = NoteForHelper[i].index;
9106f7d9f87SMike Stump 
9116f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
9126f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
9136f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
9146f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
9156f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9169793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
9176f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
9186f7d9f87SMike Stump 
9196f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
9206f7d9f87SMike Stump       }
9216f7d9f87SMike Stump     }
92267645930SMike Stump   }
9236f7d9f87SMike Stump 
9240c743277SMike Stump   CGF.FinishFunction();
9250c743277SMike Stump 
926ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
9270c743277SMike Stump }
9280c743277SMike Stump 
929aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
93067645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
931aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
932aeb0ffd5SMike Stump                                                          T, NoteForHelper);
9330c743277SMike Stump }
9340c743277SMike Stump 
935aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
93667645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
937aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
93867645930SMike Stump                                                             T, NoteForHelperp);
93997d01d50SMike Stump }
940626aecc4SMike Stump 
941f89230d9SMike Stump llvm::Constant *BlockFunction::
942f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
943ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
944ee2a5ee5SMike Stump 
945ee2a5ee5SMike Stump   FunctionArgList Args;
946ee2a5ee5SMike Stump   // FIXME: This leaks
947f89230d9SMike Stump   ImplicitParamDecl *Dst =
948f89230d9SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
949f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
950f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
951f89230d9SMike Stump 
952f89230d9SMike Stump   // FIXME: This leaks
953ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
954ee2a5ee5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
955ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
956ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
957ee2a5ee5SMike Stump 
958ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
959ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
960ee2a5ee5SMike Stump 
961ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_copy_");
962ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
963ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
964ee2a5ee5SMike Stump 
965cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
966cbc2bcafSMike Stump   // internal linkage.
967ee2a5ee5SMike Stump   llvm::Function *Fn =
968ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
969ee2a5ee5SMike Stump                            Name,
970ee2a5ee5SMike Stump                            &CGM.getModule());
971ee2a5ee5SMike Stump 
972ee2a5ee5SMike Stump   IdentifierInfo *II
973ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
974ee2a5ee5SMike Stump 
975ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
976ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
97760ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
978ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
979ee2a5ee5SMike Stump                                           true);
980ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
981f89230d9SMike Stump 
982f89230d9SMike Stump   // dst->x
983f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
9849793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
9853b65ac26SMike Stump   V = Builder.CreateLoad(V);
986f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
987f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
988f89230d9SMike Stump 
989f89230d9SMike Stump   // src->x
990f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
991f89230d9SMike Stump   V = Builder.CreateLoad(V);
992f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
993f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
9949793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
995f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
996f89230d9SMike Stump 
997f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
998f89230d9SMike Stump 
99941a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
100041a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1001f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1002f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1003f89230d9SMike Stump 
1004ee2a5ee5SMike Stump   CGF.FinishFunction();
1005ee2a5ee5SMike Stump 
1006ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1007ee2a5ee5SMike Stump }
1008ee2a5ee5SMike Stump 
1009fbe25dd1SMike Stump llvm::Constant *
1010fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1011fbe25dd1SMike Stump                                                   int flag) {
1012ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1013ee2a5ee5SMike Stump 
1014ee2a5ee5SMike Stump   FunctionArgList Args;
1015ee2a5ee5SMike Stump   // FIXME: This leaks
1016ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
1017ee2a5ee5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
1018ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1019ee2a5ee5SMike Stump 
1020ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1021ee2a5ee5SMike Stump 
1022ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1023ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
1024ee2a5ee5SMike Stump 
1025ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_dispose_");
1026ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1027ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1028ee2a5ee5SMike Stump 
1029cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1030cbc2bcafSMike Stump   // internal linkage.
1031ee2a5ee5SMike Stump   llvm::Function *Fn =
1032ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1033ee2a5ee5SMike Stump                            Name,
1034ee2a5ee5SMike Stump                            &CGM.getModule());
1035ee2a5ee5SMike Stump 
1036ee2a5ee5SMike Stump   IdentifierInfo *II
1037ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1038ee2a5ee5SMike Stump 
1039ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1040ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
104160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1042ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1043ee2a5ee5SMike Stump                                           true);
1044ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1045fbe25dd1SMike Stump 
1046fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
10479793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10483b65ac26SMike Stump   V = Builder.CreateLoad(V);
1049fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10509793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
10513b65ac26SMike Stump   V = Builder.CreateLoad(V);
1052fbe25dd1SMike Stump 
1053fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1054fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1055ee2a5ee5SMike Stump   CGF.FinishFunction();
1056ee2a5ee5SMike Stump 
1057ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1058ee2a5ee5SMike Stump }
1059ee2a5ee5SMike Stump 
1060f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1061cbc2bcafSMike Stump                                                     int flag, unsigned Align) {
1062cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1063cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1064cbc2bcafSMike Stump   // with.
1065cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1066cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1067cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1068cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1069cbc2bcafSMike Stump   uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1070cbc2bcafSMike Stump   llvm::Constant *& Entry = CGM.AssignCache[kind];
1071cbc2bcafSMike Stump   if (Entry)
1072cbc2bcafSMike Stump     return Entry;
1073cbc2bcafSMike Stump   return Entry=CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
1074ee2a5ee5SMike Stump }
1075ee2a5ee5SMike Stump 
1076fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1077cbc2bcafSMike Stump                                                        int flag,
1078cbc2bcafSMike Stump                                                        unsigned Align) {
1079cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1080cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1081cbc2bcafSMike Stump   // with.
1082cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1083cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1084cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1085cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1086cbc2bcafSMike Stump   uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1087cbc2bcafSMike Stump   llvm::Constant *& Entry = CGM.DestroyCache[kind];
1088cbc2bcafSMike Stump   if (Entry)
1089cbc2bcafSMike Stump     return Entry;
1090cbc2bcafSMike Stump   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
1091ee2a5ee5SMike Stump }
1092ee2a5ee5SMike Stump 
1093626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1094626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1095626aecc4SMike Stump     const llvm::FunctionType *FTy;
1096626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
109741a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1098626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
109941a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11009793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1101626aecc4SMike Stump     CGM.BlockObjectDispose
1102626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1103626aecc4SMike Stump   }
1104626aecc4SMike Stump   return CGM.BlockObjectDispose;
1105626aecc4SMike Stump }
1106626aecc4SMike Stump 
1107f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1108f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1109f89230d9SMike Stump     const llvm::FunctionType *FTy;
1110f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
111141a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1112f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1113f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
111441a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11159793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1116f89230d9SMike Stump     CGM.BlockObjectAssign
1117f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1118f89230d9SMike Stump   }
1119f89230d9SMike Stump   return CGM.BlockObjectAssign;
1120f89230d9SMike Stump }
1121f89230d9SMike Stump 
1122fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1123626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1124fbe25dd1SMike Stump   llvm::Value *N;
1125626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
112641a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1127626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1128626aecc4SMike Stump }
11294446dcf0SMike Stump 
11304446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1131aeb0ffd5SMike Stump 
1132aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1133aeb0ffd5SMike Stump                              CGBuilderTy &B)
1134170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
113541a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
113641a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1137aeb0ffd5SMike Stump 
1138aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1139aeb0ffd5SMike Stump }
1140