12437cbfaSAnders Carlsson //===--- CGBlocks.cpp - Emit LLVM Code for declarations -------------------===//
22437cbfaSAnders Carlsson //
32437cbfaSAnders Carlsson //                     The LLVM Compiler Infrastructure
42437cbfaSAnders Carlsson //
52437cbfaSAnders Carlsson // This file is distributed under the University of Illinois Open Source
62437cbfaSAnders Carlsson // License. See LICENSE.TXT for details.
72437cbfaSAnders Carlsson //
82437cbfaSAnders Carlsson //===----------------------------------------------------------------------===//
92437cbfaSAnders Carlsson //
102437cbfaSAnders Carlsson // This contains code to emit blocks.
112437cbfaSAnders Carlsson //
122437cbfaSAnders Carlsson //===----------------------------------------------------------------------===//
132437cbfaSAnders Carlsson 
142437cbfaSAnders Carlsson #include "CodeGenFunction.h"
152437cbfaSAnders Carlsson #include "CodeGenModule.h"
16692c6e37SMike Stump #include "clang/AST/DeclObjC.h"
172437cbfaSAnders Carlsson #include "llvm/Module.h"
186a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
192437cbfaSAnders Carlsson 
202437cbfaSAnders Carlsson #include <algorithm>
212437cbfaSAnders Carlsson 
222437cbfaSAnders Carlsson using namespace clang;
232437cbfaSAnders Carlsson using namespace CodeGen;
242437cbfaSAnders Carlsson 
250874160bSMike Stump // Temporary code to enable testing of __block variables
260874160bSMike Stump // #include "clang/Frontend/CompileOptions.h"
270874160bSMike Stump #include "llvm/Support/CommandLine.h"
280874160bSMike Stump 
29d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
30d2142cffSMike Stump BuildDescriptorBlockDecl(bool BlockHasCopyDispose, uint64_t Size,
31d2142cffSMike Stump                          const llvm::StructType* Ty,
32aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
33c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
34c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
3585284bacSMike Stump   llvm::Constant *C;
3685284bacSMike Stump   std::vector<llvm::Constant*> Elts;
3785284bacSMike Stump 
3885284bacSMike Stump   // reserved
39c2c38331SMike Stump   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
4085284bacSMike Stump   Elts.push_back(C);
4185284bacSMike Stump 
4285284bacSMike Stump   // Size
432ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
442ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
452ac40a9fSMike Stump   // API to size_t.
46cb2fbcb0SMike Stump   C = llvm::ConstantInt::get(UnsignedLongTy, Size);
4785284bacSMike Stump   Elts.push_back(C);
4885284bacSMike Stump 
4985284bacSMike Stump   if (BlockHasCopyDispose) {
5085284bacSMike Stump     // copy_func_helper_decl
5167645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
5285284bacSMike Stump 
5385284bacSMike Stump     // destroy_func_decl
5467645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
5585284bacSMike Stump   }
5685284bacSMike Stump 
5785284bacSMike Stump   C = llvm::ConstantStruct::get(Elts);
5885284bacSMike Stump 
5985284bacSMike Stump   C = new llvm::GlobalVariable(C->getType(), true,
6085284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
61499ae7ecSMike Stump                                C, "__block_descriptor_tmp", &CGM.getModule());
6285284bacSMike Stump   return C;
6385284bacSMike Stump }
6485284bacSMike Stump 
6595435674SMike Stump llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
66971f9b66SMike Stump   if (NSConcreteGlobalBlock)
67971f9b66SMike Stump     return NSConcreteGlobalBlock;
68971f9b66SMike Stump 
6952d9c49dSMike Stump   // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
702d33d630SMike Stump   // same thing as CreateRuntimeFunction if there's already a variable with the
712d33d630SMike Stump   // same name.
72971f9b66SMike Stump   NSConcreteGlobalBlock
73971f9b66SMike Stump     = new llvm::GlobalVariable(PtrToInt8Ty, false,
74971f9b66SMike Stump                                llvm::GlobalValue::ExternalLinkage,
75971f9b66SMike Stump                                0, "_NSConcreteGlobalBlock",
76971f9b66SMike Stump                                &getModule());
77971f9b66SMike Stump 
78971f9b66SMike Stump   return NSConcreteGlobalBlock;
79971f9b66SMike Stump }
80971f9b66SMike Stump 
8195435674SMike Stump llvm::Constant *BlockModule::getNSConcreteStackBlock() {
827ab278dbSMike Stump   if (NSConcreteStackBlock)
837ab278dbSMike Stump     return NSConcreteStackBlock;
847ab278dbSMike Stump 
8552d9c49dSMike Stump   // FIXME: We should have a CodeGenModule::AddRuntimeVariable that does the
862d33d630SMike Stump   // same thing as CreateRuntimeFunction if there's already a variable with the
872d33d630SMike Stump   // same name.
887ab278dbSMike Stump   NSConcreteStackBlock
897ab278dbSMike Stump     = new llvm::GlobalVariable(PtrToInt8Ty, false,
907ab278dbSMike Stump                                llvm::GlobalValue::ExternalLinkage,
917ab278dbSMike Stump                                0, "_NSConcreteStackBlock",
927ab278dbSMike Stump                                &getModule());
937ab278dbSMike Stump 
947ab278dbSMike Stump   return NSConcreteStackBlock;
957ab278dbSMike Stump }
967ab278dbSMike Stump 
97ed5e69feSAnders Carlsson static void CollectBlockDeclRefInfo(const Stmt *S,
98ed5e69feSAnders Carlsson                                     CodeGenFunction::BlockInfo &Info) {
99ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
100ed5e69feSAnders Carlsson        I != E; ++I)
101dd942713SDaniel Dunbar     if (*I)
102ed5e69feSAnders Carlsson       CollectBlockDeclRefInfo(*I, Info);
103ed5e69feSAnders Carlsson 
104ed5e69feSAnders Carlsson   if (const BlockDeclRefExpr *DE = dyn_cast<BlockDeclRefExpr>(S)) {
105ed5e69feSAnders Carlsson     // FIXME: Handle enums.
106ed5e69feSAnders Carlsson     if (isa<FunctionDecl>(DE->getDecl()))
107ed5e69feSAnders Carlsson       return;
108ed5e69feSAnders Carlsson 
109ed5e69feSAnders Carlsson     if (DE->isByRef())
110ed5e69feSAnders Carlsson       Info.ByRefDeclRefs.push_back(DE);
111ed5e69feSAnders Carlsson     else
112ed5e69feSAnders Carlsson       Info.ByCopyDeclRefs.push_back(DE);
113ed5e69feSAnders Carlsson   }
114ed5e69feSAnders Carlsson }
115ed5e69feSAnders Carlsson 
1162d33d630SMike Stump /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
1172d33d630SMike Stump /// declared as a global variable instead of on the stack.
118ed5e69feSAnders Carlsson static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info)
119ed5e69feSAnders Carlsson {
120ed5e69feSAnders Carlsson   return Info.ByRefDeclRefs.empty() && Info.ByCopyDeclRefs.empty();
121ed5e69feSAnders Carlsson }
122ed5e69feSAnders Carlsson 
1232d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
1242d33d630SMike Stump // name.
125b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
126ed5e69feSAnders Carlsson 
127ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
128ed5e69feSAnders Carlsson   CodeGenFunction::BlockInfo Info(0, Name.c_str());
129ed5e69feSAnders Carlsson   CollectBlockDeclRefInfo(BE->getBody(), Info);
130ed5e69feSAnders Carlsson 
131ed5e69feSAnders Carlsson   // Check if the block can be global.
1322d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
1332d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
1342d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
13597d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
136ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
13785284bacSMike Stump 
1384446dcf0SMike Stump   std::vector<llvm::Constant*> Elts(5);
13985284bacSMike Stump   llvm::Constant *C;
140b750d928SMike Stump   llvm::Value *V;
14185284bacSMike Stump 
14285284bacSMike Stump   {
14385284bacSMike Stump     // C = BuildBlockStructInitlist();
14485284bacSMike Stump     unsigned int flags = BLOCK_HAS_DESCRIPTOR;
14585284bacSMike Stump 
1464446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1474446dcf0SMike Stump     // block literal.
1484446dcf0SMike Stump     // __invoke
1494446dcf0SMike Stump     uint64_t subBlockSize, subBlockAlign;
1504446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
151d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1524446dcf0SMike Stump     llvm::Function *Fn
153692c6e37SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl, LocalDeclMap,
1545469f29aSMike Stump                                                    subBlockSize,
1554446dcf0SMike Stump                                                    subBlockAlign,
1564446dcf0SMike Stump                                                    subBlockDeclRefDecls,
157d2142cffSMike Stump                                                    subBlockHasCopyDispose);
158d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1594446dcf0SMike Stump     Elts[3] = Fn;
1604446dcf0SMike Stump 
161d2142cffSMike Stump     if (subBlockHasCopyDispose)
16285284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
16385284bacSMike Stump 
164499ae7ecSMike Stump     // __isa
1657ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
16685284bacSMike Stump     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1674446dcf0SMike Stump     Elts[0] = C;
16885284bacSMike Stump 
16985284bacSMike Stump     // __flags
17085284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
17185284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
17285284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, flags);
1734446dcf0SMike Stump     Elts[1] = C;
17485284bacSMike Stump 
17585284bacSMike Stump     // __reserved
17685284bacSMike Stump     C = llvm::ConstantInt::get(IntTy, 0);
1774446dcf0SMike Stump     Elts[2] = C;
17885284bacSMike Stump 
179b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
180d6ef62f0SMike Stump       // __descriptor
181d2142cffSMike Stump       Elts[4] = BuildDescriptorBlockDecl(subBlockHasCopyDispose, subBlockSize, 0, 0);
182d6ef62f0SMike Stump 
1833a139f37SMike Stump       // Optimize to being a global block.
1843a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
1853a139f37SMike Stump       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
1863a139f37SMike Stump 
18785284bacSMike Stump       C = llvm::ConstantStruct::get(Elts);
18885284bacSMike Stump 
18985284bacSMike Stump       char Name[32];
1909319db8aSMike Stump       sprintf(Name, "__block_holder_tmp_%d", CGM.getGlobalUniqueCount());
19185284bacSMike Stump       C = new llvm::GlobalVariable(C->getType(), true,
19285284bacSMike Stump                                    llvm::GlobalValue::InternalLinkage,
19385284bacSMike Stump                                    C, Name, &CGM.getModule());
1945d2534adSMike Stump       QualType BPT = BE->getType();
1955d2534adSMike Stump       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
19685284bacSMike Stump       return C;
19785284bacSMike Stump     }
19885284bacSMike Stump 
199b750d928SMike Stump     std::vector<const llvm::Type *> Types(5+subBlockDeclRefDecls.size());
200aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
201b750d928SMike Stump       Types[i] = Elts[i]->getType();
202aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
20385284bacSMike Stump 
2041db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2051db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2061db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2071db7d04bSMike Stump       QualType Ty = E->getType();
20897d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
20997d01d50SMike Stump         uint64_t Align = getContext().getDeclAlignInBytes(BDRE->getDecl());
21097d01d50SMike Stump         Types[i+5] = llvm::PointerType::get(BuildByRefType(Ty, Align), 0);
21197d01d50SMike Stump       } else
2121db7d04bSMike Stump         Types[i+5] = ConvertType(Ty);
2131db7d04bSMike Stump     }
214b750d928SMike Stump 
215aeb0ffd5SMike Stump     llvm::StructType *Ty = llvm::StructType::get(Types, true);
216b750d928SMike Stump 
217b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
218b750d928SMike Stump     A->setAlignment(subBlockAlign);
219b750d928SMike Stump     V = A;
220b750d928SMike Stump 
221aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
222aeb0ffd5SMike Stump     int helpersize = 0;
223aeb0ffd5SMike Stump 
224aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
225b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
226b750d928SMike Stump 
227b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
228b750d928SMike Stump       {
2291db7d04bSMike Stump         // FIXME: Push const down.
2301db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2311db7d04bSMike Stump         DeclRefExpr *DR;
2321db7d04bSMike Stump         ValueDecl *VD;
233b750d928SMike Stump 
2341db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2351db7d04bSMike Stump         // Skip padding.
2361db7d04bSMike Stump         if (DR) continue;
2371db7d04bSMike Stump 
2381db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2391db7d04bSMike Stump         VD = BDRE->getDecl();
2401db7d04bSMike Stump 
24197d01d50SMike Stump         llvm::Value* Addr = Builder.CreateStructGEP(V, i+5, "tmp");
242aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
243aeb0ffd5SMike Stump         NoteForHelper[helpersize].RequiresCopying = BlockRequiresCopying(VD->getType());
244aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
245aeb0ffd5SMike Stump           = VD->getType()->isBlockPointerType() ? BLOCK_FIELD_IS_BLOCK : BLOCK_FIELD_IS_OBJECT;
246aeb0ffd5SMike Stump 
2471db7d04bSMike Stump         if (LocalDeclMap[VD]) {
24897d01d50SMike Stump           if (BDRE->isByRef()) {
249aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
25090d8daf5SMike Stump               // FIXME: Someone double check this.
25190d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
25297d01d50SMike Stump             const llvm::Type *Ty = Types[i+5];
25397d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
25497d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
25597d01d50SMike Stump             Loc = Builder.CreateLoad(Loc, false);
25697d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
25797d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
258aeb0ffd5SMike Stump             ++helpersize;
25997d01d50SMike Stump             continue;
26097d01d50SMike Stump           } else
2611db7d04bSMike Stump             E = new (getContext()) DeclRefExpr (cast<NamedDecl>(VD),
2621db7d04bSMike Stump                                                 VD->getType(), SourceLocation(),
2631db7d04bSMike Stump                                                 false, false);
2641db7d04bSMike Stump         }
26597d01d50SMike Stump         if (BDRE->isByRef()) {
266efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
267efd7caa8SMike Stump             // FIXME: Someone double check this.
268efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
2691db7d04bSMike Stump           E = new (getContext())
2701db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
2711db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
2721db7d04bSMike Stump                           SourceLocation());
27397d01d50SMike Stump         }
274aeb0ffd5SMike Stump         ++helpersize;
2751db7d04bSMike Stump 
2761db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
27797d01d50SMike Stump         if (r.isScalar()) {
27897d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
27997d01d50SMike Stump           const llvm::Type *Ty = Types[i+5];
28097d01d50SMike Stump           if  (BDRE->isByRef()) {
2812d33d630SMike Stump             // E is now the address of the value field, instead, we want the
2822d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
2832d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
2842d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
2852d33d630SMike Stump             // until then.
2862d33d630SMike Stump             uint64_t offset = BlockDecls[BDRE->getDecl()];
2872d33d630SMike Stump 
2882d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
2892d33d630SMike Stump 
2902d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
2912d33d630SMike Stump                                     llvm::ConstantInt::get(llvm::Type::Int64Ty,
2922d33d630SMike Stump                                                            offset),
2932d33d630SMike Stump                                     "block.literal");
2942d33d630SMike Stump             Ty = llvm::PointerType::get(Ty, 0);
29597d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
2962d33d630SMike Stump             Loc = Builder.CreateLoad(Loc, false);
2972d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
29897d01d50SMike Stump           }
29997d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
30097d01d50SMike Stump         } else if (r.isComplex())
301b750d928SMike Stump           // FIXME: implement
302b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
303b750d928SMike Stump         else if (r.isAggregate())
304b750d928SMike Stump           ; // Already created into the destination
305b750d928SMike Stump         else
306b750d928SMike Stump           assert (0 && "bad block variable");
307b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
308b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
309b750d928SMike Stump       }
310aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
311d6ef62f0SMike Stump 
312d6ef62f0SMike Stump     // __descriptor
313d2142cffSMike Stump     llvm::Value *Descriptor = BuildDescriptorBlockDecl(subBlockHasCopyDispose,
314d2142cffSMike Stump                                                        subBlockSize, Ty,
315aeb0ffd5SMike Stump                                                        &NoteForHelper);
316aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
317aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
318b750d928SMike Stump   }
319b750d928SMike Stump 
320b750d928SMike Stump   QualType BPT = BE->getType();
321b750d928SMike Stump   return Builder.CreateBitCast(V, ConvertType(BPT));
322b750d928SMike Stump }
32385284bacSMike Stump 
32485284bacSMike Stump 
32595435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
326650c932dSMike Stump   if (BlockDescriptorType)
327650c932dSMike Stump     return BlockDescriptorType;
3282437cbfaSAnders Carlsson 
3292437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
330650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3312437cbfaSAnders Carlsson 
3322437cbfaSAnders Carlsson   // struct __block_descriptor {
3332437cbfaSAnders Carlsson   //   unsigned long reserved;
3342437cbfaSAnders Carlsson   //   unsigned long block_size;
3352437cbfaSAnders Carlsson   // };
336650c932dSMike Stump   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy,
3372437cbfaSAnders Carlsson                                               UnsignedLongTy,
3382437cbfaSAnders Carlsson                                               NULL);
3392437cbfaSAnders Carlsson 
340650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
341650c932dSMike Stump                           BlockDescriptorType);
3422437cbfaSAnders Carlsson 
343650c932dSMike Stump   return BlockDescriptorType;
3442437cbfaSAnders Carlsson }
3452437cbfaSAnders Carlsson 
34695435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
347005c9a62SMike Stump   if (GenericBlockLiteralType)
348005c9a62SMike Stump     return GenericBlockLiteralType;
3492437cbfaSAnders Carlsson 
3502437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
351005c9a62SMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
3522437cbfaSAnders Carlsson 
35392bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
35492bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
35592bbd6d4SMike Stump 
3562437cbfaSAnders Carlsson   // struct __block_literal_generic {
3575d2534adSMike Stump   //   void *__isa;
3585d2534adSMike Stump   //   int __flags;
3595d2534adSMike Stump   //   int __reserved;
3605d2534adSMike Stump   //   void (*__invoke)(void *);
3615d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3622437cbfaSAnders Carlsson   // };
363626aecc4SMike Stump   GenericBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
36492bbd6d4SMike Stump                                                   IntTy,
36592bbd6d4SMike Stump                                                   IntTy,
366626aecc4SMike Stump                                                   PtrToInt8Ty,
3672437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
3682437cbfaSAnders Carlsson                                                   NULL);
3692437cbfaSAnders Carlsson 
370005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
371005c9a62SMike Stump                           GenericBlockLiteralType);
3722437cbfaSAnders Carlsson 
373005c9a62SMike Stump   return GenericBlockLiteralType;
3742437cbfaSAnders Carlsson }
3752437cbfaSAnders Carlsson 
37695435674SMike Stump const llvm::Type *BlockModule::getGenericExtendedBlockLiteralType() {
3775d2534adSMike Stump   if (GenericExtendedBlockLiteralType)
3785d2534adSMike Stump     return GenericExtendedBlockLiteralType;
3795d2534adSMike Stump 
3805d2534adSMike Stump   const llvm::Type *BlockDescPtrTy =
3815d2534adSMike Stump     llvm::PointerType::getUnqual(getBlockDescriptorType());
3825d2534adSMike Stump 
3835d2534adSMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
3845d2534adSMike Stump     getTypes().ConvertType(getContext().IntTy));
3855d2534adSMike Stump 
3865d2534adSMike Stump   // struct __block_literal_generic {
3875d2534adSMike Stump   //   void *__isa;
3885d2534adSMike Stump   //   int __flags;
3895d2534adSMike Stump   //   int __reserved;
3905d2534adSMike Stump   //   void (*__invoke)(void *);
3915d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
3925d2534adSMike Stump   //   void *__copy_func_helper_decl;
3935d2534adSMike Stump   //   void *__destroy_func_decl;
3945d2534adSMike Stump   // };
395626aecc4SMike Stump   GenericExtendedBlockLiteralType = llvm::StructType::get(PtrToInt8Ty,
3965d2534adSMike Stump                                                           IntTy,
3975d2534adSMike Stump                                                           IntTy,
398626aecc4SMike Stump                                                           PtrToInt8Ty,
3995d2534adSMike Stump                                                           BlockDescPtrTy,
400626aecc4SMike Stump                                                           PtrToInt8Ty,
401626aecc4SMike Stump                                                           PtrToInt8Ty,
4025d2534adSMike Stump                                                           NULL);
4035d2534adSMike Stump 
4045d2534adSMike Stump   getModule().addTypeName("struct.__block_literal_extended_generic",
4055d2534adSMike Stump                           GenericExtendedBlockLiteralType);
4065d2534adSMike Stump 
4075d2534adSMike Stump   return GenericExtendedBlockLiteralType;
4085d2534adSMike Stump }
4095d2534adSMike Stump 
4106a60fa24SAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E) {
4112437cbfaSAnders Carlsson   const BlockPointerType *BPT =
4122437cbfaSAnders Carlsson     E->getCallee()->getType()->getAsBlockPointerType();
4132437cbfaSAnders Carlsson 
4142437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4152437cbfaSAnders Carlsson 
4162437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4172437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
418005c9a62SMike Stump     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4192437cbfaSAnders Carlsson 
4202437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4212437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4222437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4232437cbfaSAnders Carlsson 
4242437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4252437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4262437cbfaSAnders Carlsson 
4272437cbfaSAnders Carlsson   BlockLiteral =
4282437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
4292437cbfaSAnders Carlsson                           llvm::PointerType::getUnqual(llvm::Type::Int8Ty),
4302437cbfaSAnders Carlsson                           "tmp");
4312437cbfaSAnders Carlsson 
4322437cbfaSAnders Carlsson   // Add the block literal.
4332437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4342437cbfaSAnders Carlsson   CallArgList Args;
4352437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4362437cbfaSAnders Carlsson 
437479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
438479e6fc7SAnders Carlsson 
4392437cbfaSAnders Carlsson   // And the rest of the arguments.
440479e6fc7SAnders Carlsson   EmitCallArgs(Args, FnType->getAsFunctionProtoType(),
441479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4422437cbfaSAnders Carlsson 
4435f50c651SAnders Carlsson   // Load the function.
4445f50c651SAnders Carlsson   llvm::Value *Func = Builder.CreateLoad(FuncPtr, false, "tmp");
4455f50c651SAnders Carlsson 
446a60cbcdfSAnders Carlsson   QualType ResultType = FnType->getAsFunctionType()->getResultType();
447a60cbcdfSAnders Carlsson 
448a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
449a60cbcdfSAnders Carlsson     CGM.getTypes().getFunctionInfo(ResultType, Args);
4505f50c651SAnders Carlsson 
4515f50c651SAnders Carlsson   // Cast the function pointer to the right type.
4525f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
453a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
4545f50c651SAnders Carlsson 
4555f50c651SAnders Carlsson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
4565f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4575f50c651SAnders Carlsson 
4582437cbfaSAnders Carlsson   // And call the block.
459350da607SAnders Carlsson   return EmitCall(FnInfo, Func, Args);
4602437cbfaSAnders Carlsson }
4616a60fa24SAnders Carlsson 
46297d01d50SMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
46397d01d50SMike Stump   uint64_t &offset = BlockDecls[E->getDecl()];
46497d01d50SMike Stump 
46597d01d50SMike Stump   const llvm::Type *Ty;
46697d01d50SMike Stump   Ty = CGM.getTypes().ConvertType(E->getDecl()->getType());
46797d01d50SMike Stump 
46897d01d50SMike Stump   // See if we have already allocated an offset for this variable.
46997d01d50SMike Stump   if (offset == 0) {
4704446dcf0SMike Stump     // Don't run the expensive check, unless we have to.
4714446dcf0SMike Stump     if (!BlockHasCopyDispose && BlockRequiresCopying(E->getType()))
4724446dcf0SMike Stump       BlockHasCopyDispose = true;
47397d01d50SMike Stump     // if not, allocate one now.
47497d01d50SMike Stump     offset = getBlockOffset(E);
47597d01d50SMike Stump   }
47697d01d50SMike Stump 
47797d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
47897d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
47997d01d50SMike Stump                                      llvm::ConstantInt::get(llvm::Type::Int64Ty,
48097d01d50SMike Stump                                                             offset),
4812d33d630SMike Stump                                      "block.literal");
48297d01d50SMike Stump   if (E->isByRef()) {
48397d01d50SMike Stump     bool needsCopyDispose = BlockRequiresCopying(E->getType());
48497d01d50SMike Stump     uint64_t Align = getContext().getDeclAlignInBytes(E->getDecl());
48597d01d50SMike Stump     const llvm::Type *PtrStructTy
48697d01d50SMike Stump       = llvm::PointerType::get(BuildByRefType(E->getType(), Align), 0);
487efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
488efd7caa8SMike Stump     BlockHasCopyDispose = true;
48997d01d50SMike Stump     Ty = PtrStructTy;
49097d01d50SMike Stump     Ty = llvm::PointerType::get(Ty, 0);
49197d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
49297d01d50SMike Stump     V = Builder.CreateLoad(V, false);
49397d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
49497d01d50SMike Stump     V = Builder.CreateLoad(V, false);
49597d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
49697d01d50SMike Stump     V = Builder.CreateStructGEP(V, needsCopyDispose*2 + 4, "x");
49797d01d50SMike Stump   } else {
49897d01d50SMike Stump     Ty = llvm::PointerType::get(Ty, 0);
49997d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
50097d01d50SMike Stump   }
50197d01d50SMike Stump   return V;
50297d01d50SMike Stump }
50397d01d50SMike Stump 
504692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
505692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
506692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
507692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
508692c6e37SMike Stump   if (DMEntry)
509692c6e37SMike Stump     return;
510692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
511692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
512692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
513692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
514692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
515692c6e37SMike Stump }
516692c6e37SMike Stump 
5172d5a2878SMike Stump llvm::Constant *
5186c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
5196a60fa24SAnders Carlsson   // Generate the block descriptor.
5206a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
52192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
52292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5236a60fa24SAnders Carlsson 
5246a60fa24SAnders Carlsson   llvm::Constant *DescriptorFields[2];
5256a60fa24SAnders Carlsson 
5266a60fa24SAnders Carlsson   // Reserved
5276a60fa24SAnders Carlsson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
5286a60fa24SAnders Carlsson 
5296a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5306a60fa24SAnders Carlsson   // block literal struct.
5316a60fa24SAnders Carlsson   uint64_t BlockLiteralSize =
532005c9a62SMike Stump     TheTargetData.getTypeStoreSizeInBits(getGenericBlockLiteralType()) / 8;
5336a60fa24SAnders Carlsson   DescriptorFields[1] = llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize);
5346a60fa24SAnders Carlsson 
5356a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
5366a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&DescriptorFields[0], 2);
5376a60fa24SAnders Carlsson 
5386a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
5396a60fa24SAnders Carlsson     new llvm::GlobalVariable(DescriptorStruct->getType(), true,
5406a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
5416a60fa24SAnders Carlsson                              DescriptorStruct, "__block_descriptor_global",
5426a60fa24SAnders Carlsson                              &getModule());
5436a60fa24SAnders Carlsson 
5446a60fa24SAnders Carlsson   // Generate the constants for the block literal.
5456a60fa24SAnders Carlsson   llvm::Constant *LiteralFields[5];
5466a60fa24SAnders Carlsson 
5472d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
548b750d928SMike Stump   uint64_t subBlockSize, subBlockAlign;
5491db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
550a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
5515469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
552cb2fbcb0SMike Stump   llvm::Function *Fn
553692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
5545469f29aSMike Stump                                                  subBlockSize,
555b750d928SMike Stump                                                  subBlockAlign,
5564446dcf0SMike Stump                                                  subBlockDeclRefDecls,
5574446dcf0SMike Stump                                                  subBlockHasCopyDispose);
558cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
559cb2fbcb0SMike Stump          && "no imports allowed for global block");
560a61bb4d1SDaniel Dunbar   assert(!subBlockHasCopyDispose && "no imports allowed for global block");
5616a60fa24SAnders Carlsson 
5626a60fa24SAnders Carlsson   // isa
563971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
5646a60fa24SAnders Carlsson 
5656a60fa24SAnders Carlsson   // Flags
5665878c797SAnders Carlsson   LiteralFields[1] =
5675878c797SAnders Carlsson     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_DESCRIPTOR);
5686a60fa24SAnders Carlsson 
5696a60fa24SAnders Carlsson   // Reserved
57092bbd6d4SMike Stump   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
5716a60fa24SAnders Carlsson 
5726a60fa24SAnders Carlsson   // Function
5736a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
5746a60fa24SAnders Carlsson 
5756a60fa24SAnders Carlsson   // Descriptor
5766a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
5776a60fa24SAnders Carlsson 
5786a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
5796a60fa24SAnders Carlsson     llvm::ConstantStruct::get(&LiteralFields[0], 5);
5806a60fa24SAnders Carlsson 
5816a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
5826a60fa24SAnders Carlsson     new llvm::GlobalVariable(BlockLiteralStruct->getType(), true,
5836a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
5846a60fa24SAnders Carlsson                              BlockLiteralStruct, "__block_literal_global",
5856a60fa24SAnders Carlsson                              &getModule());
5866a60fa24SAnders Carlsson 
5876a60fa24SAnders Carlsson   return BlockLiteral;
5886a60fa24SAnders Carlsson }
5896a60fa24SAnders Carlsson 
590cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
591cb2fbcb0SMike Stump   return Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], "self");
592cb2fbcb0SMike Stump }
593cb2fbcb0SMike Stump 
5944446dcf0SMike Stump llvm::Function *
5954446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
596cb2fbcb0SMike Stump                                        const BlockInfo& Info,
597692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
5985469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
599b750d928SMike Stump                                        uint64_t &Size,
600b750d928SMike Stump                                        uint64_t &Align,
6014446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
6024446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
6039074ed8cSDevang Patel 
6049074ed8cSDevang Patel   // Check if we should generate debug info for this block.
6059074ed8cSDevang Patel   if (CGM.getDebugInfo())
6069074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
6079074ed8cSDevang Patel 
6085469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
6095469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
6105469f29aSMike Stump   // in a block.
6115469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
6125469f29aSMike Stump        i != ldm.end();
6135469f29aSMike Stump        ++i) {
6145469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
6155469f29aSMike Stump 
6160ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
6175469f29aSMike Stump       LocalDeclMap[VD] = i->second;
6185469f29aSMike Stump   }
6195469f29aSMike Stump 
62009a9b6e3SEli Friedman   // FIXME: We need to rearrange the code for copy/dispose so we have this
62109a9b6e3SEli Friedman   // sooner, so we can calculate offsets correctly.
62209a9b6e3SEli Friedman   if (!BlockHasCopyDispose)
62309a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
62409a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
62509a9b6e3SEli Friedman   else
62609a9b6e3SEli Friedman     BlockOffset = CGM.getTargetData()
62709a9b6e3SEli Friedman       .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
62809a9b6e3SEli Friedman   BlockAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
62909a9b6e3SEli Friedman 
630aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
631aae4349dSFariborz Jahanian   QualType ResultType;
632aae4349dSFariborz Jahanian   bool IsVariadic;
633a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
634a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
635aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
636aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
637aae4349dSFariborz Jahanian   }
638aae4349dSFariborz Jahanian   else {
639aae4349dSFariborz Jahanian     // K&R style block.
640aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
641aae4349dSFariborz Jahanian     IsVariadic = false;
642aae4349dSFariborz Jahanian   }
6436a60fa24SAnders Carlsson 
6446a60fa24SAnders Carlsson   FunctionArgList Args;
6456a60fa24SAnders Carlsson 
6463385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
6476a60fa24SAnders Carlsson 
6486a60fa24SAnders Carlsson   // FIXME: This leaks
6496a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
6506a60fa24SAnders Carlsson     ImplicitParamDecl::Create(getContext(), 0,
6516a60fa24SAnders Carlsson                               SourceLocation(), 0,
6526a60fa24SAnders Carlsson                               getContext().getPointerType(getContext().VoidTy));
6536a60fa24SAnders Carlsson 
6546a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
655cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
6566a60fa24SAnders Carlsson 
657c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
6586a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
659eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
6606a60fa24SAnders Carlsson 
6616a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
662aae4349dSFariborz Jahanian     CGM.getTypes().getFunctionInfo(ResultType, Args);
6636a60fa24SAnders Carlsson 
6642d5a2878SMike Stump   std::string Name = std::string("__") + Info.Name + "_block_invoke_";
6656a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
666aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
6676a60fa24SAnders Carlsson 
6686a60fa24SAnders Carlsson   llvm::Function *Fn =
6696a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
6706a60fa24SAnders Carlsson                            Name,
6716a60fa24SAnders Carlsson                            &CGM.getModule());
6726a60fa24SAnders Carlsson 
673c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
674c3e7cff6SDaniel Dunbar 
675*324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
6763385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
677*324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
67828ec0cf8SChris Lattner   CurCodeDecl = BD;
6793385fe12SChris Lattner   EmitStmt(BExpr->getBody());
6803385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
6816a60fa24SAnders Carlsson 
682b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
683b750d928SMike Stump   uint64_t MinAlign = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
684b750d928SMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, MinAlign);
685b750d928SMike Stump 
686cb2fbcb0SMike Stump   Size = BlockOffset;
687b750d928SMike Stump   Align = BlockAlign;
688b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
6894446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
6906a60fa24SAnders Carlsson   return Fn;
6916a60fa24SAnders Carlsson }
6921db7d04bSMike Stump 
693aeb0ffd5SMike Stump uint64_t BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
6941db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
6951db7d04bSMike Stump 
6961db7d04bSMike Stump   uint64_t Size = getContext().getTypeSize(D->getType()) / 8;
6971db7d04bSMike Stump   uint64_t Align = getContext().getDeclAlignInBytes(D);
6981db7d04bSMike Stump 
6991db7d04bSMike Stump   if (BDRE->isByRef()) {
7001db7d04bSMike Stump     Size = getContext().getTypeSize(getContext().VoidPtrTy) / 8;
7011db7d04bSMike Stump     Align = getContext().getTypeAlign(getContext().VoidPtrTy) / 8;
7021db7d04bSMike Stump   }
7031db7d04bSMike Stump 
7041db7d04bSMike Stump   assert ((Align > 0) && "alignment must be 1 byte or more");
7051db7d04bSMike Stump 
7061db7d04bSMike Stump   uint64_t OldOffset = BlockOffset;
7071db7d04bSMike Stump 
7081db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
7091db7d04bSMike Stump   BlockOffset = llvm::RoundUpToAlignment(BlockOffset, Align);
7101db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
7111db7d04bSMike Stump 
7121db7d04bSMike Stump   uint64_t Pad = BlockOffset - OldOffset;
7131db7d04bSMike Stump   if (Pad) {
7141db7d04bSMike Stump     llvm::ArrayType::get(llvm::Type::Int8Ty, Pad);
7151db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
7161db7d04bSMike Stump                                                        llvm::APInt(32, Pad),
7171db7d04bSMike Stump                                                        ArrayType::Normal, 0);
7181db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
7191db7d04bSMike Stump                                          0, QualType(PadTy), VarDecl::None,
7201db7d04bSMike Stump                                          SourceLocation());
7211db7d04bSMike Stump     Expr *E;
7221db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
7231db7d04bSMike Stump                                        SourceLocation(), false, false);
7241db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
7251db7d04bSMike Stump   }
7261db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
7271db7d04bSMike Stump 
7281db7d04bSMike Stump   BlockOffset += Size;
7291db7d04bSMike Stump   return BlockOffset-Size;
7301db7d04bSMike Stump }
73197d01d50SMike Stump 
732aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
733aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
73467645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
7350c743277SMike Stump   QualType R = getContext().VoidTy;
7360c743277SMike Stump 
7370c743277SMike Stump   FunctionArgList Args;
7380c743277SMike Stump   // FIXME: This leaks
739aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
740aeb0ffd5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
741aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
742aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
7430c743277SMike Stump   ImplicitParamDecl *Src =
7440c743277SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
7450c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
7460c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
7470c743277SMike Stump 
7480c743277SMike Stump   const CGFunctionInfo &FI =
7490c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
7500c743277SMike Stump 
7510c743277SMike Stump   std::string Name = std::string("__copy_helper_block_");
7520c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
7530c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
7540c743277SMike Stump 
7550c743277SMike Stump   llvm::Function *Fn =
7560c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
7570c743277SMike Stump                            Name,
7580c743277SMike Stump                            &CGM.getModule());
7590c743277SMike Stump 
7600c743277SMike Stump   IdentifierInfo *II
7610c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
7620c743277SMike Stump 
7630c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
7640c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
7650c743277SMike Stump                                           SourceLocation(), II, R,
7660c743277SMike Stump                                           FunctionDecl::Static, false,
7670c743277SMike Stump                                           true);
7680c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
769aeb0ffd5SMike Stump 
770aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
771aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
77267645930SMike Stump 
77367645930SMike Stump   if (NoteForHelperp) {
77467645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
77567645930SMike Stump 
776aeb0ffd5SMike Stump     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
777aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
778aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
779aeb0ffd5SMike Stump 
780aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
7813b65ac26SMike Stump     llvm::Type *PtrPtrT;
7823b65ac26SMike Stump     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
7833b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
7843b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
785aeb0ffd5SMike Stump 
786aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
787aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
788aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
789aeb0ffd5SMike Stump 
790aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
791aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
792aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
793aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
794aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
795aeb0ffd5SMike Stump                                      llvm::PointerType::get(PtrToInt8Ty, 0));
796aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
797aeb0ffd5SMike Stump 
798aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
799aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
800aeb0ffd5SMike Stump 
801aeb0ffd5SMike Stump         llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
802aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
803aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
804aeb0ffd5SMike Stump       }
805aeb0ffd5SMike Stump     }
80667645930SMike Stump   }
807aeb0ffd5SMike Stump 
8080c743277SMike Stump   CGF.FinishFunction();
8090c743277SMike Stump 
8100c743277SMike Stump   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
81197d01d50SMike Stump }
81297d01d50SMike Stump 
813d6ef62f0SMike Stump llvm::Constant *BlockFunction::
814aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
815aeb0ffd5SMike Stump                               const llvm::StructType* T,
81667645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
8170c743277SMike Stump   QualType R = getContext().VoidTy;
8180c743277SMike Stump 
8190c743277SMike Stump   FunctionArgList Args;
8200c743277SMike Stump   // FIXME: This leaks
8210c743277SMike Stump   ImplicitParamDecl *Src =
8220c743277SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
8230c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8240c743277SMike Stump 
8250c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8260c743277SMike Stump 
8270c743277SMike Stump   const CGFunctionInfo &FI =
8280c743277SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
8290c743277SMike Stump 
8300c743277SMike Stump   std::string Name = std::string("__destroy_helper_block_");
8310c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8320c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8330c743277SMike Stump 
8340c743277SMike Stump   llvm::Function *Fn =
8350c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
8360c743277SMike Stump                            Name,
8370c743277SMike Stump                            &CGM.getModule());
8380c743277SMike Stump 
8390c743277SMike Stump   IdentifierInfo *II
8400c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
8410c743277SMike Stump 
8420c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8430c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
8440c743277SMike Stump                                           SourceLocation(), II, R,
8450c743277SMike Stump                                           FunctionDecl::Static, false,
8460c743277SMike Stump                                           true);
8470c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
8486f7d9f87SMike Stump 
84967645930SMike Stump   if (NoteForHelperp) {
85067645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
85167645930SMike Stump 
8526f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
8536f7d9f87SMike Stump     llvm::Type *PtrPtrT;
8546f7d9f87SMike Stump     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
8556f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
8566f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
8576f7d9f87SMike Stump 
8586f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
8596f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
8606f7d9f87SMike Stump       int index = NoteForHelper[i].index;
8616f7d9f87SMike Stump 
8626f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
8636f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
8646f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
8656f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
8666f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
8676f7d9f87SMike Stump                                      llvm::PointerType::get(PtrToInt8Ty, 0));
8686f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
8696f7d9f87SMike Stump 
8706f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
8716f7d9f87SMike Stump       }
8726f7d9f87SMike Stump     }
87367645930SMike Stump   }
8746f7d9f87SMike Stump 
8750c743277SMike Stump   CGF.FinishFunction();
8760c743277SMike Stump 
8770c743277SMike Stump   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
8780c743277SMike Stump }
8790c743277SMike Stump 
880aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
88167645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
882aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
883aeb0ffd5SMike Stump                                                          T, NoteForHelper);
8840c743277SMike Stump }
8850c743277SMike Stump 
886aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
88767645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
888aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
88967645930SMike Stump                                                             T, NoteForHelperp);
89097d01d50SMike Stump }
891626aecc4SMike Stump 
892f89230d9SMike Stump llvm::Constant *BlockFunction::
893f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
894ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
895ee2a5ee5SMike Stump 
896ee2a5ee5SMike Stump   FunctionArgList Args;
897ee2a5ee5SMike Stump   // FIXME: This leaks
898f89230d9SMike Stump   ImplicitParamDecl *Dst =
899f89230d9SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
900f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
901f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
902f89230d9SMike Stump 
903f89230d9SMike Stump   // FIXME: This leaks
904ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
905ee2a5ee5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
906ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
907ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
908ee2a5ee5SMike Stump 
909ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
910ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
911ee2a5ee5SMike Stump 
912ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_copy_");
913ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
914ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
915ee2a5ee5SMike Stump 
916ee2a5ee5SMike Stump   llvm::Function *Fn =
917ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
918ee2a5ee5SMike Stump                            Name,
919ee2a5ee5SMike Stump                            &CGM.getModule());
920ee2a5ee5SMike Stump 
921ee2a5ee5SMike Stump   IdentifierInfo *II
922ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
923ee2a5ee5SMike Stump 
924ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
925ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
926ee2a5ee5SMike Stump                                           SourceLocation(), II, R,
927ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
928ee2a5ee5SMike Stump                                           true);
929ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
930f89230d9SMike Stump 
931f89230d9SMike Stump   // dst->x
932f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
9333b65ac26SMike Stump   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
9343b65ac26SMike Stump   V = Builder.CreateLoad(V);
935f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
936f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
937f89230d9SMike Stump 
938f89230d9SMike Stump   // src->x
939f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
940f89230d9SMike Stump   V = Builder.CreateLoad(V);
941f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
942f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
943f89230d9SMike Stump   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
944f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
945f89230d9SMike Stump 
946f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
947f89230d9SMike Stump 
948f89230d9SMike Stump   llvm::Value *N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
949f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
950f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
951f89230d9SMike Stump 
952ee2a5ee5SMike Stump   CGF.FinishFunction();
953ee2a5ee5SMike Stump 
954ee2a5ee5SMike Stump   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
955ee2a5ee5SMike Stump }
956ee2a5ee5SMike Stump 
957fbe25dd1SMike Stump llvm::Constant *
958fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
959fbe25dd1SMike Stump                                                   int flag) {
960ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
961ee2a5ee5SMike Stump 
962ee2a5ee5SMike Stump   FunctionArgList Args;
963ee2a5ee5SMike Stump   // FIXME: This leaks
964ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
965ee2a5ee5SMike Stump     ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0,
966ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
967ee2a5ee5SMike Stump 
968ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
969ee2a5ee5SMike Stump 
970ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
971ee2a5ee5SMike Stump     CGM.getTypes().getFunctionInfo(R, Args);
972ee2a5ee5SMike Stump 
973ee2a5ee5SMike Stump   std::string Name = std::string("__Block_byref_id_object_dispose_");
974ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
975ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
976ee2a5ee5SMike Stump 
977ee2a5ee5SMike Stump   llvm::Function *Fn =
978ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
979ee2a5ee5SMike Stump                            Name,
980ee2a5ee5SMike Stump                            &CGM.getModule());
981ee2a5ee5SMike Stump 
982ee2a5ee5SMike Stump   IdentifierInfo *II
983ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
984ee2a5ee5SMike Stump 
985ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
986ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
987ee2a5ee5SMike Stump                                           SourceLocation(), II, R,
988ee2a5ee5SMike Stump                                           FunctionDecl::Static, false,
989ee2a5ee5SMike Stump                                           true);
990ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
991fbe25dd1SMike Stump 
992fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
9933b65ac26SMike Stump   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
9943b65ac26SMike Stump   V = Builder.CreateLoad(V);
995fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
9963b65ac26SMike Stump   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
9973b65ac26SMike Stump   V = Builder.CreateLoad(V);
998fbe25dd1SMike Stump 
999fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1000fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1001ee2a5ee5SMike Stump   CGF.FinishFunction();
1002ee2a5ee5SMike Stump 
1003ee2a5ee5SMike Stump   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1004ee2a5ee5SMike Stump }
1005ee2a5ee5SMike Stump 
1006f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1007f89230d9SMike Stump                                                     int flag) {
1008f89230d9SMike Stump   return CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, flag);
1009ee2a5ee5SMike Stump }
1010ee2a5ee5SMike Stump 
1011fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1012fbe25dd1SMike Stump                                                        int flag) {
1013fbe25dd1SMike Stump   return CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, flag);
1014ee2a5ee5SMike Stump }
1015ee2a5ee5SMike Stump 
1016626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1017626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1018626aecc4SMike Stump     const llvm::FunctionType *FTy;
1019626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
1020626aecc4SMike Stump     const llvm::Type *ResultType = llvm::Type::VoidTy;
1021626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1022626aecc4SMike Stump     ArgTys.push_back(llvm::Type::Int32Ty);
1023626aecc4SMike Stump     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1024626aecc4SMike Stump     CGM.BlockObjectDispose
1025626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1026626aecc4SMike Stump   }
1027626aecc4SMike Stump   return CGM.BlockObjectDispose;
1028626aecc4SMike Stump }
1029626aecc4SMike Stump 
1030f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1031f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1032f89230d9SMike Stump     const llvm::FunctionType *FTy;
1033f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
1034f89230d9SMike Stump     const llvm::Type *ResultType = llvm::Type::VoidTy;
1035f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1036f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1037f89230d9SMike Stump     ArgTys.push_back(llvm::Type::Int32Ty);
1038f89230d9SMike Stump     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1039f89230d9SMike Stump     CGM.BlockObjectAssign
1040f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1041f89230d9SMike Stump   }
1042f89230d9SMike Stump   return CGM.BlockObjectAssign;
1043f89230d9SMike Stump }
1044f89230d9SMike Stump 
1045fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1046626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1047fbe25dd1SMike Stump   llvm::Value *N;
1048626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
1049fbe25dd1SMike Stump   N = llvm::ConstantInt::get(llvm::Type::Int32Ty, flag);
1050626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1051626aecc4SMike Stump }
10524446dcf0SMike Stump 
10534446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1054aeb0ffd5SMike Stump 
1055aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1056aeb0ffd5SMike Stump                              CGBuilderTy &B)
1057aeb0ffd5SMike Stump   : CGM(cgm), CGF(cgf), Builder(B) {
1058aeb0ffd5SMike Stump   PtrToInt8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1059aeb0ffd5SMike Stump 
1060aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1061aeb0ffd5SMike Stump }
1062