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 
76*066b6166SMike Stump static void CollectBlockDeclRefInfo(
77*066b6166SMike Stump   const Stmt *S, CodeGenFunction::BlockInfo &Info,
78*066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> &InnerContexts) {
79ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
80ed5e69feSAnders Carlsson        I != E; ++I)
81dd942713SDaniel Dunbar     if (*I)
82*066b6166SMike Stump       CollectBlockDeclRefInfo(*I, Info, InnerContexts);
83ed5e69feSAnders Carlsson 
847fe9cc1dSMike Stump   // We want to ensure we walk down into block literals so we can find
857fe9cc1dSMike Stump   // all nested BlockDeclRefExprs.
86*066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
87*066b6166SMike Stump     InnerContexts.insert(cast<DeclContext>(BE->getBlockDecl()));
88*066b6166SMike Stump     CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
89*066b6166SMike Stump   }
907fe9cc1dSMike Stump 
91*066b6166SMike Stump   if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
92ed5e69feSAnders Carlsson     // FIXME: Handle enums.
93*066b6166SMike Stump     if (isa<FunctionDecl>(BDRE->getDecl()))
94ed5e69feSAnders Carlsson       return;
95ed5e69feSAnders Carlsson 
96*066b6166SMike Stump     // Only Decls that escape are added.
97*066b6166SMike Stump     if (!InnerContexts.count(BDRE->getDecl()->getDeclContext()))
98*066b6166SMike Stump       Info.DeclRefs.push_back(BDRE);
99ed5e69feSAnders Carlsson   }
100ed5e69feSAnders Carlsson }
101ed5e69feSAnders Carlsson 
1022d33d630SMike Stump /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
1032d33d630SMike Stump /// declared as a global variable instead of on the stack.
10446813bbfSChris Lattner static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
1057fe9cc1dSMike Stump   return Info.DeclRefs.empty();
1067fe9cc1dSMike Stump }
1077fe9cc1dSMike Stump 
1087fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
1097fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block
1107fe9cc1dSMike Stump /// invoke function.
1117fe9cc1dSMike Stump static void AllocateAllBlockDeclRefs(const CodeGenFunction::BlockInfo &Info,
1127fe9cc1dSMike Stump                                      CodeGenFunction *CGF) {
1137fe9cc1dSMike Stump   // Always allocate self, as it is often handy in the debugger, even if there
1147fe9cc1dSMike Stump   // is no codegen in the block that uses it.  This is also useful to always do
1157fe9cc1dSMike Stump   // this as if we didn't, we'd have to figure out all code that uses a self
1167fe9cc1dSMike Stump   // pointer, including implicit uses.
1177fe9cc1dSMike Stump   if (const ObjCMethodDecl *OMD
1187fe9cc1dSMike Stump       = dyn_cast_or_null<ObjCMethodDecl>(CGF->CurFuncDecl)) {
1197fe9cc1dSMike Stump     ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
1207fe9cc1dSMike Stump     BlockDeclRefExpr *BDRE = new (CGF->getContext())
1217fe9cc1dSMike Stump       BlockDeclRefExpr(SelfDecl,
1227fe9cc1dSMike Stump                        SelfDecl->getType(), SourceLocation(), false);
1237fe9cc1dSMike Stump     CGF->AllocateBlockDecl(BDRE);
1247fe9cc1dSMike Stump   }
1257fe9cc1dSMike Stump 
1267fe9cc1dSMike Stump   // FIXME: Also always forward the this pointer in C++ as well.
1277fe9cc1dSMike Stump 
1287fe9cc1dSMike Stump   for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
1297fe9cc1dSMike Stump     CGF->AllocateBlockDecl(Info.DeclRefs[i]);
130ed5e69feSAnders Carlsson }
131ed5e69feSAnders Carlsson 
1322d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
1332d33d630SMike Stump // name.
134b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
135ed5e69feSAnders Carlsson 
136ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
137ed5e69feSAnders Carlsson   CodeGenFunction::BlockInfo Info(0, Name.c_str());
138*066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> InnerContexts;
139*066b6166SMike Stump   InnerContexts.insert(BE->getBlockDecl());
140*066b6166SMike Stump   CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
141ed5e69feSAnders Carlsson 
142ed5e69feSAnders Carlsson   // Check if the block can be global.
1432d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
1442d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
1452d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
14697d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
147ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
14885284bacSMike Stump 
1494446dcf0SMike Stump   std::vector<llvm::Constant*> Elts(5);
15085284bacSMike Stump   llvm::Constant *C;
151b750d928SMike Stump   llvm::Value *V;
15285284bacSMike Stump 
15385284bacSMike Stump   {
15485284bacSMike Stump     // C = BuildBlockStructInitlist();
15585284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
15685284bacSMike Stump 
1574446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1584446dcf0SMike Stump     // block literal.
1594446dcf0SMike Stump     // __invoke
1604446dcf0SMike Stump     uint64_t subBlockSize, subBlockAlign;
1614446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
162d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1634446dcf0SMike Stump     llvm::Function *Fn
164d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
165d2a3e617SMike Stump                                                    LocalDeclMap,
1665469f29aSMike Stump                                                    subBlockSize,
1674446dcf0SMike Stump                                                    subBlockAlign,
1684446dcf0SMike Stump                                                    subBlockDeclRefDecls,
169d2142cffSMike Stump                                                    subBlockHasCopyDispose);
170d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1714446dcf0SMike Stump     Elts[3] = Fn;
1724446dcf0SMike Stump 
17318bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
17418bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
175d2142cffSMike Stump     if (subBlockHasCopyDispose)
17685284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
17785284bacSMike Stump 
178499ae7ecSMike Stump     // __isa
1797ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
180ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1814446dcf0SMike Stump     Elts[0] = C;
18285284bacSMike Stump 
18385284bacSMike Stump     // __flags
18485284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
18585284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
186b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
1874446dcf0SMike Stump     Elts[1] = C;
18885284bacSMike Stump 
18985284bacSMike Stump     // __reserved
190b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
1914446dcf0SMike Stump     Elts[2] = C;
19285284bacSMike Stump 
193b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
194d6ef62f0SMike Stump       // __descriptor
1957fe9cc1dSMike Stump       Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize,
1967fe9cc1dSMike Stump                                          0, 0);
197d6ef62f0SMike Stump 
1983a139f37SMike Stump       // Optimize to being a global block.
1993a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
200b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2013a139f37SMike Stump 
20241eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
20385284bacSMike Stump 
20485284bacSMike Stump       char Name[32];
2059319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
206c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
20785284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
208c10c8d3eSOwen Anderson                                    C, Name);
2095d2534adSMike Stump       QualType BPT = BE->getType();
210ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
21185284bacSMike Stump       return C;
21285284bacSMike Stump     }
21385284bacSMike Stump 
214b750d928SMike Stump     std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
215aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
216b750d928SMike Stump       Types[i] = Elts[i]->getType();
217aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
21885284bacSMike Stump 
2191db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2201db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2211db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2221db7d04bSMike Stump       QualType Ty = E->getType();
22397d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
22471d1d92dSAnders Carlsson         Types[i+5] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
22597d01d50SMike Stump       } else
2261db7d04bSMike Stump         Types[i+5] = ConvertType(Ty);
2271db7d04bSMike Stump     }
228b750d928SMike Stump 
229758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
230b750d928SMike Stump 
231b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
232b750d928SMike Stump     A->setAlignment(subBlockAlign);
233b750d928SMike Stump     V = A;
234b750d928SMike Stump 
235aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
236aeb0ffd5SMike Stump     int helpersize = 0;
237aeb0ffd5SMike Stump 
238aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
239b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
240b750d928SMike Stump 
241b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
242b750d928SMike Stump       {
2431db7d04bSMike Stump         // FIXME: Push const down.
2441db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2451db7d04bSMike Stump         DeclRefExpr *DR;
2461db7d04bSMike Stump         ValueDecl *VD;
247b750d928SMike Stump 
2481db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2491db7d04bSMike Stump         // Skip padding.
2501db7d04bSMike Stump         if (DR) continue;
2511db7d04bSMike Stump 
2521db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2531db7d04bSMike Stump         VD = BDRE->getDecl();
2541db7d04bSMike Stump 
25597d01d50SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
256aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
2572114d7c2SMike Stump         NoteForHelper[helpersize].RequiresCopying
2582114d7c2SMike Stump           = BlockRequiresCopying(VD->getType());
259aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
2602114d7c2SMike Stump           = (VD->getType()->isBlockPointerType()
2612114d7c2SMike Stump              ? BLOCK_FIELD_IS_BLOCK
2622114d7c2SMike Stump              : BLOCK_FIELD_IS_OBJECT);
263aeb0ffd5SMike Stump 
2641db7d04bSMike Stump         if (LocalDeclMap[VD]) {
26597d01d50SMike Stump           if (BDRE->isByRef()) {
266aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
26790d8daf5SMike Stump               // FIXME: Someone double check this.
26890d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
26997d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
27097d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
27197d01d50SMike Stump             Loc = Builder.CreateLoad(Loc, false);
27297d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
273aeb0ffd5SMike Stump             ++helpersize;
27497d01d50SMike Stump             continue;
27597d01d50SMike Stump           } else
2761db7d04bSMike Stump             E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
2771db7d04bSMike Stump                                                 VD->getType(), SourceLocation(),
2781db7d04bSMike Stump                                                 false, false);
2791db7d04bSMike Stump         }
28097d01d50SMike Stump         if (BDRE->isByRef()) {
281efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
282efd7caa8SMike Stump             // FIXME: Someone double check this.
283efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
2841db7d04bSMike Stump           E = new (getContext())
2851db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
2861db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
2871db7d04bSMike Stump                           SourceLocation());
28897d01d50SMike Stump         }
289aeb0ffd5SMike Stump         ++helpersize;
2901db7d04bSMike Stump 
2911db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
29297d01d50SMike Stump         if (r.isScalar()) {
29397d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
29497d01d50SMike Stump           const llvm::Type *Ty = Types[i+5];
29597d01d50SMike Stump           if  (BDRE->isByRef()) {
2962d33d630SMike Stump             // E is now the address of the value field, instead, we want the
2972d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
2982d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
2992d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
3002d33d630SMike Stump             // until then.
3012d33d630SMike Stump             uint64_t offset = BlockDecls[BDRE->getDecl()];
3022d33d630SMike Stump 
3032d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
3042d33d630SMike Stump 
3052d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
30641a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
3072d33d630SMike Stump                                                            offset),
3082d33d630SMike Stump                                     "block.literal");
3099793f0e4SOwen Anderson             Ty = llvm::PointerType::get(Ty, 0);
31097d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
3112d33d630SMike Stump             Loc = Builder.CreateLoad(Loc, false);
3122d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
31397d01d50SMike Stump           }
31497d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
31597d01d50SMike Stump         } else if (r.isComplex())
316b750d928SMike Stump           // FIXME: implement
317b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
318b750d928SMike Stump         else if (r.isAggregate())
319b750d928SMike Stump           ; // Already created into the destination
320b750d928SMike Stump         else
321b750d928SMike Stump           assert (0 && "bad block variable");
322b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
323b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
324b750d928SMike Stump       }
325aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
326d6ef62f0SMike Stump 
327d6ef62f0SMike Stump     // __descriptor
328d2142cffSMike Stump     llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
329d2142cffSMike Stump                                                        subBlockSize, Ty,
330aeb0ffd5SMike Stump                                                        &NoteForHelper);
331aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
332aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
333b750d928SMike Stump   }
334b750d928SMike Stump 
335b750d928SMike Stump   QualType BPT = BE->getType();
336b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
337b750d928SMike Stump }
33885284bacSMike Stump 
33985284bacSMike Stump 
34095435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
341650c932dSMike Stump   if (BlockDescriptorType)
342650c932dSMike Stump     return BlockDescriptorType;
3432437cbfaSAnders Carlsson 
3442437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
345650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3462437cbfaSAnders Carlsson 
3472437cbfaSAnders Carlsson   // struct __block_descriptor {
3482437cbfaSAnders Carlsson   //   unsigned long reserved;
3492437cbfaSAnders Carlsson   //   unsigned long block_size;
3502437cbfaSAnders Carlsson   // };
351758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
352758428f4SOwen Anderson                                               UnsignedLongTy,
3532437cbfaSAnders Carlsson                                               UnsignedLongTy,
3542437cbfaSAnders Carlsson                                               NULL);
3552437cbfaSAnders Carlsson 
356650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
357650c932dSMike Stump                           BlockDescriptorType);
3582437cbfaSAnders Carlsson 
359650c932dSMike Stump   return BlockDescriptorType;
3602437cbfaSAnders Carlsson }
3612437cbfaSAnders Carlsson 
36295435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
363005c9a62SMike Stump   if (GenericBlockLiteralType)
364005c9a62SMike Stump     return GenericBlockLiteralType;
3652437cbfaSAnders Carlsson 
3662437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
3679793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3682437cbfaSAnders Carlsson 
36992bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
37092bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
37192bbd6d4SMike Stump 
3722437cbfaSAnders Carlsson   // struct __block_literal_generic {
3735d2534adSMike Stump   //   void *__isa;
3745d2534adSMike Stump   //   int __flags;
3755d2534adSMike Stump   //   int __reserved;
3765d2534adSMike Stump   //   void (*__invoke)(void *);
3775d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3782437cbfaSAnders Carlsson   // };
379758428f4SOwen Anderson   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
380758428f4SOwen Anderson                                                   PtrToInt8Ty,
38192bbd6d4SMike Stump                                                   IntTy,
38292bbd6d4SMike Stump                                                   IntTy,
383626aecc4SMike Stump                                                   PtrToInt8Ty,
3842437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
3852437cbfaSAnders Carlsson                                                   NULL);
3862437cbfaSAnders Carlsson 
387005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
388005c9a62SMike Stump                           GenericBlockLiteralType);
3892437cbfaSAnders Carlsson 
390005c9a62SMike Stump   return GenericBlockLiteralType;
3912437cbfaSAnders Carlsson }
3922437cbfaSAnders Carlsson 
39395435674SMike Stump const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
3945d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
3955d2534adSMike Stump     return GenericExtendedBlockLiteralType;
3965d2534adSMike Stump 
3975d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
3989793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3995d2534adSMike Stump 
4005d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
4015d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
4025d2534adSMike Stump 
4035d2534adSMike Stump   // struct __block_literal_generic {
4045d2534adSMike Stump   //   void *__isa;
4055d2534adSMike Stump   //   int __flags;
4065d2534adSMike Stump   //   int __reserved;
4075d2534adSMike Stump   //   void (*__invoke)(void *);
4085d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4095d2534adSMike Stump   //   void *__copy_func_helper_decl;
4105d2534adSMike Stump   //   void *__destroy_func_decl;
4115d2534adSMike Stump   // };
412758428f4SOwen Anderson   GenericExtendedBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
413758428f4SOwen Anderson                                                           PtrToInt8Ty,
4145d2534adSMike Stump                                                           IntTy,
4155d2534adSMike Stump                                                           IntTy,
416626aecc4SMike Stump                                                           PtrToInt8Ty,
4175d2534adSMike Stump                                                           BlockDescPtrTy,
418626aecc4SMike Stump                                                           PtrToInt8Ty,
419626aecc4SMike Stump                                                           PtrToInt8Ty,
4205d2534adSMike Stump                                                           NULL);
4215d2534adSMike Stump 
4225d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
4235d2534adSMike Stump                           GenericExtendedBlockLiteralType);
4245d2534adSMike Stump 
4255d2534adSMike Stump   return GenericExtendedBlockLiteralType;
4265d2534adSMike Stump }
4275d2534adSMike Stump 
4286a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
4292437cbfaSAnders Carlsson   const BlockPointerType *BPT =
430c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
4312437cbfaSAnders Carlsson 
4322437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4332437cbfaSAnders Carlsson 
4342437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4352437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
4369793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4372437cbfaSAnders Carlsson 
4382437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4392437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4402437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4412437cbfaSAnders Carlsson 
4422437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4432437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4442437cbfaSAnders Carlsson 
4452437cbfaSAnders Carlsson   BlockLiteral =
4462437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
447abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
4482437cbfaSAnders Carlsson                           "tmp");
4492437cbfaSAnders Carlsson 
4502437cbfaSAnders Carlsson   // Add the block literal.
4512437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4522437cbfaSAnders Carlsson   CallArgList Args;
4532437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4542437cbfaSAnders Carlsson 
455479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
456479e6fc7SAnders Carlsson 
4572437cbfaSAnders Carlsson   // And the rest of the arguments.
4589dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
459479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4602437cbfaSAnders Carlsson 
4615f50c651SAnders Carlsson   // Load the function.
4625f50c651SAnders Carlsson   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
4635f50c651SAnders Carlsson 
4649dd450bbSJohn McCall   QualType ResultType = FnType->getAs<FunctionType>()->getResultType();
465a60cbcdfSAnders Carlsson 
466a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
467a60cbcdfSAnders Carlsson     CGM.getTypes().getFunctionInfo(ResultType, Args);
4685f50c651SAnders Carlsson 
4695f50c651SAnders Carlsson   // Cast the function pointer to the right type.
4705f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
471a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
4725f50c651SAnders Carlsson 
4739793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
4745f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4755f50c651SAnders Carlsson 
4762437cbfaSAnders Carlsson   // And call the block.
477350da607SAnders Carlsson   return EmitCall(FnInfo, Func, Args);
4782437cbfaSAnders Carlsson }
4796a60fa24SAnders Carlsson 
4807fe9cc1dSMike Stump uint64_t CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
4810168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
4820168f4b2SAnders Carlsson   uint64_t &offset = BlockDecls[VD];
4830168f4b2SAnders Carlsson 
48497d01d50SMike Stump   // See if we have already allocated an offset for this variable.
4857fe9cc1dSMike Stump   if (offset)
4867fe9cc1dSMike Stump     return offset;
4877fe9cc1dSMike Stump 
4884446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
4894446dcf0SMike Stump   if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
4904446dcf0SMike Stump     BlockHasCopyDispose = true;
4917fe9cc1dSMike Stump 
49297d01d50SMike Stump   // if not, allocate one now.
49397d01d50SMike Stump   offset = getBlockOffset(E);
4947fe9cc1dSMike Stump 
4957fe9cc1dSMike Stump   return offset;
49697d01d50SMike Stump }
49797d01d50SMike Stump 
4987fe9cc1dSMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
4997fe9cc1dSMike Stump   const ValueDecl *VD = E->getDecl();
5007fe9cc1dSMike Stump   uint64_t offset = AllocateBlockDecl(E);
5017fe9cc1dSMike Stump 
5027fe9cc1dSMike Stump 
50397d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
50497d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
50541a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
50697d01d50SMike Stump                                                          offset),
5072d33d630SMike Stump                                      "block.literal");
50897d01d50SMike Stump   if (E->isByRef()) {
50997d01d50SMike Stump     const llvm::Type *PtrStructTy
5100168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
511efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
512efd7caa8SMike Stump     BlockHasCopyDispose = true;
5130168f4b2SAnders Carlsson 
5140168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
5159793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
51697d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
51797d01d50SMike Stump     V = Builder.CreateLoad(V, false);
51897d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
51997d01d50SMike Stump     V = Builder.CreateLoad(V, false);
52097d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
5210168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
5220168f4b2SAnders Carlsson                                 VD->getNameAsString());
52397d01d50SMike Stump   } else {
5240168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
5250168f4b2SAnders Carlsson 
5269793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
52797d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
52897d01d50SMike Stump   }
52997d01d50SMike Stump   return V;
53097d01d50SMike Stump }
53197d01d50SMike Stump 
532692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
533692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
534692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
535692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
536692c6e37SMike Stump   if (DMEntry)
537692c6e37SMike Stump     return;
538692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
539692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
540692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
541692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
542692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
543692c6e37SMike Stump }
544692c6e37SMike Stump 
5452d5a2878SMike Stump llvm::Constant *
5466c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
5476a60fa24SAnders Carlsson   // Generate the block descriptor.
5486a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
54992bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
55092bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5516a60fa24SAnders Carlsson 
5526a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
5536a60fa24SAnders Carlsson 
5546a60fa24SAnders Carlsson   // Reserved
5550b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
5566a60fa24SAnders Carlsson 
5576a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5586a60fa24SAnders Carlsson   // block literal struct.
5596a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
560005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
561170229f6SOwen Anderson   DescriptorFields[1] =
562b7a2fe6fSOwen Anderson                       llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
5636a60fa24SAnders Carlsson 
5646a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
56541eaf0acSNick Lewycky     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 2, false);
5666a60fa24SAnders Carlsson 
5676a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
568c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
5696a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
570c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
5716a60fa24SAnders Carlsson 
5726a60fa24SAnders Carlsson   // Generate the constants for the block literal.
5736a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
5746a60fa24SAnders Carlsson 
5752d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
576b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
5771db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
578a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
5795469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
580cb2fbcb0SMike Stump   llvm::Function *Fn
581692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
5825469f29aSMike Stump                                                  subBlockSize,
583b750d928SMike Stump                                                  subBlockAlign,
5844446dcf0SMike Stump                                                  subBlockDeclRefDecls,
5854446dcf0SMike Stump                                                  subBlockHasCopyDispose);
586cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
587cb2fbcb0SMike Stump          && "no imports allowed for global block");
5886a60fa24SAnders Carlsson 
5896a60fa24SAnders Carlsson   // isa
590971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
5916a60fa24SAnders Carlsson 
5926a60fa24SAnders Carlsson   // Flags
5935878c797SAnders Carlsson   LiteralFields[1] =
594b7a2fe6fSOwen Anderson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
5956a60fa24SAnders Carlsson 
5966a60fa24SAnders Carlsson   // Reserved
5970b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
5986a60fa24SAnders Carlsson 
5996a60fa24SAnders Carlsson   // Function
6006a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
6016a60fa24SAnders Carlsson 
6026a60fa24SAnders Carlsson   // Descriptor
6036a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
6046a60fa24SAnders Carlsson 
6056a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
60641eaf0acSNick Lewycky     llvm::ConstantStruct::get(VMContext, &LiteralFields[0], 5, false);
6076a60fa24SAnders Carlsson 
6086a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
609c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
6106a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
611c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
6126a60fa24SAnders Carlsson 
6136a60fa24SAnders Carlsson   return BlockLiteral;
6146a60fa24SAnders Carlsson }
6156a60fa24SAnders Carlsson 
616cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
61738382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
61838382028SMike Stump                                       "self");
61938382028SMike Stump   // For now, we codegen based upon byte offsets.
62038382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
621cb2fbcb0SMike Stump }
622cb2fbcb0SMike Stump 
6234446dcf0SMike Stump llvm::Function *
6244446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
625cb2fbcb0SMike Stump                                        const BlockInfo& Info,
626692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
6275469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
628b750d928SMike Stump                                        uint64_t &Size,
629b750d928SMike Stump                                        uint64_t &Align,
6304446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
6314446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
6329074ed8cSDevang Patel 
6339074ed8cSDevang Patel   // Check if we should generate debug info for this block.
6349074ed8cSDevang Patel   if (CGM.getDebugInfo())
6359074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
6369074ed8cSDevang Patel 
6375469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
6385469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
6395469f29aSMike Stump   // in a block.
6405469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
6415469f29aSMike Stump        i != ldm.end();
6425469f29aSMike Stump        ++i) {
6435469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
6445469f29aSMike Stump 
6450ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
6465469f29aSMike Stump       LocalDeclMap[VD] = i->second;
6475469f29aSMike Stump   }
6485469f29aSMike Stump 
64909a9b6e3SEli Friedman   // FIXME: We need to rearrange the code for copy/dispose so we have this
65009a9b6e3SEli Friedman   // sooner, so we can calculate offsets correctly.
65109a9b6e3SEli Friedman   if (!BlockHasCopyDispose)
65209a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
65309a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
65409a9b6e3SEli Friedman   else
65509a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
65609a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
65709a9b6e3SEli Friedman   BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
65809a9b6e3SEli Friedman 
659aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
660aae4349dSFariborz Jahanian   QualType ResultType;
661aae4349dSFariborz Jahanian   bool IsVariadic;
662a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
663a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
664aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
665aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
666658fe02dSMike Stump   } else {
667aae4349dSFariborz Jahanian     // K&R style block.
668aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
669aae4349dSFariborz Jahanian     IsVariadic = false;
670aae4349dSFariborz Jahanian   }
6716a60fa24SAnders Carlsson 
6726a60fa24SAnders Carlsson   FunctionArgList Args;
6736a60fa24SAnders Carlsson 
6747fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
6757fe9cc1dSMike Stump 
6763385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
6776a60fa24SAnders Carlsson 
6787fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
679d015328fSMike Stump 
680945fec05SMike Stump   // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
6817fe9cc1dSMike Stump   // FIXME: Resolve testsuite problems, then enable.
6827fe9cc1dSMike Stump   if (0)
6837fe9cc1dSMike Stump     AllocateAllBlockDeclRefs(Info, this);
6847fe9cc1dSMike Stump 
6857fe9cc1dSMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockDeclRefDecls);
6866a60fa24SAnders Carlsson   // FIXME: This leaks
6876a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
6886a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
689d015328fSMike Stump                               SourceLocation(), II,
690d015328fSMike Stump                               ParmTy);
6916a60fa24SAnders Carlsson 
6926a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
693cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
6946a60fa24SAnders Carlsson 
695c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
6966a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
697eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
6986a60fa24SAnders Carlsson 
6996a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
700aae4349dSFariborz Jahanian     CGM.getTypes().getFunctionInfo(ResultType, Args);
7016a60fa24SAnders Carlsson 
7022d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
7036a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
704aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
7056a60fa24SAnders Carlsson 
7066a60fa24SAnders Carlsson   llvm::Function *Fn =
7076a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
7086a60fa24SAnders Carlsson                            Name,
7096a60fa24SAnders Carlsson                            &CGM.getModule());
7106a60fa24SAnders Carlsson 
711c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
712c3e7cff6SDaniel Dunbar 
713324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
7143385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
7152e722b91SMike Stump 
716324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
71728ec0cf8SChris Lattner   CurCodeDecl = BD;
718017460abSMike Stump 
719017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
720017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
721017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
722017460abSMike Stump   --entry_ptr;
723017460abSMike Stump 
7243385fe12SChris Lattner   EmitStmt(BExpr->getBody());
725017460abSMike Stump 
7267d69911aSMike Stump   // Remember where we were...
7277d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
728017460abSMike Stump 
7297d69911aSMike Stump   // Go back to the entry.
730017460abSMike Stump   ++entry_ptr;
731017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
732017460abSMike Stump 
7332e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
7342e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
7352e722b91SMike Stump     for (unsigned i=0; i < BlockDeclRefDecls.size(); ++i) {
7362e722b91SMike Stump       const Expr *E = BlockDeclRefDecls[i];
7372e722b91SMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
7382e722b91SMike Stump       if (BDRE) {
7392e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
7402e722b91SMike Stump         DI->setLocation(D->getLocation());
7412e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
7422e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
7432e722b91SMike Stump                                               Builder, this);
7442e722b91SMike Stump       }
7452e722b91SMike Stump     }
7462e722b91SMike Stump   }
7477d69911aSMike Stump   // And resume where we left off.
7487d69911aSMike Stump   if (resume == 0)
7497d69911aSMike Stump     Builder.ClearInsertionPoint();
7507d69911aSMike Stump   else
7517d69911aSMike Stump     Builder.SetInsertPoint(resume);
7522e722b91SMike Stump 
7533385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
7546a60fa24SAnders Carlsson 
755b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
756b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
757b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
758b750d928SMike Stump 
759cb2fbcb0SMike Stump   Size = BlockOffset;
760b750d928SMike Stump   Align = BlockAlign;
761b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
7624446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
7636a60fa24SAnders Carlsson   return Fn;
7646a60fa24SAnders Carlsson }
7651db7d04bSMike Stump 
766aeb0ffd5SMike Stump uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
7671db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
7681db7d04bSMike Stump 
7691db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
7701db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
7711db7d04bSMike Stump 
7721db7d04bSMike Stump   if (BDRE->isByRef()) {
7731db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
7741db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
7751db7d04bSMike Stump   }
7761db7d04bSMike Stump 
7771db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
7781db7d04bSMike Stump 
7791db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
7801db7d04bSMike Stump 
7811db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
7821db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
7831db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
7841db7d04bSMike Stump 
7851db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
7861db7d04bSMike Stump   if (Pad) {
78741a75027SOwen Anderson     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad);
7881db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
7891db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
7901db7d04bSMike Stump                                                        ArrayType::Normal, 0);
7911db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
7926032ef1aSArgyrios Kyrtzidis                                          0, QualType(PadTy), 0, VarDecl::None);
7931db7d04bSMike Stump     Expr *E;
7941db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
7951db7d04bSMike Stump                                        SourceLocation(), false, false);
7961db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
7971db7d04bSMike Stump   }
7981db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
7991db7d04bSMike Stump 
8001db7d04bSMike Stump   BlockOffset += Size;
8011db7d04bSMike Stump   return BlockOffset-Size;
8021db7d04bSMike Stump }
80397d01d50SMike Stump 
804aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
805aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
80667645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
8070c743277SMike Stump   QualType R = getContext().VoidTy;
8080c743277SMike Stump 
8090c743277SMike Stump   FunctionArgList Args;
8100c743277SMike Stump   // FIXME: This leaks
811aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
8127fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8137fe9cc1dSMike Stump                               SourceLocation(), 0,
814aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
815aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
8160c743277SMike Stump   ImplicitParamDecl *Src =
8177fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8187fe9cc1dSMike Stump                               SourceLocation(), 0,
8190c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8200c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8210c743277SMike Stump 
8220c743277SMike Stump   const CGFunctionInfo &FI =
8230c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
8240c743277SMike Stump 
825cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
826cbc2bcafSMike Stump   // internal linkage.
8270c743277SMike Stump   std::string Name = std::string("__copy_helper_block_");
8280c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8290c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8300c743277SMike Stump 
8310c743277SMike Stump   llvm::Function *Fn =
8320c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
8330c743277SMike Stump                            Name,
8340c743277SMike Stump                            &CGM.getModule());
8350c743277SMike Stump 
8360c743277SMike Stump   IdentifierInfo *II
8370c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
8380c743277SMike Stump 
8390c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8400c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
84160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
8420c743277SMike Stump                                           FunctionDecl::Static, false,
8430c743277SMike Stump                                           true);
8440c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
845aeb0ffd5SMike Stump 
846aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
847aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
84867645930SMike Stump 
84967645930SMike Stump   if (NoteForHelperp) {
85067645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
85167645930SMike Stump 
8529793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
853aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
854aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
855aeb0ffd5SMike Stump 
856aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
8573b65ac26SMike Stump     llvm::Type *PtrPtrT;
8589793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
8593b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
8603b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
861aeb0ffd5SMike Stump 
862aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
863aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
864aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
865aeb0ffd5SMike Stump 
866aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
867aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
868aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
869aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
870aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
8719793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
872aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
873aeb0ffd5SMike Stump 
874aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
875aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
876aeb0ffd5SMike Stump 
87741a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
87841a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
879aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
880aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
881aeb0ffd5SMike Stump       }
882aeb0ffd5SMike Stump     }
88367645930SMike Stump   }
884aeb0ffd5SMike Stump 
8850c743277SMike Stump   CGF.FinishFunction();
8860c743277SMike Stump 
887ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
88897d01d50SMike Stump }
88997d01d50SMike Stump 
890d6ef62f0SMike Stump llvm::Constant *BlockFunction::
891aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
892aeb0ffd5SMike Stump                               const llvm::StructType* T,
89367645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
8940c743277SMike Stump   QualType R = getContext().VoidTy;
8950c743277SMike Stump 
8960c743277SMike Stump   FunctionArgList Args;
8970c743277SMike Stump   // FIXME: This leaks
8980c743277SMike Stump   ImplicitParamDecl *Src =
8997fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9007fe9cc1dSMike Stump                               SourceLocation(), 0,
9010c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9020c743277SMike Stump 
9030c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9040c743277SMike Stump 
9050c743277SMike Stump   const CGFunctionInfo &FI =
9060c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
9070c743277SMike Stump 
908cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
909cbc2bcafSMike Stump   // internal linkage.
9100c743277SMike Stump   std::string Name = std::string("__destroy_helper_block_");
9110c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9120c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9130c743277SMike Stump 
9140c743277SMike Stump   llvm::Function *Fn =
9150c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
9160c743277SMike Stump                            Name,
9170c743277SMike Stump                            &CGM.getModule());
9180c743277SMike Stump 
9190c743277SMike Stump   IdentifierInfo *II
9200c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
9210c743277SMike Stump 
9220c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9230c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
92460ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
9250c743277SMike Stump                                           FunctionDecl::Static, false,
9260c743277SMike Stump                                           true);
9270c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
9286f7d9f87SMike Stump 
92967645930SMike Stump   if (NoteForHelperp) {
93067645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
93167645930SMike Stump 
9326f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
9336f7d9f87SMike Stump     llvm::Type *PtrPtrT;
9349793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9356f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
9366f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
9376f7d9f87SMike Stump 
9386f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
9396f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
9406f7d9f87SMike Stump       int index = NoteForHelper[i].index;
9416f7d9f87SMike Stump 
9426f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
9436f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
9446f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
9456f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
9466f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9479793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
9486f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
9496f7d9f87SMike Stump 
9506f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
9516f7d9f87SMike Stump       }
9526f7d9f87SMike Stump     }
95367645930SMike Stump   }
9546f7d9f87SMike Stump 
9550c743277SMike Stump   CGF.FinishFunction();
9560c743277SMike Stump 
957ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
9580c743277SMike Stump }
9590c743277SMike Stump 
960aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
96167645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
962aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
963aeb0ffd5SMike Stump                                                          T, NoteForHelper);
9640c743277SMike Stump }
9650c743277SMike Stump 
966aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
96767645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
968aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
96967645930SMike Stump                                                             T, NoteForHelperp);
97097d01d50SMike Stump }
971626aecc4SMike Stump 
972f89230d9SMike Stump llvm::Constant *BlockFunction::
973f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
974ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
975ee2a5ee5SMike Stump 
976ee2a5ee5SMike Stump   FunctionArgList Args;
977ee2a5ee5SMike Stump   // FIXME: This leaks
978f89230d9SMike Stump   ImplicitParamDecl *Dst =
9797fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9807fe9cc1dSMike Stump                               SourceLocation(), 0,
981f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
982f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
983f89230d9SMike Stump 
984f89230d9SMike Stump   // FIXME: This leaks
985ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
9867fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9877fe9cc1dSMike Stump                               SourceLocation(), 0,
988ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
989ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
990ee2a5ee5SMike Stump 
991ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
992ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
993ee2a5ee5SMike Stump 
994ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_copy_");
995ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
996ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
997ee2a5ee5SMike Stump 
998cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
999cbc2bcafSMike Stump   // internal linkage.
1000ee2a5ee5SMike Stump   llvm::Function *Fn =
1001ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1002ee2a5ee5SMike Stump                            Name,
1003ee2a5ee5SMike Stump                            &CGM.getModule());
1004ee2a5ee5SMike Stump 
1005ee2a5ee5SMike Stump   IdentifierInfo *II
1006ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1007ee2a5ee5SMike Stump 
1008ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1009ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
101060ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1011ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1012ee2a5ee5SMike Stump                                           true);
1013ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1014f89230d9SMike Stump 
1015f89230d9SMike Stump   // dst->x
1016f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
10179793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10183b65ac26SMike Stump   V = Builder.CreateLoad(V);
1019f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1020f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1021f89230d9SMike Stump 
1022f89230d9SMike Stump   // src->x
1023f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1024f89230d9SMike Stump   V = Builder.CreateLoad(V);
1025f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1026f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10279793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1028f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1029f89230d9SMike Stump 
1030f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1031f89230d9SMike Stump 
103241a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
103341a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1034f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1035f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1036f89230d9SMike Stump 
1037ee2a5ee5SMike Stump   CGF.FinishFunction();
1038ee2a5ee5SMike Stump 
1039ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1040ee2a5ee5SMike Stump }
1041ee2a5ee5SMike Stump 
1042fbe25dd1SMike Stump llvm::Constant *
1043fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1044fbe25dd1SMike Stump                                                   int flag) {
1045ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1046ee2a5ee5SMike Stump 
1047ee2a5ee5SMike Stump   FunctionArgList Args;
1048ee2a5ee5SMike Stump   // FIXME: This leaks
1049ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10507fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10517fe9cc1dSMike Stump                               SourceLocation(), 0,
1052ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1053ee2a5ee5SMike Stump 
1054ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1055ee2a5ee5SMike Stump 
1056ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1057ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
1058ee2a5ee5SMike Stump 
1059ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_dispose_");
1060ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1061ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1062ee2a5ee5SMike Stump 
1063cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1064cbc2bcafSMike Stump   // internal linkage.
1065ee2a5ee5SMike Stump   llvm::Function *Fn =
1066ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1067ee2a5ee5SMike Stump                            Name,
1068ee2a5ee5SMike Stump                            &CGM.getModule());
1069ee2a5ee5SMike Stump 
1070ee2a5ee5SMike Stump   IdentifierInfo *II
1071ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1072ee2a5ee5SMike Stump 
1073ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1074ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
107560ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1076ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1077ee2a5ee5SMike Stump                                           true);
1078ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1079fbe25dd1SMike Stump 
1080fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
10819793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10823b65ac26SMike Stump   V = Builder.CreateLoad(V);
1083fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10849793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
10853b65ac26SMike Stump   V = Builder.CreateLoad(V);
1086fbe25dd1SMike Stump 
1087fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1088fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1089ee2a5ee5SMike Stump   CGF.FinishFunction();
1090ee2a5ee5SMike Stump 
1091ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1092ee2a5ee5SMike Stump }
1093ee2a5ee5SMike Stump 
1094f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1095cbc2bcafSMike Stump                                                     int flag, unsigned Align) {
1096cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1097cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1098cbc2bcafSMike Stump   // with.
1099cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1100cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1101cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1102cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1103cbc2bcafSMike Stump   uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1104cbc2bcafSMike Stump   llvm::Constant *& Entry = CGM.AssignCache[kind];
1105cbc2bcafSMike Stump   if (Entry)
1106cbc2bcafSMike Stump     return Entry;
1107cbc2bcafSMike Stump   return Entry=CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
1108ee2a5ee5SMike Stump }
1109ee2a5ee5SMike Stump 
1110fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1111cbc2bcafSMike Stump                                                        int flag,
1112cbc2bcafSMike Stump                                                        unsigned Align) {
1113cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1114cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1115cbc2bcafSMike Stump   // with.
1116cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1117cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1118cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1119cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1120cbc2bcafSMike Stump   uint64_t kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + flag;
1121cbc2bcafSMike Stump   llvm::Constant *& Entry = CGM.DestroyCache[kind];
1122cbc2bcafSMike Stump   if (Entry)
1123cbc2bcafSMike Stump     return Entry;
1124cbc2bcafSMike Stump   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
1125ee2a5ee5SMike Stump }
1126ee2a5ee5SMike Stump 
1127626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1128626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1129626aecc4SMike Stump     const llvm::FunctionType *FTy;
1130626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
113141a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1132626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
113341a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11349793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1135626aecc4SMike Stump     CGM.BlockObjectDispose
1136626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1137626aecc4SMike Stump   }
1138626aecc4SMike Stump   return CGM.BlockObjectDispose;
1139626aecc4SMike Stump }
1140626aecc4SMike Stump 
1141f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1142f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1143f89230d9SMike Stump     const llvm::FunctionType *FTy;
1144f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
114541a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1146f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1147f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
114841a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11499793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1150f89230d9SMike Stump     CGM.BlockObjectAssign
1151f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1152f89230d9SMike Stump   }
1153f89230d9SMike Stump   return CGM.BlockObjectAssign;
1154f89230d9SMike Stump }
1155f89230d9SMike Stump 
1156fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1157626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1158fbe25dd1SMike Stump   llvm::Value *N;
1159626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
116041a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1161626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1162626aecc4SMike Stump }
11634446dcf0SMike Stump 
11644446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1165aeb0ffd5SMike Stump 
1166aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1167aeb0ffd5SMike Stump                              CGBuilderTy &B)
1168170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
116941a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
117041a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1171aeb0ffd5SMike Stump 
1172aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1173aeb0ffd5SMike Stump }
1174