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"
16989908fbSFariborz Jahanian #include "CGObjCRuntime.h"
172437cbfaSAnders Carlsson #include "CodeGenModule.h"
18692c6e37SMike Stump #include "clang/AST/DeclObjC.h"
192437cbfaSAnders Carlsson #include "llvm/Module.h"
209e2e1c90SBenjamin Kramer #include "llvm/ADT/SmallSet.h"
216a60fa24SAnders Carlsson #include "llvm/Target/TargetData.h"
222437cbfaSAnders Carlsson #include <algorithm>
23db714924STorok Edwin 
242437cbfaSAnders Carlsson using namespace clang;
252437cbfaSAnders Carlsson using namespace CodeGen;
262437cbfaSAnders Carlsson 
27d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
28fc83aa04SBlaine Garst BuildDescriptorBlockDecl(const BlockExpr *BE, bool BlockHasCopyDispose, CharUnits Size,
29d2142cffSMike Stump                          const llvm::StructType* Ty,
30aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
31c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
32c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
3385284bacSMike Stump   llvm::Constant *C;
3485284bacSMike Stump   std::vector<llvm::Constant*> Elts;
3585284bacSMike Stump 
3685284bacSMike Stump   // reserved
37b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
3885284bacSMike Stump   Elts.push_back(C);
3985284bacSMike Stump 
4085284bacSMike Stump   // Size
412ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
422ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
432ac40a9fSMike Stump   // API to size_t.
4440775003SKen Dyck   C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
4585284bacSMike Stump   Elts.push_back(C);
4685284bacSMike Stump 
47fc83aa04SBlaine Garst   // optional copy/dispose helpers
4885284bacSMike Stump   if (BlockHasCopyDispose) {
4985284bacSMike Stump     // copy_func_helper_decl
5067645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
5185284bacSMike Stump 
5285284bacSMike Stump     // destroy_func_decl
5367645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
5485284bacSMike Stump   }
5585284bacSMike Stump 
56fc83aa04SBlaine Garst   // Signature.  non-optional ObjC-style method descriptor @encode sequence
57fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
58fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
59fc83aa04SBlaine Garst 
60fc83aa04SBlaine Garst   Elts.push_back(llvm::ConstantExpr::getBitCast(
61fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty));
62fc83aa04SBlaine Garst 
63fc83aa04SBlaine Garst   // Layout.
64fc83aa04SBlaine Garst   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
65fc83aa04SBlaine Garst   Elts.push_back(C);
66fc83aa04SBlaine Garst 
6741eaf0acSNick Lewycky   C = llvm::ConstantStruct::get(VMContext, Elts, false);
6885284bacSMike Stump 
69c10c8d3eSOwen Anderson   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
7085284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
71c10c8d3eSOwen Anderson                                C, "__block_descriptor_tmp");
7285284bacSMike Stump   return C;
7385284bacSMike Stump }
7485284bacSMike Stump 
7595435674SMike Stump llvm::Constant *BlockModule::getNSConcreteGlobalBlock() {
7646813bbfSChris Lattner   if (NSConcreteGlobalBlock == 0)
7746813bbfSChris Lattner     NSConcreteGlobalBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
7846813bbfSChris Lattner                                                       "_NSConcreteGlobalBlock");
79971f9b66SMike Stump   return NSConcreteGlobalBlock;
80971f9b66SMike Stump }
81971f9b66SMike Stump 
8295435674SMike Stump llvm::Constant *BlockModule::getNSConcreteStackBlock() {
8346813bbfSChris Lattner   if (NSConcreteStackBlock == 0)
8446813bbfSChris Lattner     NSConcreteStackBlock = CGM.CreateRuntimeVariable(PtrToInt8Ty,
8546813bbfSChris Lattner                                                      "_NSConcreteStackBlock");
867ab278dbSMike Stump   return NSConcreteStackBlock;
877ab278dbSMike Stump }
887ab278dbSMike Stump 
89066b6166SMike Stump static void CollectBlockDeclRefInfo(
90066b6166SMike Stump   const Stmt *S, CodeGenFunction::BlockInfo &Info,
91066b6166SMike Stump   llvm::SmallSet<const DeclContext *, 16> &InnerContexts) {
92ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
93ed5e69feSAnders Carlsson        I != E; ++I)
94dd942713SDaniel Dunbar     if (*I)
95066b6166SMike Stump       CollectBlockDeclRefInfo(*I, Info, InnerContexts);
96ed5e69feSAnders Carlsson 
977fe9cc1dSMike Stump   // We want to ensure we walk down into block literals so we can find
987fe9cc1dSMike Stump   // all nested BlockDeclRefExprs.
99066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
100066b6166SMike Stump     InnerContexts.insert(cast<DeclContext>(BE->getBlockDecl()));
101066b6166SMike Stump     CollectBlockDeclRefInfo(BE->getBody(), Info, InnerContexts);
102066b6166SMike Stump   }
1037fe9cc1dSMike Stump 
104066b6166SMike Stump   if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
105ed5e69feSAnders Carlsson     // FIXME: Handle enums.
106066b6166SMike Stump     if (isa<FunctionDecl>(BDRE->getDecl()))
107ed5e69feSAnders Carlsson       return;
108ed5e69feSAnders Carlsson 
109066b6166SMike Stump     // Only Decls that escape are added.
110066b6166SMike Stump     if (!InnerContexts.count(BDRE->getDecl()->getDeclContext()))
111066b6166SMike Stump       Info.DeclRefs.push_back(BDRE);
112ed5e69feSAnders Carlsson   }
113ed5e69feSAnders Carlsson }
114ed5e69feSAnders Carlsson 
1152d33d630SMike Stump /// CanBlockBeGlobal - Given a BlockInfo struct, determines if a block can be
1162d33d630SMike Stump /// declared as a global variable instead of on the stack.
11746813bbfSChris Lattner static bool CanBlockBeGlobal(const CodeGenFunction::BlockInfo &Info) {
1187fe9cc1dSMike Stump   return Info.DeclRefs.empty();
1197fe9cc1dSMike Stump }
1207fe9cc1dSMike Stump 
1217fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
1227fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block
1237fe9cc1dSMike Stump /// invoke function.
1247fe9cc1dSMike Stump static void AllocateAllBlockDeclRefs(const CodeGenFunction::BlockInfo &Info,
1257fe9cc1dSMike Stump                                      CodeGenFunction *CGF) {
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   std::vector<llvm::Constant*> Elts(BlockFields);
152950a9518SDavid Chisnall 
15385284bacSMike Stump   llvm::Constant *C;
154b750d928SMike Stump   llvm::Value *V;
15585284bacSMike Stump 
15685284bacSMike Stump   {
15785284bacSMike Stump     // C = BuildBlockStructInitlist();
158f27ab71dSBlaine Garst     unsigned int flags = BLOCK_HAS_SIGNATURE;
159950a9518SDavid Chisnall 
1604446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
1614446dcf0SMike Stump     // block literal.
1624446dcf0SMike Stump     // __invoke
16340775003SKen Dyck     CharUnits subBlockSize;
1645262b119SKen Dyck     CharUnits subBlockAlign;
1654446dcf0SMike Stump     llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
166d2142cffSMike Stump     bool subBlockHasCopyDispose = false;
1674446dcf0SMike Stump     llvm::Function *Fn
168d2a3e617SMike Stump       = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, CurFuncDecl,
169d2a3e617SMike Stump                                                    LocalDeclMap,
1705469f29aSMike Stump                                                    subBlockSize,
1714446dcf0SMike Stump                                                    subBlockAlign,
1724446dcf0SMike Stump                                                    subBlockDeclRefDecls,
173d2142cffSMike Stump                                                    subBlockHasCopyDispose);
174d2142cffSMike Stump     BlockHasCopyDispose |= subBlockHasCopyDispose;
1754446dcf0SMike Stump     Elts[3] = Fn;
1764446dcf0SMike Stump 
17718bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
17818bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
179d2142cffSMike Stump     if (subBlockHasCopyDispose)
18085284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
18185284bacSMike Stump 
182499ae7ecSMike Stump     // __isa
1837ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
184ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
1854446dcf0SMike Stump     Elts[0] = C;
18685284bacSMike Stump 
18785284bacSMike Stump     // __flags
188f27ab71dSBlaine Garst     {
189f27ab71dSBlaine Garst       QualType BPT = BE->getType();
190f27ab71dSBlaine Garst       const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
191f27ab71dSBlaine Garst       QualType ResultType = ftype->getResultType();
192f27ab71dSBlaine Garst 
193f27ab71dSBlaine Garst       CallArgList Args;
194f27ab71dSBlaine Garst       CodeGenTypes &Types = CGM.getTypes();
195f27ab71dSBlaine Garst       const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
196c50c27ccSRafael Espindola                                                        FunctionType::ExtInfo());
197f27ab71dSBlaine Garst       if (CGM.ReturnTypeUsesSret(FnInfo))
198f27ab71dSBlaine Garst         flags |= BLOCK_USE_STRET;
199f27ab71dSBlaine Garst     }
20085284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
20185284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
202b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
2034446dcf0SMike Stump     Elts[1] = C;
20485284bacSMike Stump 
20585284bacSMike Stump     // __reserved
206b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
2074446dcf0SMike Stump     Elts[2] = C;
20885284bacSMike Stump 
209b750d928SMike Stump     if (subBlockDeclRefDecls.size() == 0) {
210d6ef62f0SMike Stump       // __descriptor
211fc83aa04SBlaine Garst       Elts[4] = BuildDescriptorBlockDecl(BE, subBlockHasCopyDispose, subBlockSize,
2127fe9cc1dSMike Stump                                          0, 0);
213d6ef62f0SMike Stump 
2143a139f37SMike Stump       // Optimize to being a global block.
2153a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
216f27ab71dSBlaine Garst 
217b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2183a139f37SMike Stump 
21941eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
22085284bacSMike Stump 
221c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
222d6b28fc6SBenjamin Kramer                                    llvm::GlobalValue::InternalLinkage, C,
223d6b28fc6SBenjamin Kramer                                    "__block_holder_tmp_" +
224d6b28fc6SBenjamin Kramer                                    llvm::Twine(CGM.getGlobalUniqueCount()));
2255d2534adSMike Stump       QualType BPT = BE->getType();
226ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
22785284bacSMike Stump       return C;
22885284bacSMike Stump     }
22985284bacSMike Stump 
230950a9518SDavid Chisnall     std::vector<const llvm::Type *> Types(BlockFields+subBlockDeclRefDecls.size());
231aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
232b750d928SMike Stump       Types[i] = Elts[i]->getType();
233aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
23485284bacSMike Stump 
2351db7d04bSMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i) {
2361db7d04bSMike Stump       const Expr *E = subBlockDeclRefDecls[i];
2371db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2381db7d04bSMike Stump       QualType Ty = E->getType();
23997d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
240950a9518SDavid Chisnall         Types[i+BlockFields] = llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
24197d01d50SMike Stump       } else
242950a9518SDavid Chisnall         Types[i+BlockFields] = ConvertType(Ty);
2431db7d04bSMike Stump     }
244b750d928SMike Stump 
245758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
246b750d928SMike Stump 
247b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
2485262b119SKen Dyck     A->setAlignment(subBlockAlign.getQuantity());
249b750d928SMike Stump     V = A;
250b750d928SMike Stump 
251aeb0ffd5SMike Stump     std::vector<HelperInfo> NoteForHelper(subBlockDeclRefDecls.size());
252aeb0ffd5SMike Stump     int helpersize = 0;
253aeb0ffd5SMike Stump 
254aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
255b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
256b750d928SMike Stump 
257b750d928SMike Stump     for (unsigned i=0; i < subBlockDeclRefDecls.size(); ++i)
258b750d928SMike Stump       {
2591db7d04bSMike Stump         // FIXME: Push const down.
2601db7d04bSMike Stump         Expr *E = const_cast<Expr*>(subBlockDeclRefDecls[i]);
2611db7d04bSMike Stump         DeclRefExpr *DR;
2621db7d04bSMike Stump         ValueDecl *VD;
263b750d928SMike Stump 
2641db7d04bSMike Stump         DR = dyn_cast<DeclRefExpr>(E);
2651db7d04bSMike Stump         // Skip padding.
2661db7d04bSMike Stump         if (DR) continue;
2671db7d04bSMike Stump 
2681db7d04bSMike Stump         BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2691db7d04bSMike Stump         VD = BDRE->getDecl();
2701db7d04bSMike Stump 
271950a9518SDavid Chisnall         llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
272aeb0ffd5SMike Stump         NoteForHelper[helpersize].index = i+5;
2732114d7c2SMike Stump         NoteForHelper[helpersize].RequiresCopying
2742114d7c2SMike Stump           = BlockRequiresCopying(VD->getType());
275aeb0ffd5SMike Stump         NoteForHelper[helpersize].flag
2762114d7c2SMike Stump           = (VD->getType()->isBlockPointerType()
2772114d7c2SMike Stump              ? BLOCK_FIELD_IS_BLOCK
2782114d7c2SMike Stump              : BLOCK_FIELD_IS_OBJECT);
279aeb0ffd5SMike Stump 
2801db7d04bSMike Stump         if (LocalDeclMap[VD]) {
28197d01d50SMike Stump           if (BDRE->isByRef()) {
282aeb0ffd5SMike Stump             NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
28390d8daf5SMike Stump               // FIXME: Someone double check this.
28490d8daf5SMike Stump               (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
28597d01d50SMike Stump             llvm::Value *Loc = LocalDeclMap[VD];
28697d01d50SMike Stump             Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
287c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
28897d01d50SMike Stump             Builder.CreateStore(Loc, Addr);
289aeb0ffd5SMike Stump             ++helpersize;
29097d01d50SMike Stump             continue;
29197d01d50SMike Stump           } else
292ce54657eSJohn McCall             E = new (getContext()) DeclRefExpr (VD,
293ed6c7440SDouglas Gregor                                                 VD->getType(),
294ed6c7440SDouglas Gregor                                                 SourceLocation());
2951db7d04bSMike Stump         }
29697d01d50SMike Stump         if (BDRE->isByRef()) {
297efd7caa8SMike Stump           NoteForHelper[helpersize].flag = BLOCK_FIELD_IS_BYREF |
298efd7caa8SMike Stump             // FIXME: Someone double check this.
299efd7caa8SMike Stump             (VD->getType().isObjCGCWeak() ? BLOCK_FIELD_IS_WEAK : 0);
3001db7d04bSMike Stump           E = new (getContext())
3011db7d04bSMike Stump             UnaryOperator(E, UnaryOperator::AddrOf,
3021db7d04bSMike Stump                           getContext().getPointerType(E->getType()),
3031db7d04bSMike Stump                           SourceLocation());
30497d01d50SMike Stump         }
305aeb0ffd5SMike Stump         ++helpersize;
3061db7d04bSMike Stump 
3071db7d04bSMike Stump         RValue r = EmitAnyExpr(E, Addr, false);
30897d01d50SMike Stump         if (r.isScalar()) {
30997d01d50SMike Stump           llvm::Value *Loc = r.getScalarVal();
310950a9518SDavid Chisnall           const llvm::Type *Ty = Types[i+BlockFields];
31197d01d50SMike Stump           if  (BDRE->isByRef()) {
3122d33d630SMike Stump             // E is now the address of the value field, instead, we want the
3132d33d630SMike Stump             // address of the actual ByRef struct.  We optimize this slightly
3142d33d630SMike Stump             // compared to gcc by not grabbing the forwarding slot as this must
3152d33d630SMike Stump             // be done during Block_copy for us, and we can postpone the work
3162d33d630SMike Stump             // until then.
31740775003SKen Dyck             CharUnits offset = BlockDecls[BDRE->getDecl()];
3182d33d630SMike Stump 
3192d33d630SMike Stump             llvm::Value *BlockLiteral = LoadBlockStruct();
3202d33d630SMike Stump 
3212d33d630SMike Stump             Loc = Builder.CreateGEP(BlockLiteral,
32241a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
32340775003SKen Dyck                                                            offset.getQuantity()),
3242d33d630SMike Stump                                     "block.literal");
3259793f0e4SOwen Anderson             Ty = llvm::PointerType::get(Ty, 0);
32697d01d50SMike Stump             Loc = Builder.CreateBitCast(Loc, Ty);
327c76493a6SDaniel Dunbar             Loc = Builder.CreateLoad(Loc);
3282d33d630SMike Stump             // Loc = Builder.CreateBitCast(Loc, Ty);
32997d01d50SMike Stump           }
33097d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
33197d01d50SMike Stump         } else if (r.isComplex())
332b750d928SMike Stump           // FIXME: implement
333b750d928SMike Stump           ErrorUnsupported(BE, "complex in block literal");
334b750d928SMike Stump         else if (r.isAggregate())
335b750d928SMike Stump           ; // Already created into the destination
336b750d928SMike Stump         else
337b750d928SMike Stump           assert (0 && "bad block variable");
338b750d928SMike Stump         // FIXME: Ensure that the offset created by the backend for
339b750d928SMike Stump         // the struct matches the previously computed offset in BlockDecls.
340b750d928SMike Stump       }
341aeb0ffd5SMike Stump     NoteForHelper.resize(helpersize);
342d6ef62f0SMike Stump 
343d6ef62f0SMike Stump     // __descriptor
344fc83aa04SBlaine Garst     llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE,
345fc83aa04SBlaine Garst                                                        subBlockHasCopyDispose,
346d2142cffSMike Stump                                                        subBlockSize, Ty,
347aeb0ffd5SMike Stump                                                        &NoteForHelper);
348aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
349aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
350b750d928SMike Stump   }
351b750d928SMike Stump 
352b750d928SMike Stump   QualType BPT = BE->getType();
353989908fbSFariborz Jahanian   V = Builder.CreateBitCast(V, ConvertType(BPT));
354989908fbSFariborz Jahanian   // See if this is a __weak block variable and the must call objc_read_weak
355989908fbSFariborz Jahanian   // on it.
356989908fbSFariborz Jahanian   const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
357989908fbSFariborz Jahanian   QualType RES = ftype->getResultType();
358989908fbSFariborz Jahanian   if (RES.isObjCGCWeak()) {
359989908fbSFariborz Jahanian     // Must cast argument to id*
360989908fbSFariborz Jahanian     const llvm::Type *ObjectPtrTy =
361989908fbSFariborz Jahanian       ConvertType(CGM.getContext().getObjCIdType());
362989908fbSFariborz Jahanian     const llvm::Type *PtrObjectPtrTy =
363989908fbSFariborz Jahanian       llvm::PointerType::getUnqual(ObjectPtrTy);
364989908fbSFariborz Jahanian     V = Builder.CreateBitCast(V, PtrObjectPtrTy);
365989908fbSFariborz Jahanian     V =  CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
366989908fbSFariborz Jahanian   }
367989908fbSFariborz Jahanian   return V;
368b750d928SMike Stump }
36985284bacSMike Stump 
37085284bacSMike Stump 
37195435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
372650c932dSMike Stump   if (BlockDescriptorType)
373650c932dSMike Stump     return BlockDescriptorType;
3742437cbfaSAnders Carlsson 
3752437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
376650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
3772437cbfaSAnders Carlsson 
3782437cbfaSAnders Carlsson   // struct __block_descriptor {
3792437cbfaSAnders Carlsson   //   unsigned long reserved;
3802437cbfaSAnders Carlsson   //   unsigned long block_size;
381fc83aa04SBlaine Garst   //
382fc83aa04SBlaine Garst   //   // later, the following will be added
383fc83aa04SBlaine Garst   //
384fc83aa04SBlaine Garst   //   struct {
385fc83aa04SBlaine Garst   //     void (*copyHelper)();
386fc83aa04SBlaine Garst   //     void (*copyHelper)();
387fc83aa04SBlaine Garst   //   } helpers;                // !!! optional
388fc83aa04SBlaine Garst   //
389fc83aa04SBlaine Garst   //   const char *signature;   // the block signature
390fc83aa04SBlaine Garst   //   const char *layout;      // reserved
3912437cbfaSAnders Carlsson   // };
392758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
393758428f4SOwen Anderson                                               UnsignedLongTy,
3942437cbfaSAnders Carlsson                                               UnsignedLongTy,
3952437cbfaSAnders Carlsson                                               NULL);
3962437cbfaSAnders Carlsson 
397650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
398650c932dSMike Stump                           BlockDescriptorType);
3992437cbfaSAnders Carlsson 
400650c932dSMike Stump   return BlockDescriptorType;
4012437cbfaSAnders Carlsson }
4022437cbfaSAnders Carlsson 
40395435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
404005c9a62SMike Stump   if (GenericBlockLiteralType)
405005c9a62SMike Stump     return GenericBlockLiteralType;
4062437cbfaSAnders Carlsson 
4072437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
4089793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
4092437cbfaSAnders Carlsson 
41092bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
41192bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
41292bbd6d4SMike Stump 
4132437cbfaSAnders Carlsson   // struct __block_literal_generic {
4145d2534adSMike Stump   //   void *__isa;
4155d2534adSMike Stump   //   int __flags;
4165d2534adSMike Stump   //   int __reserved;
4175d2534adSMike Stump   //   void (*__invoke)(void *);
4185d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4192437cbfaSAnders Carlsson   // };
420758428f4SOwen Anderson   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
421758428f4SOwen Anderson                                                   PtrToInt8Ty,
42292bbd6d4SMike Stump                                                   IntTy,
42392bbd6d4SMike Stump                                                   IntTy,
424626aecc4SMike Stump                                                   PtrToInt8Ty,
4252437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
4262437cbfaSAnders Carlsson                                                   NULL);
4272437cbfaSAnders Carlsson 
428005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
429005c9a62SMike Stump                           GenericBlockLiteralType);
4302437cbfaSAnders Carlsson 
431005c9a62SMike Stump   return GenericBlockLiteralType;
4322437cbfaSAnders Carlsson }
4332437cbfaSAnders Carlsson 
4345d2534adSMike Stump 
435bfb3671bSAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
436bfb3671bSAnders Carlsson                                           ReturnValueSlot ReturnValue) {
4372437cbfaSAnders Carlsson   const BlockPointerType *BPT =
438c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
4392437cbfaSAnders Carlsson 
4402437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
4412437cbfaSAnders Carlsson 
4422437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
4432437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
4449793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
4452437cbfaSAnders Carlsson 
4462437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
4472437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
4482437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
4492437cbfaSAnders Carlsson 
4502437cbfaSAnders Carlsson   // Get the function pointer from the literal.
4512437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
4522437cbfaSAnders Carlsson 
4532437cbfaSAnders Carlsson   BlockLiteral =
4542437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
455abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
4562437cbfaSAnders Carlsson                           "tmp");
4572437cbfaSAnders Carlsson 
4582437cbfaSAnders Carlsson   // Add the block literal.
4592437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
4602437cbfaSAnders Carlsson   CallArgList Args;
4612437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
4622437cbfaSAnders Carlsson 
463479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
464479e6fc7SAnders Carlsson 
4652437cbfaSAnders Carlsson   // And the rest of the arguments.
4669dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
467479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
4682437cbfaSAnders Carlsson 
4695f50c651SAnders Carlsson   // Load the function.
470c76493a6SDaniel Dunbar   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
4715f50c651SAnders Carlsson 
472ab26cfa5SJohn McCall   const FunctionType *FuncTy = FnType->getAs<FunctionType>();
473ab26cfa5SJohn McCall   QualType ResultType = FuncTy->getResultType();
474a60cbcdfSAnders Carlsson 
475a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
476c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args,
477c50c27ccSRafael Espindola                                    FuncTy->getExtInfo());
4785f50c651SAnders Carlsson 
4795f50c651SAnders Carlsson   // Cast the function pointer to the right type.
4805f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
481a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
4825f50c651SAnders Carlsson 
4839793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
4845f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
4855f50c651SAnders Carlsson 
4862437cbfaSAnders Carlsson   // And call the block.
487bfb3671bSAnders Carlsson   return EmitCall(FnInfo, Func, ReturnValue, Args);
4882437cbfaSAnders Carlsson }
4896a60fa24SAnders Carlsson 
49040775003SKen Dyck CharUnits CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
4910168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
49240775003SKen Dyck   CharUnits &offset = BlockDecls[VD];
4930168f4b2SAnders Carlsson 
49497d01d50SMike Stump   // See if we have already allocated an offset for this variable.
49540775003SKen Dyck   if (offset.isPositive())
4967fe9cc1dSMike Stump     return offset;
4977fe9cc1dSMike Stump 
4984446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
499e1b19ba0SMike Stump   if (!BlockHasCopyDispose)
500e1b19ba0SMike Stump     if (E->isByRef()
501e1b19ba0SMike Stump         || BlockRequiresCopying(E->getType()))
5024446dcf0SMike Stump       BlockHasCopyDispose = true;
5037fe9cc1dSMike Stump 
50497d01d50SMike Stump   // if not, allocate one now.
50597d01d50SMike Stump   offset = getBlockOffset(E);
5067fe9cc1dSMike Stump 
5077fe9cc1dSMike Stump   return offset;
50897d01d50SMike Stump }
50997d01d50SMike Stump 
5107fe9cc1dSMike Stump llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const BlockDeclRefExpr *E) {
5117fe9cc1dSMike Stump   const ValueDecl *VD = E->getDecl();
51240775003SKen Dyck   CharUnits offset = AllocateBlockDecl(E);
5137fe9cc1dSMike Stump 
5147fe9cc1dSMike Stump 
51597d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
51697d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
51741a75027SOwen Anderson                        llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
51840775003SKen Dyck                                                          offset.getQuantity()),
5192d33d630SMike Stump                                      "block.literal");
52097d01d50SMike Stump   if (E->isByRef()) {
52197d01d50SMike Stump     const llvm::Type *PtrStructTy
5220168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
523efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
524efd7caa8SMike Stump     BlockHasCopyDispose = true;
5250168f4b2SAnders Carlsson 
5260168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
5279793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
52897d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
529c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
53097d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
531c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
53297d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
5330168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
5340168f4b2SAnders Carlsson                                 VD->getNameAsString());
53597d01d50SMike Stump   } else {
5360168f4b2SAnders Carlsson     const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType());
5370168f4b2SAnders Carlsson 
5389793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
53997d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
54097d01d50SMike Stump   }
54197d01d50SMike Stump   return V;
54297d01d50SMike Stump }
54397d01d50SMike Stump 
544692c6e37SMike Stump void CodeGenFunction::BlockForwardSelf() {
545692c6e37SMike Stump   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
546692c6e37SMike Stump   ImplicitParamDecl *SelfDecl = OMD->getSelfDecl();
547692c6e37SMike Stump   llvm::Value *&DMEntry = LocalDeclMap[SelfDecl];
548692c6e37SMike Stump   if (DMEntry)
549692c6e37SMike Stump     return;
550692c6e37SMike Stump   // FIXME - Eliminate BlockDeclRefExprs, clients don't need/want to care
551692c6e37SMike Stump   BlockDeclRefExpr *BDRE = new (getContext())
552692c6e37SMike Stump     BlockDeclRefExpr(SelfDecl,
553692c6e37SMike Stump                      SelfDecl->getType(), SourceLocation(), false);
554692c6e37SMike Stump   DMEntry = GetAddrOfBlockDecl(BDRE);
555692c6e37SMike Stump }
556692c6e37SMike Stump 
5572d5a2878SMike Stump llvm::Constant *
5586c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
5596a60fa24SAnders Carlsson   // Generate the block descriptor.
5606a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
56192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
56292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
5636a60fa24SAnders Carlsson 
564fc83aa04SBlaine Garst   llvm::Constant *DescriptorFields[4];
5656a60fa24SAnders Carlsson 
5666a60fa24SAnders Carlsson   // Reserved
5670b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
5686a60fa24SAnders Carlsson 
5696a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
5706a60fa24SAnders Carlsson   // block literal struct.
57198ca7943SKen Dyck   CharUnits BlockLiteralSize =
57298ca7943SKen Dyck     CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
573170229f6SOwen Anderson   DescriptorFields[1] =
57440775003SKen Dyck     llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
5756a60fa24SAnders Carlsson 
576fc83aa04SBlaine Garst   // signature.  non-optional ObjC-style method descriptor @encode sequence
577fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
578fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
579fc83aa04SBlaine Garst 
580fc83aa04SBlaine Garst   DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
581fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
582fc83aa04SBlaine Garst 
583fc83aa04SBlaine Garst   // layout
584fc83aa04SBlaine Garst   DescriptorFields[3] =
585fc83aa04SBlaine Garst     llvm::ConstantInt::get(UnsignedLongTy,0);
586fc83aa04SBlaine Garst 
587fc83aa04SBlaine Garst   // build the structure from the 4 elements
5886a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
589fc83aa04SBlaine Garst     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
5906a60fa24SAnders Carlsson 
5916a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
592c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
5936a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
594c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
5956a60fa24SAnders Carlsson 
596950a9518SDavid Chisnall   int FieldCount = 5;
5976a60fa24SAnders Carlsson   // Generate the constants for the block literal.
598950a9518SDavid Chisnall 
599950a9518SDavid Chisnall   std::vector<llvm::Constant*> LiteralFields(FieldCount);
6006a60fa24SAnders Carlsson 
6012d5a2878SMike Stump   CodeGenFunction::BlockInfo Info(0, n);
60240775003SKen Dyck   CharUnits subBlockSize;
6035262b119SKen Dyck   CharUnits subBlockAlign;
6041db7d04bSMike Stump   llvm::SmallVector<const Expr *, 8> subBlockDeclRefDecls;
605a61bb4d1SDaniel Dunbar   bool subBlockHasCopyDispose = false;
6065469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
607cb2fbcb0SMike Stump   llvm::Function *Fn
608692c6e37SMike Stump     = CodeGenFunction(CGM).GenerateBlockFunction(BE, Info, 0, LocalDeclMap,
6095469f29aSMike Stump                                                  subBlockSize,
610b750d928SMike Stump                                                  subBlockAlign,
6114446dcf0SMike Stump                                                  subBlockDeclRefDecls,
6124446dcf0SMike Stump                                                  subBlockHasCopyDispose);
613cb2fbcb0SMike Stump   assert(subBlockSize == BlockLiteralSize
614cb2fbcb0SMike Stump          && "no imports allowed for global block");
6156a60fa24SAnders Carlsson 
6166a60fa24SAnders Carlsson   // isa
617971f9b66SMike Stump   LiteralFields[0] = getNSConcreteGlobalBlock();
6186a60fa24SAnders Carlsson 
6196a60fa24SAnders Carlsson   // Flags
620fc83aa04SBlaine Garst   LiteralFields[1] =
621f27ab71dSBlaine Garst     llvm::ConstantInt::get(IntTy, BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE);
6226a60fa24SAnders Carlsson 
6236a60fa24SAnders Carlsson   // Reserved
6240b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
6256a60fa24SAnders Carlsson 
6266a60fa24SAnders Carlsson   // Function
6276a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
6286a60fa24SAnders Carlsson 
6296a60fa24SAnders Carlsson   // Descriptor
6306a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
6316a60fa24SAnders Carlsson 
6326a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
633950a9518SDavid Chisnall     llvm::ConstantStruct::get(VMContext, LiteralFields, false);
6346a60fa24SAnders Carlsson 
6356a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
636c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
6376a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
638c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
6396a60fa24SAnders Carlsson 
6406a60fa24SAnders Carlsson   return BlockLiteral;
6416a60fa24SAnders Carlsson }
6426a60fa24SAnders Carlsson 
643cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
64438382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
64538382028SMike Stump                                       "self");
64638382028SMike Stump   // For now, we codegen based upon byte offsets.
64738382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
648cb2fbcb0SMike Stump }
649cb2fbcb0SMike Stump 
6504446dcf0SMike Stump llvm::Function *
6514446dcf0SMike Stump CodeGenFunction::GenerateBlockFunction(const BlockExpr *BExpr,
652cb2fbcb0SMike Stump                                        const BlockInfo& Info,
653692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
6545469f29aSMike Stump                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm,
65540775003SKen Dyck                                        CharUnits &Size,
6565262b119SKen Dyck                                        CharUnits &Align,
6574446dcf0SMike Stump                        llvm::SmallVector<const Expr *, 8> &subBlockDeclRefDecls,
6584446dcf0SMike Stump                                        bool &subBlockHasCopyDispose) {
6599074ed8cSDevang Patel 
6609074ed8cSDevang Patel   // Check if we should generate debug info for this block.
6619074ed8cSDevang Patel   if (CGM.getDebugInfo())
6629074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
6639074ed8cSDevang Patel 
6645469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
6655469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
6665469f29aSMike Stump   // in a block.
6675469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
6685469f29aSMike Stump        i != ldm.end();
6695469f29aSMike Stump        ++i) {
6705469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
6715469f29aSMike Stump 
6720ca16601SDaniel Dunbar     if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage())
6735469f29aSMike Stump       LocalDeclMap[VD] = i->second;
6745469f29aSMike Stump   }
6755469f29aSMike Stump 
67698ca7943SKen Dyck   BlockOffset =
67798ca7943SKen Dyck       CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
6785262b119SKen Dyck   BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
67909a9b6e3SEli Friedman 
680aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
681aae4349dSFariborz Jahanian   QualType ResultType;
682c50c27ccSRafael Espindola   FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
683aae4349dSFariborz Jahanian   bool IsVariadic;
684a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
685a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
686aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
687aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
688658fe02dSMike Stump   } else {
689aae4349dSFariborz Jahanian     // K&R style block.
690aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
691aae4349dSFariborz Jahanian     IsVariadic = false;
692aae4349dSFariborz Jahanian   }
6936a60fa24SAnders Carlsson 
6946a60fa24SAnders Carlsson   FunctionArgList Args;
6956a60fa24SAnders Carlsson 
6967fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
6977fe9cc1dSMike Stump 
6983385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
6996a60fa24SAnders Carlsson 
7007fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
701d015328fSMike Stump 
702945fec05SMike Stump   // Allocate all BlockDeclRefDecls, so we can calculate the right ParmTy below.
7037fe9cc1dSMike Stump   AllocateAllBlockDeclRefs(Info, this);
7047fe9cc1dSMike Stump 
705e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
706e1b19ba0SMike Stump                                                   BlockDeclRefDecls);
7076a60fa24SAnders Carlsson   // FIXME: This leaks
7086a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
709*4d4dcc8eSJohn McCall     ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
710d015328fSMike Stump                               SourceLocation(), II,
711d015328fSMike Stump                               ParmTy);
7126a60fa24SAnders Carlsson 
7136a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
714cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
7156a60fa24SAnders Carlsson 
716c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
7176a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
718eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
7196a60fa24SAnders Carlsson 
7206a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
721c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
7226a60fa24SAnders Carlsson 
7236a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
724aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
7256a60fa24SAnders Carlsson 
7266a60fa24SAnders Carlsson   llvm::Function *Fn =
7276a60fa24SAnders Carlsson     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
728d6b28fc6SBenjamin Kramer                            llvm::Twine("__") + Info.Name + "_block_invoke_",
7296a60fa24SAnders Carlsson                            &CGM.getModule());
7306a60fa24SAnders Carlsson 
731c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
732c3e7cff6SDaniel Dunbar 
733324f80b1SChris Lattner   StartFunction(BD, ResultType, Fn, Args,
7343385fe12SChris Lattner                 BExpr->getBody()->getLocEnd());
7352e722b91SMike Stump 
736324f80b1SChris Lattner   CurFuncDecl = OuterFuncDecl;
73728ec0cf8SChris Lattner   CurCodeDecl = BD;
738017460abSMike Stump 
739017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
740017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
741017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
742017460abSMike Stump   --entry_ptr;
743017460abSMike Stump 
7443385fe12SChris Lattner   EmitStmt(BExpr->getBody());
745017460abSMike Stump 
7467d69911aSMike Stump   // Remember where we were...
7477d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
748017460abSMike Stump 
7497d69911aSMike Stump   // Go back to the entry.
750017460abSMike Stump   ++entry_ptr;
751017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
752017460abSMike Stump 
7532e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
7542e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
755bf78478dSChris Lattner     for (unsigned i = 0, e = BlockDeclRefDecls.size(); i != e; ++i) {
756bf78478dSChris Lattner       if (const BlockDeclRefExpr *BDRE =
757bf78478dSChris Lattner             dyn_cast<BlockDeclRefExpr>(BlockDeclRefDecls[i])) {
7582e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
7592e722b91SMike Stump         DI->setLocation(D->getLocation());
7602e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
7612e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
7622e722b91SMike Stump                                               Builder, this);
7632e722b91SMike Stump       }
7642e722b91SMike Stump     }
7652e722b91SMike Stump   }
7667d69911aSMike Stump   // And resume where we left off.
7677d69911aSMike Stump   if (resume == 0)
7687d69911aSMike Stump     Builder.ClearInsertionPoint();
7697d69911aSMike Stump   else
7707d69911aSMike Stump     Builder.SetInsertPoint(resume);
7712e722b91SMike Stump 
7723385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
7736a60fa24SAnders Carlsson 
774b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
7755262b119SKen Dyck   CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
77640775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
7775262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
7785262b119SKen Dyck                                MinAlign.getQuantity()));
779b750d928SMike Stump 
780cb2fbcb0SMike Stump   Size = BlockOffset;
781b750d928SMike Stump   Align = BlockAlign;
782b750d928SMike Stump   subBlockDeclRefDecls = BlockDeclRefDecls;
7834446dcf0SMike Stump   subBlockHasCopyDispose |= BlockHasCopyDispose;
7846a60fa24SAnders Carlsson   return Fn;
7856a60fa24SAnders Carlsson }
7861db7d04bSMike Stump 
78740775003SKen Dyck CharUnits BlockFunction::getBlockOffset(const BlockDeclRefExpr *BDRE) {
7881db7d04bSMike Stump   const ValueDecl *D = dyn_cast<ValueDecl>(BDRE->getDecl());
7891db7d04bSMike Stump 
79040775003SKen Dyck   CharUnits Size = getContext().getTypeSizeInChars(D->getType());
791160146ebSKen Dyck   CharUnits Align = getContext().getDeclAlign(D);
7921db7d04bSMike Stump 
7931db7d04bSMike Stump   if (BDRE->isByRef()) {
79440775003SKen Dyck     Size = getContext().getTypeSizeInChars(getContext().VoidPtrTy);
7955262b119SKen Dyck     Align = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
7961db7d04bSMike Stump   }
7971db7d04bSMike Stump 
7985262b119SKen Dyck   assert ((Align.isPositive()) && "alignment must be 1 byte or more");
7991db7d04bSMike Stump 
80040775003SKen Dyck   CharUnits OldOffset = BlockOffset;
8011db7d04bSMike Stump 
8021db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
80340775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
8045262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
8051db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
8061db7d04bSMike Stump 
80740775003SKen Dyck   CharUnits Pad = BlockOffset - OldOffset;
80840775003SKen Dyck   if (Pad.isPositive()) {
80940775003SKen Dyck     llvm::ArrayType::get(llvm::Type::getInt8Ty(VMContext), Pad.getQuantity());
8101db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
81140775003SKen Dyck                                                        llvm::APInt(32,
81240775003SKen Dyck                                                          Pad.getQuantity()),
8131db7d04bSMike Stump                                                        ArrayType::Normal, 0);
8141db7d04bSMike Stump     ValueDecl *PadDecl = VarDecl::Create(getContext(), 0, SourceLocation(),
815c4df4076SDouglas Gregor                                          0, QualType(PadTy), 0,
816c4df4076SDouglas Gregor                                          VarDecl::None, VarDecl::None);
8171db7d04bSMike Stump     Expr *E;
8181db7d04bSMike Stump     E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
819ed6c7440SDouglas Gregor                                        SourceLocation());
8201db7d04bSMike Stump     BlockDeclRefDecls.push_back(E);
8211db7d04bSMike Stump   }
8221db7d04bSMike Stump   BlockDeclRefDecls.push_back(BDRE);
8231db7d04bSMike Stump 
8241db7d04bSMike Stump   BlockOffset += Size;
8251db7d04bSMike Stump   return BlockOffset-Size;
8261db7d04bSMike Stump }
82797d01d50SMike Stump 
828aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
829aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
83067645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
8310c743277SMike Stump   QualType R = getContext().VoidTy;
8320c743277SMike Stump 
8330c743277SMike Stump   FunctionArgList Args;
8340c743277SMike Stump   // FIXME: This leaks
835aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
8367fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8377fe9cc1dSMike Stump                               SourceLocation(), 0,
838aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
839aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
8400c743277SMike Stump   ImplicitParamDecl *Src =
8417fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
8427fe9cc1dSMike Stump                               SourceLocation(), 0,
8430c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
8440c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
8450c743277SMike Stump 
8460c743277SMike Stump   const CGFunctionInfo &FI =
847c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
8480c743277SMike Stump 
849cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
850cbc2bcafSMike Stump   // internal linkage.
8510c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
8520c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
8530c743277SMike Stump 
8540c743277SMike Stump   llvm::Function *Fn =
8550c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
856d6b28fc6SBenjamin Kramer                            "__copy_helper_block_", &CGM.getModule());
8570c743277SMike Stump 
8580c743277SMike Stump   IdentifierInfo *II
8590c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
8600c743277SMike Stump 
8610c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
8620c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
86360ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
864c4df4076SDouglas Gregor                                           FunctionDecl::Static,
865c4df4076SDouglas Gregor                                           FunctionDecl::None,
866c4df4076SDouglas Gregor                                           false,
8670c743277SMike Stump                                           true);
8680c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
869aeb0ffd5SMike Stump 
870aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
871aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
87267645930SMike Stump 
87367645930SMike Stump   if (NoteForHelperp) {
87467645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
87567645930SMike Stump 
8769793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
877aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
878aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
879aeb0ffd5SMike Stump 
880aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
8813b65ac26SMike Stump     llvm::Type *PtrPtrT;
8829793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
8833b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
8843b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
885aeb0ffd5SMike Stump 
886aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
887aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
888aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
889aeb0ffd5SMike Stump 
890aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
891aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
892aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
893aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
894aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
8959793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
896aeb0ffd5SMike Stump         Srcv = Builder.CreateLoad(Srcv);
897aeb0ffd5SMike Stump 
898aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
899aeb0ffd5SMike Stump         Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
900aeb0ffd5SMike Stump 
90141a75027SOwen Anderson         llvm::Value *N = llvm::ConstantInt::get(
90241a75027SOwen Anderson               llvm::Type::getInt32Ty(T->getContext()), flag);
903aeb0ffd5SMike Stump         llvm::Value *F = getBlockObjectAssign();
904aeb0ffd5SMike Stump         Builder.CreateCall3(F, Dstv, Srcv, N);
905aeb0ffd5SMike Stump       }
906aeb0ffd5SMike Stump     }
90767645930SMike Stump   }
908aeb0ffd5SMike Stump 
9090c743277SMike Stump   CGF.FinishFunction();
9100c743277SMike Stump 
911ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
91297d01d50SMike Stump }
91397d01d50SMike Stump 
914d6ef62f0SMike Stump llvm::Constant *BlockFunction::
915aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
916aeb0ffd5SMike Stump                               const llvm::StructType* T,
91767645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
9180c743277SMike Stump   QualType R = getContext().VoidTy;
9190c743277SMike Stump 
9200c743277SMike Stump   FunctionArgList Args;
9210c743277SMike Stump   // FIXME: This leaks
9220c743277SMike Stump   ImplicitParamDecl *Src =
9237fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9247fe9cc1dSMike Stump                               SourceLocation(), 0,
9250c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9260c743277SMike Stump 
9270c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9280c743277SMike Stump 
9290c743277SMike Stump   const CGFunctionInfo &FI =
930c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
9310c743277SMike Stump 
932cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
933cbc2bcafSMike Stump   // internal linkage.
9340c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9350c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9360c743277SMike Stump 
9370c743277SMike Stump   llvm::Function *Fn =
9380c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
939d6b28fc6SBenjamin Kramer                            "__destroy_helper_block_", &CGM.getModule());
9400c743277SMike Stump 
9410c743277SMike Stump   IdentifierInfo *II
9420c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
9430c743277SMike Stump 
9440c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9450c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
94660ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
947c4df4076SDouglas Gregor                                           FunctionDecl::Static,
948c4df4076SDouglas Gregor                                           FunctionDecl::None,
949c4df4076SDouglas Gregor                                           false, true);
9500c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
9516f7d9f87SMike Stump 
95267645930SMike Stump   if (NoteForHelperp) {
95367645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
95467645930SMike Stump 
9556f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
9566f7d9f87SMike Stump     llvm::Type *PtrPtrT;
9579793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9586f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
9596f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
9606f7d9f87SMike Stump 
9616f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
9626f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
9636f7d9f87SMike Stump       int index = NoteForHelper[i].index;
9646f7d9f87SMike Stump 
9656f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
9666f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
9676f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
9686f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
9696f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
9709793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
9716f7d9f87SMike Stump         Srcv = Builder.CreateLoad(Srcv);
9726f7d9f87SMike Stump 
9736f7d9f87SMike Stump         BuildBlockRelease(Srcv, flag);
9746f7d9f87SMike Stump       }
9756f7d9f87SMike Stump     }
97667645930SMike Stump   }
9776f7d9f87SMike Stump 
9780c743277SMike Stump   CGF.FinishFunction();
9790c743277SMike Stump 
980ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
9810c743277SMike Stump }
9820c743277SMike Stump 
983aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
98467645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
985aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
986aeb0ffd5SMike Stump                                                          T, NoteForHelper);
9870c743277SMike Stump }
9880c743277SMike Stump 
989aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
99067645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
991aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
99267645930SMike Stump                                                             T, NoteForHelperp);
99397d01d50SMike Stump }
994626aecc4SMike Stump 
995f89230d9SMike Stump llvm::Constant *BlockFunction::
996f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
997ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
998ee2a5ee5SMike Stump 
999ee2a5ee5SMike Stump   FunctionArgList Args;
1000ee2a5ee5SMike Stump   // FIXME: This leaks
1001f89230d9SMike Stump   ImplicitParamDecl *Dst =
10027fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10037fe9cc1dSMike Stump                               SourceLocation(), 0,
1004f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1005f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
1006f89230d9SMike Stump 
1007f89230d9SMike Stump   // FIXME: This leaks
1008ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10097fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10107fe9cc1dSMike Stump                               SourceLocation(), 0,
1011ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1012ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1013ee2a5ee5SMike Stump 
1014ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1015c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1016ee2a5ee5SMike Stump 
1017ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1018ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1019ee2a5ee5SMike Stump 
1020cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1021cbc2bcafSMike Stump   // internal linkage.
1022ee2a5ee5SMike Stump   llvm::Function *Fn =
1023ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1024d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_copy_", &CGM.getModule());
1025ee2a5ee5SMike Stump 
1026ee2a5ee5SMike Stump   IdentifierInfo *II
1027ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1028ee2a5ee5SMike Stump 
1029ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1030ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
103160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1032c4df4076SDouglas Gregor                                           FunctionDecl::Static,
1033c4df4076SDouglas Gregor                                           FunctionDecl::None,
1034c4df4076SDouglas Gregor                                           false, true);
1035ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1036f89230d9SMike Stump 
1037f89230d9SMike Stump   // dst->x
1038f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
10399793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
10403b65ac26SMike Stump   V = Builder.CreateLoad(V);
1041f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1042f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1043f89230d9SMike Stump 
1044f89230d9SMike Stump   // src->x
1045f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1046f89230d9SMike Stump   V = Builder.CreateLoad(V);
1047f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1048f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
10499793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1050f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1051f89230d9SMike Stump 
1052f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1053f89230d9SMike Stump 
105441a75027SOwen Anderson   llvm::Value *N = llvm::ConstantInt::get(
105541a75027SOwen Anderson           llvm::Type::getInt32Ty(T->getContext()), flag);
1056f89230d9SMike Stump   llvm::Value *F = getBlockObjectAssign();
1057f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1058f89230d9SMike Stump 
1059ee2a5ee5SMike Stump   CGF.FinishFunction();
1060ee2a5ee5SMike Stump 
1061ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1062ee2a5ee5SMike Stump }
1063ee2a5ee5SMike Stump 
1064fbe25dd1SMike Stump llvm::Constant *
1065fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1066fbe25dd1SMike Stump                                                   int flag) {
1067ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1068ee2a5ee5SMike Stump 
1069ee2a5ee5SMike Stump   FunctionArgList Args;
1070ee2a5ee5SMike Stump   // FIXME: This leaks
1071ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
10727fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10737fe9cc1dSMike Stump                               SourceLocation(), 0,
1074ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1075ee2a5ee5SMike Stump 
1076ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1077ee2a5ee5SMike Stump 
1078ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1079c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1080ee2a5ee5SMike Stump 
1081ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1082ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1083ee2a5ee5SMike Stump 
1084cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1085cbc2bcafSMike Stump   // internal linkage.
1086ee2a5ee5SMike Stump   llvm::Function *Fn =
1087ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1088d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_dispose_",
1089ee2a5ee5SMike Stump                            &CGM.getModule());
1090ee2a5ee5SMike Stump 
1091ee2a5ee5SMike Stump   IdentifierInfo *II
1092ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1093ee2a5ee5SMike Stump 
1094ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1095ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
109660ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
1097c4df4076SDouglas Gregor                                           FunctionDecl::Static,
1098c4df4076SDouglas Gregor                                           FunctionDecl::None,
1099c4df4076SDouglas Gregor                                           false, true);
1100ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1101fbe25dd1SMike Stump 
1102fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
11039793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
11043b65ac26SMike Stump   V = Builder.CreateLoad(V);
1105fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
11069793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
11073b65ac26SMike Stump   V = Builder.CreateLoad(V);
1108fbe25dd1SMike Stump 
1109fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1110fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1111ee2a5ee5SMike Stump   CGF.FinishFunction();
1112ee2a5ee5SMike Stump 
1113ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1114ee2a5ee5SMike Stump }
1115ee2a5ee5SMike Stump 
1116f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1117e08ea787SChris Lattner                                                     int Flag, unsigned Align) {
1118e08ea787SChris Lattner   // All alignments below that of pointer alignment collapse down to just
1119cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1120cbc2bcafSMike Stump   // with.
1121cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1122e08ea787SChris Lattner 
1123cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1124cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1125cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1126e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1127e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1128cbc2bcafSMike Stump   if (Entry)
1129cbc2bcafSMike Stump     return Entry;
1130e08ea787SChris Lattner   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1131ee2a5ee5SMike Stump }
1132ee2a5ee5SMike Stump 
1133fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1134e08ea787SChris Lattner                                                        int Flag,
1135cbc2bcafSMike Stump                                                        unsigned Align) {
1136cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1137cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1138cbc2bcafSMike Stump   // with.
1139cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1140e08ea787SChris Lattner 
1141cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1142cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1143cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1144e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1145e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1146cbc2bcafSMike Stump   if (Entry)
1147cbc2bcafSMike Stump     return Entry;
1148e08ea787SChris Lattner   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1149ee2a5ee5SMike Stump }
1150ee2a5ee5SMike Stump 
1151626aecc4SMike Stump llvm::Value *BlockFunction::getBlockObjectDispose() {
1152626aecc4SMike Stump   if (CGM.BlockObjectDispose == 0) {
1153626aecc4SMike Stump     const llvm::FunctionType *FTy;
1154626aecc4SMike Stump     std::vector<const llvm::Type*> ArgTys;
115541a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1156626aecc4SMike Stump     ArgTys.push_back(PtrToInt8Ty);
115741a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11589793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1159626aecc4SMike Stump     CGM.BlockObjectDispose
1160626aecc4SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_dispose");
1161626aecc4SMike Stump   }
1162626aecc4SMike Stump   return CGM.BlockObjectDispose;
1163626aecc4SMike Stump }
1164626aecc4SMike Stump 
1165f89230d9SMike Stump llvm::Value *BlockFunction::getBlockObjectAssign() {
1166f89230d9SMike Stump   if (CGM.BlockObjectAssign == 0) {
1167f89230d9SMike Stump     const llvm::FunctionType *FTy;
1168f89230d9SMike Stump     std::vector<const llvm::Type*> ArgTys;
116941a75027SOwen Anderson     const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext);
1170f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
1171f89230d9SMike Stump     ArgTys.push_back(PtrToInt8Ty);
117241a75027SOwen Anderson     ArgTys.push_back(llvm::Type::getInt32Ty(VMContext));
11739793f0e4SOwen Anderson     FTy = llvm::FunctionType::get(ResultType, ArgTys, false);
1174f89230d9SMike Stump     CGM.BlockObjectAssign
1175f89230d9SMike Stump       = CGM.CreateRuntimeFunction(FTy, "_Block_object_assign");
1176f89230d9SMike Stump   }
1177f89230d9SMike Stump   return CGM.BlockObjectAssign;
1178f89230d9SMike Stump }
1179f89230d9SMike Stump 
1180fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1181626aecc4SMike Stump   llvm::Value *F = getBlockObjectDispose();
1182fbe25dd1SMike Stump   llvm::Value *N;
1183626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
118441a75027SOwen Anderson   N = llvm::ConstantInt::get(llvm::Type::getInt32Ty(V->getContext()), flag);
1185626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1186626aecc4SMike Stump }
11874446dcf0SMike Stump 
11884446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1189aeb0ffd5SMike Stump 
1190aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1191aeb0ffd5SMike Stump                              CGBuilderTy &B)
1192170229f6SOwen Anderson   : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()), Builder(B) {
119341a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
119441a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1195aeb0ffd5SMike Stump 
1196aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1197aeb0ffd5SMike Stump }
1198