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 
76066b6166SMike Stump static void CollectBlockDeclRefInfo(
77066b6166SMike Stump   const Stmt *S, CodeGenFunction::BlockInfo &Info,
78066b6166SMike 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)
82066b6166SMike 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.
86066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
87066b6166SMike Stump     InnerContexts.insert(cast<DeclContext>(BE->getBlockDecl()));
88066b6166SMike Stump     CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
89066b6166SMike Stump   }
907fe9cc1dSMike Stump 
91066b6166SMike Stump   if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
92ed5e69feSAnders Carlsson     // FIXME: Handle enums.
93066b6166SMike Stump     if (isa<FunctionDecl>(BDRE->getDecl()))
94ed5e69feSAnders Carlsson       return;
95ed5e69feSAnders Carlsson 
96066b6166SMike Stump     // Only Decls that escape are added.
97066b6166SMike Stump     if (!InnerContexts.count(BDRE->getDecl()->getDeclContext()))
98066b6166SMike 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());
138066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> InnerContexts;
139066b6166SMike Stump   InnerContexts.insert(BE->getBlockDecl());
140066b6166SMike 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 
149950a9518SDavid Chisnall   size_t BlockFields = 5;
150950a9518SDavid Chisnall 
151950a9518SDavid Chisnall   bool hasIntrospection  = CGM.getContext().getLangOptions().BlockIntrospection;
152950a9518SDavid Chisnall 
153950a9518SDavid Chisnall   if (hasIntrospection) {
154950a9518SDavid Chisnall     BlockFields++;
155950a9518SDavid Chisnall   }
156950a9518SDavid Chisnall   std::vector<llvm::Constant*> Elts(BlockFields);
157950a9518SDavid Chisnall 
158950a9518SDavid Chisnall   if (hasIntrospection) {
159950a9518SDavid Chisnall     std::string BlockTypeEncoding;
160950a9518SDavid Chisnall     CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
161950a9518SDavid Chisnall 
162950a9518SDavid Chisnall     Elts[5] = llvm::ConstantExpr::getBitCast(
163950a9518SDavid Chisnall             CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
164950a9518SDavid Chisnall   }
165950a9518SDavid Chisnall 
16685284bacSMike Stump   llvm::Constant *C;
167b750d928SMike Stump   llvm::Value *V;
16885284bacSMike Stump 
16985284bacSMike Stump   {
17085284bacSMike Stump     // C = BuildBlockStructInitlist();
17185284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
17285284bacSMike Stump 
173950a9518SDavid Chisnall     if (hasIntrospection)
174950a9518SDavid Chisnall       flags |= BLOCK_HAS_OBJC_TYPE;
175950a9518SDavid Chisnall 
1764446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1774446dcf0SMike Stump     // block literal.
1784446dcf0SMike Stump     // __invoke
1794446dcf0SMike Stump     uint64_t subBlockSize, subBlockAlign;
1804446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
181d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1824446dcf0SMike Stump     llvm::Function *Fn
183d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
184d2a3e617SMike Stump                                                    LocalDeclMap,
1855469f29aSMike Stump                                                    subBlockSize,
1864446dcf0SMike Stump                                                    subBlockAlign,
1874446dcf0SMike Stump                                                    subBlockDeclRefDecls,
188d2142cffSMike Stump                                                    subBlockHasCopyDispose);
189d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1904446dcf0SMike Stump     Elts[3] = Fn;
1914446dcf0SMike Stump 
19218bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
19318bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
194d2142cffSMike Stump     if (subBlockHasCopyDispose)
19585284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
19685284bacSMike Stump 
197499ae7ecSMike Stump     // __isa
1987ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
199ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
2004446dcf0SMike Stump     Elts[0] = C;
20185284bacSMike Stump 
20285284bacSMike Stump     // __flags
20385284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
20485284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
205b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
2064446dcf0SMike Stump     Elts[1] = C;
20785284bacSMike Stump 
20885284bacSMike Stump     // __reserved
209b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
2104446dcf0SMike Stump     Elts[2] = C;
21185284bacSMike Stump 
212b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
213d6ef62f0SMike Stump       // __descriptor
2147fe9cc1dSMike Stump       Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize,
2157fe9cc1dSMike Stump                                          0, 0);
216d6ef62f0SMike Stump 
2173a139f37SMike Stump       // Optimize to being a global block.
2183a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
219b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2203a139f37SMike Stump 
22141eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
22285284bacSMike Stump 
22385284bacSMike Stump       char Name[32];
2249319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
225c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
22685284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
227c10c8d3eSOwen Anderson                                    C, Name);
2285d2534adSMike Stump       QualType BPT = BE->getType();
229ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
23085284bacSMike Stump       return C;
23185284bacSMike Stump     }
23285284bacSMike Stump 
233950a9518SDavid Chisnall     std::vector<const llvm::Type *> Types(BlockFields+subBlockDeclRefDecls.size());
234aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
235b750d928SMike Stump       Types[i] = Elts[i]->getType();
236aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
237950a9518SDavid Chisnall     if (hasIntrospection)
238950a9518SDavid Chisnall       Types[5] = PtrToInt8Ty;
23985284bacSMike Stump 
2401db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2411db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2421db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2431db7d04bSMike Stump       QualType Ty = E->getType();
24497d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
245950a9518SDavid Chisnall         Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
24697d01d50SMike Stump       } else
247950a9518SDavid Chisnall         Types[i+BlockFields] = ConvertType(Ty);
2481db7d04bSMike Stump     }
249b750d928SMike Stump 
250758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
251b750d928SMike Stump 
252b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
253b750d928SMike Stump     A->setAlignment(subBlockAlign);
254b750d928SMike Stump     V = A;
255b750d928SMike Stump 
256aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
257aeb0ffd5SMike Stump     int helpersize = 0;
258aeb0ffd5SMike Stump 
259aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
260b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
261950a9518SDavid Chisnall     if (hasIntrospection)
262950a9518SDavid Chisnall       Builder.CreateStore(Elts[5], Builder.CreateStructGEP(V, 5, "block.tmp"));
263b750d928SMike Stump 
264b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
265b750d928SMike Stump       {
2661db7d04bSMike Stump         // FIXME: Push const down.
2671db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2681db7d04bSMike Stump         DeclRefExpr *DR;
2691db7d04bSMike Stump         ValueDecl *VD;
270b750d928SMike Stump 
2711db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2721db7d04bSMike Stump         // Skip padding.
2731db7d04bSMike Stump         if (DR) continue;
2741db7d04bSMike Stump 
2751db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2761db7d04bSMike Stump         VD = BDRE->getDecl();
2771db7d04bSMike Stump 
278950a9518SDavid Chisnall         llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
279aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
2802114d7c2SMike Stump         NoteForHelper[helpersize].RequiresCopying
2812114d7c2SMike Stump           = BlockRequiresCopying(VD->getType());
282aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
2832114d7c2SMike Stump           = (VD->getType()->isBlockPointerType()
2842114d7c2SMike Stump              ? BLOCK_FIELD_IS_BLOCK
2852114d7c2SMike Stump              : BLOCK_FIELD_IS_OBJECT);
286aeb0ffd5SMike Stump 
2871db7d04bSMike Stump         if (LocalDeclMap[VD]) {
28897d01d50SMike Stump           if (BDRE->isByRef()) {
289aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
29090d8daf5SMike Stump               // FIXME: Someone double check this.
29190d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
29297d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
29397d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
294c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
29597d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
296aeb0ffd5SMike Stump             ++helpersize;
29797d01d50SMike Stump             continue;
29897d01d50SMike Stump           } else
299*ce54657eSJohn McCall             E = new (getContext()) DeclRefExpr (VD,
300ed6c7440SDouglas Gregor                                                 VD->getType(),
301ed6c7440SDouglas Gregor                                                 SourceLocation());
3021db7d04bSMike Stump         }
30397d01d50SMike Stump         if (BDRE->isByRef()) {
304efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
305efd7caa8SMike Stump             // FIXME: Someone double check this.
306efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
3071db7d04bSMike Stump           E = new (getContext())
3081db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
3091db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
3101db7d04bSMike Stump                           SourceLocation());
31197d01d50SMike Stump         }
312aeb0ffd5SMike Stump         ++helpersize;
3131db7d04bSMike Stump 
3141db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
31597d01d50SMike Stump         if (r.isScalar()) {
31697d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
317950a9518SDavid Chisnall           const llvm::Type *Ty = Types[i+BlockFields];
31897d01d50SMike Stump           if  (BDRE->isByRef()) {
3192d33d630SMike Stump             // E is now the address of the value field, instead, we want the
3202d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
3212d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
3222d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
3232d33d630SMike Stump             // until then.
3242d33d630SMike Stump             uint64_t offset = BlockDecls[BDRE->getDecl()];
3252d33d630SMike Stump 
3262d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
3272d33d630SMike Stump 
3282d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
32941a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
3302d33d630SMike Stump                                                            offset),
3312d33d630SMike Stump                                     "block.literal");
3329793f0e4SOwen Anderson             Ty = llvm::PointerType::get(Ty, 0);
33397d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
334c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
3352d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
33697d01d50SMike Stump           }
33797d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
33897d01d50SMike Stump         } else if (r.isComplex())
339b750d928SMike Stump           // FIXME: implement
340b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
341b750d928SMike Stump         else if (r.isAggregate())
342b750d928SMike Stump           ; // Already created into the destination
343b750d928SMike Stump         else
344b750d928SMike Stump           assert (0 && "bad block variable");
345b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
346b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
347b750d928SMike Stump       }
348aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
349d6ef62f0SMike Stump 
350d6ef62f0SMike Stump     // __descriptor
351d2142cffSMike Stump     llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
352d2142cffSMike Stump                                                        subBlockSize, Ty,
353aeb0ffd5SMike Stump                                                        &NoteForHelper);
354aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
355aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
356b750d928SMike Stump   }
357b750d928SMike Stump 
358b750d928SMike Stump   QualType BPT = BE->getType();
359b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
360b750d928SMike Stump }
36185284bacSMike Stump 
36285284bacSMike Stump 
36395435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
364650c932dSMike Stump   if (BlockDescriptorType)
365650c932dSMike Stump     return BlockDescriptorType;
3662437cbfaSAnders Carlsson 
3672437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
368650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3692437cbfaSAnders Carlsson 
3702437cbfaSAnders Carlsson   // struct __block_descriptor {
3712437cbfaSAnders Carlsson   //   unsigned long reserved;
3722437cbfaSAnders Carlsson   //   unsigned long block_size;
3732437cbfaSAnders Carlsson   // };
374758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
375758428f4SOwen Anderson                                               UnsignedLongTy,
3762437cbfaSAnders Carlsson                                               UnsignedLongTy,
3772437cbfaSAnders Carlsson                                               NULL);
3782437cbfaSAnders Carlsson 
379650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
380650c932dSMike Stump                           BlockDescriptorType);
3812437cbfaSAnders Carlsson 
382650c932dSMike Stump   return BlockDescriptorType;
3832437cbfaSAnders Carlsson }
3842437cbfaSAnders Carlsson 
38595435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
386005c9a62SMike Stump   if (GenericBlockLiteralType)
387005c9a62SMike Stump     return GenericBlockLiteralType;
3882437cbfaSAnders Carlsson 
3892437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
3909793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
3912437cbfaSAnders Carlsson 
39292bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
39392bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
39492bbd6d4SMike Stump 
3952437cbfaSAnders Carlsson   // struct __block_literal_generic {
3965d2534adSMike Stump   //   void *__isa;
3975d2534adSMike Stump   //   int __flags;
3985d2534adSMike Stump   //   int __reserved;
3995d2534adSMike Stump   //   void (*__invoke)(void *);
4005d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
401950a9518SDavid Chisnall   //   // GNU runtime only:
402950a9518SDavid Chisnall   //   const char *types;
4032437cbfaSAnders Carlsson   // };
404950a9518SDavid Chisnall   if (CGM.getContext().getLangOptions().BlockIntrospection)
405950a9518SDavid Chisnall     GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
406950a9518SDavid Chisnall                                                   PtrToInt8Ty,
407950a9518SDavid Chisnall                                                   IntTy,
408950a9518SDavid Chisnall                                                   IntTy,
409950a9518SDavid Chisnall                                                   PtrToInt8Ty,
410950a9518SDavid Chisnall                                                   BlockDescPtrTy,
411950a9518SDavid Chisnall                                                   PtrToInt8Ty,
412950a9518SDavid Chisnall                                                   NULL);
413950a9518SDavid Chisnall   else
414758428f4SOwen Anderson     GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
415758428f4SOwen Anderson                                                   PtrToInt8Ty,
41692bbd6d4SMike Stump                                                   IntTy,
41792bbd6d4SMike Stump                                                   IntTy,
418626aecc4SMike Stump                                                   PtrToInt8Ty,
4192437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
4202437cbfaSAnders Carlsson                                                   NULL);
4212437cbfaSAnders Carlsson 
422005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
423005c9a62SMike Stump                           GenericBlockLiteralType);
4242437cbfaSAnders Carlsson 
425005c9a62SMike Stump   return GenericBlockLiteralType;
4262437cbfaSAnders Carlsson }
4272437cbfaSAnders Carlsson 
42895435674SMike Stump const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
4295d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
4305d2534adSMike Stump     return GenericExtendedBlockLiteralType;
4315d2534adSMike Stump 
4325d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
4339793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
4345d2534adSMike Stump 
4355d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
4365d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
4375d2534adSMike Stump 
4385d2534adSMike Stump   // struct __block_literal_generic {
4395d2534adSMike Stump   //   void *__isa;
4405d2534adSMike Stump   //   int __flags;
4415d2534adSMike Stump   //   int __reserved;
4425d2534adSMike Stump   //   void (*__invoke)(void *);
4435d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4445d2534adSMike Stump   //   void *__copy_func_helper_decl;
4455d2534adSMike Stump   //   void *__destroy_func_decl;
4465d2534adSMike Stump   // };
447758428f4SOwen Anderson   GenericExtendedBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
448758428f4SOwen Anderson                                                           PtrToInt8Ty,
4495d2534adSMike Stump                                                           IntTy,
4505d2534adSMike Stump                                                           IntTy,
451626aecc4SMike Stump                                                           PtrToInt8Ty,
4525d2534adSMike Stump                                                           BlockDescPtrTy,
453626aecc4SMike Stump                                                           PtrToInt8Ty,
454626aecc4SMike Stump                                                           PtrToInt8Ty,
4555d2534adSMike Stump                                                           NULL);
4565d2534adSMike Stump 
4575d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
4585d2534adSMike Stump                           GenericExtendedBlockLiteralType);
4595d2534adSMike Stump 
4605d2534adSMike Stump   return GenericExtendedBlockLiteralType;
4615d2534adSMike Stump }
4625d2534adSMike Stump 
4636a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
4642437cbfaSAnders Carlsson   const BlockPointerType *BPT =
465c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
4662437cbfaSAnders Carlsson 
4672437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4682437cbfaSAnders Carlsson 
4692437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4702437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
4719793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4722437cbfaSAnders Carlsson 
4732437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4742437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4752437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4762437cbfaSAnders Carlsson 
4772437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4782437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4792437cbfaSAnders Carlsson 
4802437cbfaSAnders Carlsson   BlockLiteral =
4812437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
482abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
4832437cbfaSAnders Carlsson                           "tmp");
4842437cbfaSAnders Carlsson 
4852437cbfaSAnders Carlsson   // Add the block literal.
4862437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4872437cbfaSAnders Carlsson   CallArgList Args;
4882437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4892437cbfaSAnders Carlsson 
490479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
491479e6fc7SAnders Carlsson 
4922437cbfaSAnders Carlsson   // And the rest of the arguments.
4939dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
494479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4952437cbfaSAnders Carlsson 
4965f50c651SAnders Carlsson   // Load the function.
497c76493a6SDaniel Dunbar   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
4985f50c651SAnders Carlsson 
4999dd450bbSJohn McCall   QualType ResultType = FnType->getAs<FunctionType>()->getResultType();
500a60cbcdfSAnders Carlsson 
501a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
502a60cbcdfSAnders Carlsson     CGM.getTypes().getFunctionInfo(ResultType, Args);
5035f50c651SAnders Carlsson 
5045f50c651SAnders Carlsson   // Cast the function pointer to the right type.
5055f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
506a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
5075f50c651SAnders Carlsson 
5089793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
5095f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
5105f50c651SAnders Carlsson 
5112437cbfaSAnders Carlsson   // And call the block.
512350da607SAnders Carlsson   return EmitCall(FnInfo, Func, Args);
5132437cbfaSAnders Carlsson }
5146a60fa24SAnders Carlsson 
5157fe9cc1dSMike Stump uint64_t CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
5160168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
5170168f4b2SAnders Carlsson   uint64_t &offset = BlockDecls[VD];
5180168f4b2SAnders Carlsson 
51997d01d50SMike Stump   // See if we have already allocated an offset for this variable.
5207fe9cc1dSMike Stump   if (offset)
5217fe9cc1dSMike Stump     return offset;
5227fe9cc1dSMike Stump 
5234446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
524e1b19ba0SMike Stump   if (!BlockHasCopyDispose)
525e1b19ba0SMike Stump     if (E->isByRef()
526e1b19ba0SMike Stump         || BlockRequiresCopying(E->getType()))
5274446dcf0SMike Stump       BlockHasCopyDispose = true;
5287fe9cc1dSMike Stump 
52997d01d50SMike Stump   // if not, allocate one now.
53097d01d50SMike Stump   offset = getBlockOffset(E);
5317fe9cc1dSMike Stump 
5327fe9cc1dSMike Stump   return offset;
53397d01d50SMike Stump }
53497d01d50SMike Stump 
5357fe9cc1dSMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
5367fe9cc1dSMike Stump   const ValueDecl *VD = E->getDecl();
5377fe9cc1dSMike Stump   uint64_t offset = AllocateBlockDecl(E);
5387fe9cc1dSMike Stump 
5397fe9cc1dSMike Stump 
54097d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
54197d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
54241a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
54397d01d50SMike Stump                                                          offset),
5442d33d630SMike Stump                                      "block.literal");
54597d01d50SMike Stump   if (E->isByRef()) {
54697d01d50SMike Stump     const llvm::Type *PtrStructTy
5470168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
548efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
549efd7caa8SMike Stump     BlockHasCopyDispose = true;
5500168f4b2SAnders Carlsson 
5510168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
5529793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
55397d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
554c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
55597d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
556c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
55797d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
5580168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
5590168f4b2SAnders Carlsson                                 VD->getNameAsString());
56097d01d50SMike Stump   } else {
5610168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
5620168f4b2SAnders Carlsson 
5639793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
56497d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
56597d01d50SMike Stump   }
56697d01d50SMike Stump   return V;
56797d01d50SMike Stump }
56897d01d50SMike Stump 
569692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
570692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
571692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
572692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
573692c6e37SMike Stump   if (DMEntry)
574692c6e37SMike Stump     return;
575692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
576692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
577692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
578692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
579692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
580692c6e37SMike Stump }
581692c6e37SMike Stump 
5822d5a2878SMike Stump llvm::Constant *
5836c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
5846a60fa24SAnders Carlsson   // Generate the block descriptor.
5856a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
58692bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
58792bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5886a60fa24SAnders Carlsson 
5896a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
5906a60fa24SAnders Carlsson 
5916a60fa24SAnders Carlsson   // Reserved
5920b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
5936a60fa24SAnders Carlsson 
5946a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5956a60fa24SAnders Carlsson   // block literal struct.
5966a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
597005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
598170229f6SOwen Anderson   DescriptorFields[1] =
599b7a2fe6fSOwen Anderson                       llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
6006a60fa24SAnders Carlsson 
6016a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
60241eaf0acSNick Lewycky     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 2, false);
6036a60fa24SAnders Carlsson 
6046a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
605c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
6066a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
607c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
6086a60fa24SAnders Carlsson 
609950a9518SDavid Chisnall   int FieldCount = 5;
6106a60fa24SAnders Carlsson   // Generate the constants for the block literal.
611950a9518SDavid Chisnall   if (CGM.getContext().getLangOptions().BlockIntrospection)
612950a9518SDavid Chisnall     FieldCount = 6;
613950a9518SDavid Chisnall 
614950a9518SDavid Chisnall   std::vector<llvm::Constant*> LiteralFields(FieldCount);
6156a60fa24SAnders Carlsson 
6162d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
617b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
6181db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
619a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
6205469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
621cb2fbcb0SMike Stump   llvm::Function *Fn
622692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
6235469f29aSMike Stump                                                  subBlockSize,
624b750d928SMike Stump                                                  subBlockAlign,
6254446dcf0SMike Stump                                                  subBlockDeclRefDecls,
6264446dcf0SMike Stump                                                  subBlockHasCopyDispose);
627cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
628cb2fbcb0SMike Stump          && "no imports allowed for global block");
6296a60fa24SAnders Carlsson 
6306a60fa24SAnders Carlsson   // isa
631971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
6326a60fa24SAnders Carlsson 
6336a60fa24SAnders Carlsson   // Flags
634950a9518SDavid Chisnall   LiteralFields[1] = CGM.getContext().getLangOptions().BlockIntrospection ?
635950a9518SDavid Chisnall     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR |
636950a9518SDavid Chisnall             BLOCK_HAS_OBJC_TYPE) :
637b7a2fe6fSOwen Anderson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
6386a60fa24SAnders Carlsson 
6396a60fa24SAnders Carlsson   // Reserved
6400b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
6416a60fa24SAnders Carlsson 
6426a60fa24SAnders Carlsson   // Function
6436a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
6446a60fa24SAnders Carlsson 
6456a60fa24SAnders Carlsson   // Descriptor
6466a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
6476a60fa24SAnders Carlsson 
648950a9518SDavid Chisnall   // Type encoding
649950a9518SDavid Chisnall   if (CGM.getContext().getLangOptions().BlockIntrospection) {
650950a9518SDavid Chisnall     std::string BlockTypeEncoding;
651950a9518SDavid Chisnall     CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
652950a9518SDavid Chisnall 
653950a9518SDavid Chisnall     LiteralFields[5] = CGM.GetAddrOfConstantCString(BlockTypeEncoding);
654950a9518SDavid Chisnall   }
655950a9518SDavid Chisnall 
6566a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
657950a9518SDavid Chisnall     llvm::ConstantStruct::get(VMContext, LiteralFields, false);
6586a60fa24SAnders Carlsson 
6596a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
660c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
6616a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
662c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
6636a60fa24SAnders Carlsson 
6646a60fa24SAnders Carlsson   return BlockLiteral;
6656a60fa24SAnders Carlsson }
6666a60fa24SAnders Carlsson 
667cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
66838382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
66938382028SMike Stump                                       "self");
67038382028SMike Stump   // For now, we codegen based upon byte offsets.
67138382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
672cb2fbcb0SMike Stump }
673cb2fbcb0SMike Stump 
6744446dcf0SMike Stump llvm::Function *
6754446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
676cb2fbcb0SMike Stump                                        const BlockInfo& Info,
677692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
6785469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
679b750d928SMike Stump                                        uint64_t &Size,
680b750d928SMike Stump                                        uint64_t &Align,
6814446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
6824446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
6839074ed8cSDevang Patel 
6849074ed8cSDevang Patel   // Check if we should generate debug info for this block.
6859074ed8cSDevang Patel   if (CGM.getDebugInfo())
6869074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
6879074ed8cSDevang Patel 
6885469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
6895469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
6905469f29aSMike Stump   // in a block.
6915469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
6925469f29aSMike Stump        i != ldm.end();
6935469f29aSMike Stump        ++i) {
6945469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
6955469f29aSMike Stump 
6960ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
6975469f29aSMike Stump       LocalDeclMap[VD] = i->second;
6985469f29aSMike Stump   }
6995469f29aSMike Stump 
70009a9b6e3SEli Friedman   BlockOffset = CGM.getTargetData()
70109a9b6e3SEli Friedman     .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
70209a9b6e3SEli Friedman   BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
70309a9b6e3SEli Friedman 
704aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
705aae4349dSFariborz Jahanian   QualType ResultType;
706aae4349dSFariborz Jahanian   bool IsVariadic;
707a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
708a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
709aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
710aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
711658fe02dSMike Stump   } else {
712aae4349dSFariborz Jahanian     // K&R style block.
713aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
714aae4349dSFariborz Jahanian     IsVariadic = false;
715aae4349dSFariborz Jahanian   }
7166a60fa24SAnders Carlsson 
7176a60fa24SAnders Carlsson   FunctionArgList Args;
7186a60fa24SAnders Carlsson 
7197fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
7207fe9cc1dSMike Stump 
7213385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
7226a60fa24SAnders Carlsson 
7237fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
724d015328fSMike Stump 
725945fec05SMike Stump   // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
7267fe9cc1dSMike Stump   AllocateAllBlockDeclRefs(Info, this);
7277fe9cc1dSMike Stump 
728e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
729e1b19ba0SMike Stump                                                   BlockDeclRefDecls);
7306a60fa24SAnders Carlsson   // FIXME: This leaks
7316a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
7326a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
733d015328fSMike Stump                               SourceLocation(), II,
734d015328fSMike Stump                               ParmTy);
7356a60fa24SAnders Carlsson 
7366a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
737cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
7386a60fa24SAnders Carlsson 
739c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
7406a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
741eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
7426a60fa24SAnders Carlsson 
7436a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
744aae4349dSFariborz Jahanian     CGM.getTypes().getFunctionInfo(ResultType, Args);
7456a60fa24SAnders Carlsson 
7462d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
7476a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
748aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
7496a60fa24SAnders Carlsson 
7506a60fa24SAnders Carlsson   llvm::Function *Fn =
7516a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
7526a60fa24SAnders Carlsson                            Name,
7536a60fa24SAnders Carlsson                            &CGM.getModule());
7546a60fa24SAnders Carlsson 
755c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
756c3e7cff6SDaniel Dunbar 
757324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
7583385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
7592e722b91SMike Stump 
760324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
76128ec0cf8SChris Lattner   CurCodeDecl = BD;
762017460abSMike Stump 
763017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
764017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
765017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
766017460abSMike Stump   --entry_ptr;
767017460abSMike Stump 
7683385fe12SChris Lattner   EmitStmt(BExpr->getBody());
769017460abSMike Stump 
7707d69911aSMike Stump   // Remember where we were...
7717d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
772017460abSMike Stump 
7737d69911aSMike Stump   // Go back to the entry.
774017460abSMike Stump   ++entry_ptr;
775017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
776017460abSMike Stump 
7772e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
7782e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
7792e722b91SMike Stump     for (unsigned i=0; i < BlockDeclRefDecls.size(); ++i) {
7802e722b91SMike Stump       const Expr *E = BlockDeclRefDecls[i];
7812e722b91SMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
7822e722b91SMike Stump       if (BDRE) {
7832e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
7842e722b91SMike Stump         DI->setLocation(D->getLocation());
7852e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
7862e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
7872e722b91SMike Stump                                               Builder, this);
7882e722b91SMike Stump       }
7892e722b91SMike Stump     }
7902e722b91SMike Stump   }
7917d69911aSMike Stump   // And resume where we left off.
7927d69911aSMike Stump   if (resume == 0)
7937d69911aSMike Stump     Builder.ClearInsertionPoint();
7947d69911aSMike Stump   else
7957d69911aSMike Stump     Builder.SetInsertPoint(resume);
7962e722b91SMike Stump 
7973385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
7986a60fa24SAnders Carlsson 
799b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
800b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
801b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
802b750d928SMike Stump 
803cb2fbcb0SMike Stump   Size = BlockOffset;
804b750d928SMike Stump   Align = BlockAlign;
805b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
8064446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
8076a60fa24SAnders Carlsson   return Fn;
8086a60fa24SAnders Carlsson }
8091db7d04bSMike Stump 
810aeb0ffd5SMike Stump uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
8111db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
8121db7d04bSMike Stump 
8131db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
8141db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
8151db7d04bSMike Stump 
8161db7d04bSMike Stump   if (BDRE->isByRef()) {
8171db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
8181db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
8191db7d04bSMike Stump   }
8201db7d04bSMike Stump 
8211db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
8221db7d04bSMike Stump 
8231db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
8241db7d04bSMike Stump 
8251db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
8261db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
8271db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
8281db7d04bSMike Stump 
8291db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
8301db7d04bSMike Stump   if (Pad) {
83141a75027SOwen Anderson     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad);
8321db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
8331db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
8341db7d04bSMike Stump                                                        ArrayType::Normal, 0);
8351db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
8366032ef1aSArgyrios Kyrtzidis                                          0, QualType(PadTy), 0, VarDecl::None);
8371db7d04bSMike Stump     Expr *E;
8381db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
839ed6c7440SDouglas Gregor                                        SourceLocation());
8401db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
8411db7d04bSMike Stump   }
8421db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
8431db7d04bSMike Stump 
8441db7d04bSMike Stump   BlockOffset += Size;
8451db7d04bSMike Stump   return BlockOffset-Size;
8461db7d04bSMike Stump }
84797d01d50SMike Stump 
848aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
849aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
85067645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
8510c743277SMike Stump   QualType R = getContext().VoidTy;
8520c743277SMike Stump 
8530c743277SMike Stump   FunctionArgList Args;
8540c743277SMike Stump   // FIXME: This leaks
855aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
8567fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8577fe9cc1dSMike Stump                               SourceLocation(), 0,
858aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
859aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
8600c743277SMike Stump   ImplicitParamDecl *Src =
8617fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8627fe9cc1dSMike Stump                               SourceLocation(), 0,
8630c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8640c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8650c743277SMike Stump 
8660c743277SMike Stump   const CGFunctionInfo &FI =
8670c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
8680c743277SMike Stump 
869cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
870cbc2bcafSMike Stump   // internal linkage.
8710c743277SMike Stump   std::string Name = std::string("__copy_helper_block_");
8720c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8730c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8740c743277SMike Stump 
8750c743277SMike Stump   llvm::Function *Fn =
8760c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
8770c743277SMike Stump                            Name,
8780c743277SMike Stump                            &CGM.getModule());
8790c743277SMike Stump 
8800c743277SMike Stump   IdentifierInfo *II
8810c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
8820c743277SMike Stump 
8830c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8840c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
88560ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
8860c743277SMike Stump                                           FunctionDecl::Static, false,
8870c743277SMike Stump                                           true);
8880c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
889aeb0ffd5SMike Stump 
890aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
891aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
89267645930SMike Stump 
89367645930SMike Stump   if (NoteForHelperp) {
89467645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
89567645930SMike Stump 
8969793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
897aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
898aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
899aeb0ffd5SMike Stump 
900aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
9013b65ac26SMike Stump     llvm::Type *PtrPtrT;
9029793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9033b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
9043b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
905aeb0ffd5SMike Stump 
906aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
907aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
908aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
909aeb0ffd5SMike Stump 
910aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
911aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
912aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
913aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
914aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9159793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
916aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
917aeb0ffd5SMike Stump 
918aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
919aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
920aeb0ffd5SMike Stump 
92141a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
92241a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
923aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
924aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
925aeb0ffd5SMike Stump       }
926aeb0ffd5SMike Stump     }
92767645930SMike Stump   }
928aeb0ffd5SMike Stump 
9290c743277SMike Stump   CGF.FinishFunction();
9300c743277SMike Stump 
931ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
93297d01d50SMike Stump }
93397d01d50SMike Stump 
934d6ef62f0SMike Stump llvm::Constant *BlockFunction::
935aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
936aeb0ffd5SMike Stump                               const llvm::StructType* T,
93767645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
9380c743277SMike Stump   QualType R = getContext().VoidTy;
9390c743277SMike Stump 
9400c743277SMike Stump   FunctionArgList Args;
9410c743277SMike Stump   // FIXME: This leaks
9420c743277SMike Stump   ImplicitParamDecl *Src =
9437fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9447fe9cc1dSMike Stump                               SourceLocation(), 0,
9450c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9460c743277SMike Stump 
9470c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9480c743277SMike Stump 
9490c743277SMike Stump   const CGFunctionInfo &FI =
9500c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
9510c743277SMike Stump 
952cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
953cbc2bcafSMike Stump   // internal linkage.
9540c743277SMike Stump   std::string Name = std::string("__destroy_helper_block_");
9550c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9560c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9570c743277SMike Stump 
9580c743277SMike Stump   llvm::Function *Fn =
9590c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
9600c743277SMike Stump                            Name,
9610c743277SMike Stump                            &CGM.getModule());
9620c743277SMike Stump 
9630c743277SMike Stump   IdentifierInfo *II
9640c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
9650c743277SMike Stump 
9660c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9670c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
96860ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
9690c743277SMike Stump                                           FunctionDecl::Static, false,
9700c743277SMike Stump                                           true);
9710c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
9726f7d9f87SMike Stump 
97367645930SMike Stump   if (NoteForHelperp) {
97467645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
97567645930SMike Stump 
9766f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
9776f7d9f87SMike Stump     llvm::Type *PtrPtrT;
9789793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9796f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
9806f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
9816f7d9f87SMike Stump 
9826f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
9836f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
9846f7d9f87SMike Stump       int index = NoteForHelper[i].index;
9856f7d9f87SMike Stump 
9866f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
9876f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
9886f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
9896f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
9906f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9919793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
9926f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
9936f7d9f87SMike Stump 
9946f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
9956f7d9f87SMike Stump       }
9966f7d9f87SMike Stump     }
99767645930SMike Stump   }
9986f7d9f87SMike Stump 
9990c743277SMike Stump   CGF.FinishFunction();
10000c743277SMike Stump 
1001ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
10020c743277SMike Stump }
10030c743277SMike Stump 
1004aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
100567645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
1006aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1007aeb0ffd5SMike Stump                                                          T, NoteForHelper);
10080c743277SMike Stump }
10090c743277SMike Stump 
1010aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
101167645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
1012aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
101367645930SMike Stump                                                             T, NoteForHelperp);
101497d01d50SMike Stump }
1015626aecc4SMike Stump 
1016f89230d9SMike Stump llvm::Constant *BlockFunction::
1017f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
1018ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1019ee2a5ee5SMike Stump 
1020ee2a5ee5SMike Stump   FunctionArgList Args;
1021ee2a5ee5SMike Stump   // FIXME: This leaks
1022f89230d9SMike Stump   ImplicitParamDecl *Dst =
10237fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10247fe9cc1dSMike Stump                               SourceLocation(), 0,
1025f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1026f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
1027f89230d9SMike Stump 
1028f89230d9SMike Stump   // FIXME: This leaks
1029ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10307fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10317fe9cc1dSMike Stump                               SourceLocation(), 0,
1032ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1033ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1034ee2a5ee5SMike Stump 
1035ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1036ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
1037ee2a5ee5SMike Stump 
1038ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_copy_");
1039ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1040ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1041ee2a5ee5SMike Stump 
1042cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1043cbc2bcafSMike Stump   // internal linkage.
1044ee2a5ee5SMike Stump   llvm::Function *Fn =
1045ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1046ee2a5ee5SMike Stump                            Name,
1047ee2a5ee5SMike Stump                            &CGM.getModule());
1048ee2a5ee5SMike Stump 
1049ee2a5ee5SMike Stump   IdentifierInfo *II
1050ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1051ee2a5ee5SMike Stump 
1052ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1053ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
105460ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1055ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1056ee2a5ee5SMike Stump                                           true);
1057ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1058f89230d9SMike Stump 
1059f89230d9SMike Stump   // dst->x
1060f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
10619793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10623b65ac26SMike Stump   V = Builder.CreateLoad(V);
1063f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1064f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1065f89230d9SMike Stump 
1066f89230d9SMike Stump   // src->x
1067f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1068f89230d9SMike Stump   V = Builder.CreateLoad(V);
1069f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1070f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10719793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1072f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1073f89230d9SMike Stump 
1074f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1075f89230d9SMike Stump 
107641a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
107741a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1078f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1079f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1080f89230d9SMike Stump 
1081ee2a5ee5SMike Stump   CGF.FinishFunction();
1082ee2a5ee5SMike Stump 
1083ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1084ee2a5ee5SMike Stump }
1085ee2a5ee5SMike Stump 
1086fbe25dd1SMike Stump llvm::Constant *
1087fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1088fbe25dd1SMike Stump                                                   int flag) {
1089ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1090ee2a5ee5SMike Stump 
1091ee2a5ee5SMike Stump   FunctionArgList Args;
1092ee2a5ee5SMike Stump   // FIXME: This leaks
1093ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10947fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10957fe9cc1dSMike Stump                               SourceLocation(), 0,
1096ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1097ee2a5ee5SMike Stump 
1098ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1099ee2a5ee5SMike Stump 
1100ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1101ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
1102ee2a5ee5SMike Stump 
1103ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_dispose_");
1104ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1105ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1106ee2a5ee5SMike Stump 
1107cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1108cbc2bcafSMike Stump   // internal linkage.
1109ee2a5ee5SMike Stump   llvm::Function *Fn =
1110ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1111ee2a5ee5SMike Stump                            Name,
1112ee2a5ee5SMike Stump                            &CGM.getModule());
1113ee2a5ee5SMike Stump 
1114ee2a5ee5SMike Stump   IdentifierInfo *II
1115ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1116ee2a5ee5SMike Stump 
1117ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1118ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
111960ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1120ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
1121ee2a5ee5SMike Stump                                           true);
1122ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1123fbe25dd1SMike Stump 
1124fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
11259793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
11263b65ac26SMike Stump   V = Builder.CreateLoad(V);
1127fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
11289793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
11293b65ac26SMike Stump   V = Builder.CreateLoad(V);
1130fbe25dd1SMike Stump 
1131fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1132fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1133ee2a5ee5SMike Stump   CGF.FinishFunction();
1134ee2a5ee5SMike Stump 
1135ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1136ee2a5ee5SMike Stump }
1137ee2a5ee5SMike Stump 
1138f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1139e08ea787SChris Lattner                                                     int Flag, unsigned Align) {
1140e08ea787SChris Lattner   // All alignments below that of pointer alignment collapse down to just
1141cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1142cbc2bcafSMike Stump   // with.
1143cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1144e08ea787SChris Lattner 
1145cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1146cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1147cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1148e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1149e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1150cbc2bcafSMike Stump   if (Entry)
1151cbc2bcafSMike Stump     return Entry;
1152e08ea787SChris Lattner   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1153ee2a5ee5SMike Stump }
1154ee2a5ee5SMike Stump 
1155fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1156e08ea787SChris Lattner                                                        int Flag,
1157cbc2bcafSMike Stump                                                        unsigned Align) {
1158cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1159cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1160cbc2bcafSMike Stump   // with.
1161cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1162e08ea787SChris Lattner 
1163cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1164cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1165cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1166e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1167e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1168cbc2bcafSMike Stump   if (Entry)
1169cbc2bcafSMike Stump     return Entry;
1170e08ea787SChris Lattner   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1171ee2a5ee5SMike Stump }
1172ee2a5ee5SMike Stump 
1173626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1174626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1175626aecc4SMike Stump     const llvm::FunctionType *FTy;
1176626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
117741a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1178626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
117941a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11809793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1181626aecc4SMike Stump     CGM.BlockObjectDispose
1182626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1183626aecc4SMike Stump   }
1184626aecc4SMike Stump   return CGM.BlockObjectDispose;
1185626aecc4SMike Stump }
1186626aecc4SMike Stump 
1187f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1188f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1189f89230d9SMike Stump     const llvm::FunctionType *FTy;
1190f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
119141a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1192f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1193f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
119441a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11959793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1196f89230d9SMike Stump     CGM.BlockObjectAssign
1197f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1198f89230d9SMike Stump   }
1199f89230d9SMike Stump   return CGM.BlockObjectAssign;
1200f89230d9SMike Stump }
1201f89230d9SMike Stump 
1202fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1203626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1204fbe25dd1SMike Stump   llvm::Value *N;
1205626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
120641a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1207626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1208626aecc4SMike Stump }
12094446dcf0SMike Stump 
12104446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1211aeb0ffd5SMike Stump 
1212aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1213aeb0ffd5SMike Stump                              CGBuilderTy &B)
1214170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
121541a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
121641a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1217aeb0ffd5SMike Stump 
1218aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1219aeb0ffd5SMike Stump }
1220