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 
279d42f0f1SJohn McCall CGBlockInfo::CGBlockInfo(const char *N)
28*9ffe24f1SFariborz Jahanian   : Name(N), CXXThisRef(0), NeedsObjCSelf(false),
29*9ffe24f1SFariborz Jahanian     HasCXXObject(false), BlockHasCopyDispose(false) {
309d42f0f1SJohn McCall 
319d42f0f1SJohn McCall   // Skip asm prefix, if any.
329d42f0f1SJohn McCall   if (Name && Name[0] == '\01')
339d42f0f1SJohn McCall     ++Name;
349d42f0f1SJohn McCall }
359d42f0f1SJohn McCall 
369d42f0f1SJohn McCall 
37d6ef62f0SMike Stump llvm::Constant *CodeGenFunction::
38c05349e5SFariborz Jahanian BuildDescriptorBlockDecl(const BlockExpr *BE, const CGBlockInfo &Info,
39d2142cffSMike Stump                          const llvm::StructType* Ty,
40afa3c0a8SFariborz Jahanian                          llvm::Constant *BlockVarLayout,
41aeb0ffd5SMike Stump                          std::vector<HelperInfo> *NoteForHelper) {
42c05349e5SFariborz Jahanian   bool BlockHasCopyDispose = Info.BlockHasCopyDispose;
43c05349e5SFariborz Jahanian   CharUnits Size = Info.BlockSize;
44c2c38331SMike Stump   const llvm::Type *UnsignedLongTy
45c2c38331SMike Stump     = CGM.getTypes().ConvertType(getContext().UnsignedLongTy);
4685284bacSMike Stump   llvm::Constant *C;
4785284bacSMike Stump   std::vector<llvm::Constant*> Elts;
4885284bacSMike Stump 
4985284bacSMike Stump   // reserved
50b7a2fe6fSOwen Anderson   C = llvm::ConstantInt::get(UnsignedLongTy, 0);
5185284bacSMike Stump   Elts.push_back(C);
5285284bacSMike Stump 
5385284bacSMike Stump   // Size
542ac40a9fSMike Stump   // FIXME: What is the right way to say this doesn't fit?  We should give
552ac40a9fSMike Stump   // a user diagnostic in that case.  Better fix would be to change the
562ac40a9fSMike Stump   // API to size_t.
5740775003SKen Dyck   C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity());
5885284bacSMike Stump   Elts.push_back(C);
5985284bacSMike Stump 
60fc83aa04SBlaine Garst   // optional copy/dispose helpers
6185284bacSMike Stump   if (BlockHasCopyDispose) {
6285284bacSMike Stump     // copy_func_helper_decl
6367645930SMike Stump     Elts.push_back(BuildCopyHelper(Ty, NoteForHelper));
6485284bacSMike Stump 
6585284bacSMike Stump     // destroy_func_decl
6667645930SMike Stump     Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper));
6785284bacSMike Stump   }
6885284bacSMike Stump 
69fc83aa04SBlaine Garst   // Signature.  non-optional ObjC-style method descriptor @encode sequence
70fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
71fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
72fc83aa04SBlaine Garst 
73fc83aa04SBlaine Garst   Elts.push_back(llvm::ConstantExpr::getBitCast(
74fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty));
75fc83aa04SBlaine Garst 
76fc83aa04SBlaine Garst   // Layout.
77afa3c0a8SFariborz Jahanian   C = BlockVarLayout;
78c05349e5SFariborz Jahanian 
79fc83aa04SBlaine Garst   Elts.push_back(C);
80fc83aa04SBlaine Garst 
8141eaf0acSNick Lewycky   C = llvm::ConstantStruct::get(VMContext, Elts, false);
8285284bacSMike Stump 
83c10c8d3eSOwen Anderson   C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
8485284bacSMike Stump                                llvm::GlobalValue::InternalLinkage,
85c10c8d3eSOwen Anderson                                C, "__block_descriptor_tmp");
8685284bacSMike Stump   return C;
8785284bacSMike Stump }
8885284bacSMike Stump 
899d42f0f1SJohn McCall static void CollectBlockDeclRefInfo(const Stmt *S, CGBlockInfo &Info) {
90ed5e69feSAnders Carlsson   for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
91ed5e69feSAnders Carlsson        I != E; ++I)
92dd942713SDaniel Dunbar     if (*I)
939d42f0f1SJohn McCall       CollectBlockDeclRefInfo(*I, Info);
94ed5e69feSAnders Carlsson 
957fe9cc1dSMike Stump   // We want to ensure we walk down into block literals so we can find
967fe9cc1dSMike Stump   // all nested BlockDeclRefExprs.
97066b6166SMike Stump   if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
989d42f0f1SJohn McCall     Info.InnerBlocks.insert(BE->getBlockDecl());
999d42f0f1SJohn McCall     CollectBlockDeclRefInfo(BE->getBody(), Info);
100066b6166SMike Stump   }
1017fe9cc1dSMike Stump 
1029d42f0f1SJohn McCall   else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1039d42f0f1SJohn McCall     const ValueDecl *D = BDRE->getDecl();
104ed5e69feSAnders Carlsson     // FIXME: Handle enums.
1059d42f0f1SJohn McCall     if (isa<FunctionDecl>(D))
106ed5e69feSAnders Carlsson       return;
107ed5e69feSAnders Carlsson 
1089d42f0f1SJohn McCall     if (isa<ImplicitParamDecl>(D) &&
1099d42f0f1SJohn McCall         isa<ObjCMethodDecl>(D->getDeclContext()) &&
1109d42f0f1SJohn McCall         cast<ObjCMethodDecl>(D->getDeclContext())->getSelfDecl() == D) {
1119d42f0f1SJohn McCall       Info.NeedsObjCSelf = true;
1129d42f0f1SJohn McCall       return;
1139d42f0f1SJohn McCall     }
1149d42f0f1SJohn McCall 
115066b6166SMike Stump     // Only Decls that escape are added.
116e988bdacSFariborz Jahanian     if (!Info.InnerBlocks.count(D->getDeclContext())) {
117e988bdacSFariborz Jahanian       if (BDRE->getCopyConstructorExpr())
118e988bdacSFariborz Jahanian         Info.HasCXXObject = true;
119066b6166SMike Stump       Info.DeclRefs.push_back(BDRE);
120ed5e69feSAnders Carlsson     }
121e988bdacSFariborz Jahanian   }
12287fe5d56SJohn McCall 
1239d42f0f1SJohn McCall   // Make sure to capture implicit 'self' references due to super calls.
1247ea01c3fSChandler Carruth   else if (const ObjCMessageExpr *E = dyn_cast<ObjCMessageExpr>(S)) {
1259d42f0f1SJohn McCall     if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
1269d42f0f1SJohn McCall         E->getReceiverKind() == ObjCMessageExpr::SuperInstance)
1279d42f0f1SJohn McCall       Info.NeedsObjCSelf = true;
1287ea01c3fSChandler Carruth   }
129681c0754SFariborz Jahanian   else if (const ObjCPropertyRefExpr *PE = dyn_cast<ObjCPropertyRefExpr>(S)) {
1309d42f0f1SJohn McCall     // Getter/setter uses may also cause implicit super references,
1319d42f0f1SJohn McCall     // which we can check for with:
132681c0754SFariborz Jahanian     if (PE->isSuperReceiver())
1339d42f0f1SJohn McCall       Info.NeedsObjCSelf = true;
134681c0754SFariborz Jahanian   }
135681c0754SFariborz Jahanian   else if (const ObjCImplicitSetterGetterRefExpr *IE =
136681c0754SFariborz Jahanian            dyn_cast<ObjCImplicitSetterGetterRefExpr>(S)) {
137681c0754SFariborz Jahanian     // Getter/setter uses may also cause implicit super references,
138681c0754SFariborz Jahanian     // which we can check for with:
139681c0754SFariborz Jahanian     if (IE->isSuperReceiver())
140681c0754SFariborz Jahanian       Info.NeedsObjCSelf = true;
141681c0754SFariborz Jahanian   }
1429d42f0f1SJohn McCall   else if (isa<CXXThisExpr>(S))
14387fe5d56SJohn McCall     Info.CXXThisRef = cast<CXXThisExpr>(S);
144ed5e69feSAnders Carlsson }
145ed5e69feSAnders Carlsson 
1469d42f0f1SJohn McCall /// CanBlockBeGlobal - Given a CGBlockInfo struct, determines if a block can be
1472d33d630SMike Stump /// declared as a global variable instead of on the stack.
1489d42f0f1SJohn McCall static bool CanBlockBeGlobal(const CGBlockInfo &Info) {
1497fe9cc1dSMike Stump   return Info.DeclRefs.empty();
1507fe9cc1dSMike Stump }
1517fe9cc1dSMike Stump 
1527fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to
1537fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block
1547fe9cc1dSMike Stump /// invoke function.
1559d42f0f1SJohn McCall static void AllocateAllBlockDeclRefs(CodeGenFunction &CGF, CGBlockInfo &Info) {
15687fe5d56SJohn McCall   if (Info.CXXThisRef)
1579d42f0f1SJohn McCall     CGF.AllocateBlockCXXThisPointer(Info.CXXThisRef);
1587fe9cc1dSMike Stump 
1597fe9cc1dSMike Stump   for (size_t i = 0; i < Info.DeclRefs.size(); ++i)
1609d42f0f1SJohn McCall     CGF.AllocateBlockDecl(Info.DeclRefs[i]);
1619d42f0f1SJohn McCall 
1629d42f0f1SJohn McCall   if (Info.NeedsObjCSelf) {
1639d42f0f1SJohn McCall     ValueDecl *Self = cast<ObjCMethodDecl>(CGF.CurFuncDecl)->getSelfDecl();
1649d42f0f1SJohn McCall     BlockDeclRefExpr *BDRE =
1659d42f0f1SJohn McCall       new (CGF.getContext()) BlockDeclRefExpr(Self, Self->getType(),
1669d42f0f1SJohn McCall                                               SourceLocation(), false);
1679d42f0f1SJohn McCall     Info.DeclRefs.push_back(BDRE);
1689d42f0f1SJohn McCall     CGF.AllocateBlockDecl(BDRE);
1699d42f0f1SJohn McCall   }
170ed5e69feSAnders Carlsson }
171ed5e69feSAnders Carlsson 
172d5010898SFariborz Jahanian static unsigned computeBlockFlag(CodeGenModule &CGM,
173d5010898SFariborz Jahanian                                  const BlockExpr *BE, unsigned flags) {
174d5010898SFariborz Jahanian   QualType BPT = BE->getType();
175d5010898SFariborz Jahanian   const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
176d5010898SFariborz Jahanian   QualType ResultType = ftype->getResultType();
177d5010898SFariborz Jahanian 
178d5010898SFariborz Jahanian   CallArgList Args;
179d5010898SFariborz Jahanian   CodeGenTypes &Types = CGM.getTypes();
180d5010898SFariborz Jahanian   const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args,
181d5010898SFariborz Jahanian                                                        FunctionType::ExtInfo());
182d5010898SFariborz Jahanian   if (CGM.ReturnTypeUsesSRet(FnInfo))
183d5010898SFariborz Jahanian     flags |= CodeGenFunction::BLOCK_USE_STRET;
184d5010898SFariborz Jahanian   return flags;
185d5010898SFariborz Jahanian }
186d5010898SFariborz Jahanian 
1872d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function
1882d33d630SMike Stump // name.
189b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) {
190ed5e69feSAnders Carlsson   std::string Name = CurFn->getName();
1919d42f0f1SJohn McCall   CGBlockInfo Info(Name.c_str());
1929d42f0f1SJohn McCall   Info.InnerBlocks.insert(BE->getBlockDecl());
1939d42f0f1SJohn McCall   CollectBlockDeclRefInfo(BE->getBody(), Info);
194ed5e69feSAnders Carlsson 
195ed5e69feSAnders Carlsson   // Check if the block can be global.
1962d33d630SMike Stump   // FIXME: This test doesn't work for nested blocks yet.  Longer term, I'd like
1972d33d630SMike Stump   // to just have one code path.  We should move this function into CGM and pass
1982d33d630SMike Stump   // CGF, then we can just check to see if CGF is 0.
19997d01d50SMike Stump   if (0 && CanBlockBeGlobal(Info))
200ed5e69feSAnders Carlsson     return CGM.GetAddrOfGlobalBlock(BE, Name.c_str());
20185284bacSMike Stump 
202950a9518SDavid Chisnall   size_t BlockFields = 5;
203950a9518SDavid Chisnall 
204950a9518SDavid Chisnall   std::vector<llvm::Constant*> Elts(BlockFields);
205950a9518SDavid Chisnall 
20685284bacSMike Stump   llvm::Constant *C;
207b750d928SMike Stump   llvm::Value *V;
20885284bacSMike Stump 
20985284bacSMike Stump   {
210afa3c0a8SFariborz Jahanian     llvm::Constant *BlockVarLayout;
21185284bacSMike Stump     // C = BuildBlockStructInitlist();
212f27ab71dSBlaine Garst     unsigned int flags = BLOCK_HAS_SIGNATURE;
213950a9518SDavid Chisnall 
2144446dcf0SMike Stump     // We run this first so that we set BlockHasCopyDispose from the entire
2154446dcf0SMike Stump     // block literal.
2164446dcf0SMike Stump     // __invoke
2174446dcf0SMike Stump     llvm::Function *Fn
2189b5528d2SFariborz Jahanian       = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, BE, Info, CurFuncDecl,
219afa3c0a8SFariborz Jahanian                                                    BlockVarLayout,
2209d42f0f1SJohn McCall                                                    LocalDeclMap);
2219d42f0f1SJohn McCall     BlockHasCopyDispose |= Info.BlockHasCopyDispose;
2224446dcf0SMike Stump     Elts[3] = Fn;
2234446dcf0SMike Stump 
22418bb9284SMike Stump     // FIXME: Don't use BlockHasCopyDispose, it is set more often then
22518bb9284SMike Stump     // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); }
2269d42f0f1SJohn McCall     if (Info.BlockHasCopyDispose)
22785284bacSMike Stump       flags |= BLOCK_HAS_COPY_DISPOSE;
228e988bdacSFariborz Jahanian     // This block may import a c++ object.
229e988bdacSFariborz Jahanian     if (Info.HasCXXObject)
230e988bdacSFariborz Jahanian       flags |= BLOCK_HAS_CXX_OBJ;
23185284bacSMike Stump 
232499ae7ecSMike Stump     // __isa
2337ab278dbSMike Stump     C = CGM.getNSConcreteStackBlock();
234ade90fd1SOwen Anderson     C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty);
2354446dcf0SMike Stump     Elts[0] = C;
23685284bacSMike Stump 
23785284bacSMike Stump     // __flags
238d5010898SFariborz Jahanian     flags = computeBlockFlag(CGM, BE, flags);
23985284bacSMike Stump     const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
24085284bacSMike Stump       CGM.getTypes().ConvertType(CGM.getContext().IntTy));
241b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, flags);
2424446dcf0SMike Stump     Elts[1] = C;
24385284bacSMike Stump 
24485284bacSMike Stump     // __reserved
245b7a2fe6fSOwen Anderson     C = llvm::ConstantInt::get(IntTy, 0);
2464446dcf0SMike Stump     Elts[2] = C;
24785284bacSMike Stump 
2489d42f0f1SJohn McCall     if (Info.BlockLayout.empty()) {
249d6ef62f0SMike Stump       // __descriptor
250afa3c0a8SFariborz Jahanian       C = llvm::Constant::getNullValue(PtrToInt8Ty);
251afa3c0a8SFariborz Jahanian       Elts[4] = BuildDescriptorBlockDecl(BE, Info, 0, C, 0);
252d6ef62f0SMike Stump 
2533a139f37SMike Stump       // Optimize to being a global block.
2543a139f37SMike Stump       Elts[0] = CGM.getNSConcreteGlobalBlock();
255f27ab71dSBlaine Garst 
256b7a2fe6fSOwen Anderson       Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL);
2573a139f37SMike Stump 
25841eaf0acSNick Lewycky       C = llvm::ConstantStruct::get(VMContext, Elts, false);
25985284bacSMike Stump 
260c10c8d3eSOwen Anderson       C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true,
261d6b28fc6SBenjamin Kramer                                    llvm::GlobalValue::InternalLinkage, C,
262d6b28fc6SBenjamin Kramer                                    "__block_holder_tmp_" +
263d6b28fc6SBenjamin Kramer                                    llvm::Twine(CGM.getGlobalUniqueCount()));
2645d2534adSMike Stump       QualType BPT = BE->getType();
265ade90fd1SOwen Anderson       C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT));
26685284bacSMike Stump       return C;
26785284bacSMike Stump     }
26885284bacSMike Stump 
2699d42f0f1SJohn McCall     std::vector<const llvm::Type *> Types(BlockFields+Info.BlockLayout.size());
270aeb0ffd5SMike Stump     for (int i=0; i<4; ++i)
271b750d928SMike Stump       Types[i] = Elts[i]->getType();
272aeb0ffd5SMike Stump     Types[4] = PtrToInt8Ty;
27385284bacSMike Stump 
2749d42f0f1SJohn McCall     for (unsigned i = 0, n = Info.BlockLayout.size(); i != n; ++i) {
2759d42f0f1SJohn McCall       const Expr *E = Info.BlockLayout[i];
2761db7d04bSMike Stump       const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
2771db7d04bSMike Stump       QualType Ty = E->getType();
27897d01d50SMike Stump       if (BDRE && BDRE->isByRef()) {
279d1b378e0SFariborz Jahanian         Types[i+BlockFields] =
280d1b378e0SFariborz Jahanian           llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0);
281d1b378e0SFariborz Jahanian       } else if (BDRE && BDRE->getDecl()->getType()->isReferenceType()) {
282d1b378e0SFariborz Jahanian          Types[i+BlockFields] = llvm::PointerType::get(ConvertType(Ty), 0);
28397d01d50SMike Stump       } else
284950a9518SDavid Chisnall         Types[i+BlockFields] = ConvertType(Ty);
2851db7d04bSMike Stump     }
286b750d928SMike Stump 
287758428f4SOwen Anderson     llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true);
288b750d928SMike Stump 
289b750d928SMike Stump     llvm::AllocaInst *A = CreateTempAlloca(Ty);
2909d42f0f1SJohn McCall     A->setAlignment(Info.BlockAlign.getQuantity());
291b750d928SMike Stump     V = A;
292b750d928SMike Stump 
29387fe5d56SJohn McCall     // Build layout / cleanup information for all the data entries in the
29487fe5d56SJohn McCall     // layout, and write the enclosing fields into the type.
2959d42f0f1SJohn McCall     std::vector<HelperInfo> NoteForHelper(Info.BlockLayout.size());
29687fe5d56SJohn McCall     unsigned NumHelpers = 0;
297aeb0ffd5SMike Stump 
298aeb0ffd5SMike Stump     for (unsigned i=0; i<4; ++i)
299b750d928SMike Stump       Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp"));
300b750d928SMike Stump 
3019d42f0f1SJohn McCall     for (unsigned i=0; i < Info.BlockLayout.size(); ++i) {
3029d42f0f1SJohn McCall       const Expr *E = Info.BlockLayout[i];
303b750d928SMike Stump 
3041db7d04bSMike Stump       // Skip padding.
30587fe5d56SJohn McCall       if (isa<DeclRefExpr>(E)) continue;
3061db7d04bSMike Stump 
307950a9518SDavid Chisnall       llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp");
30887fe5d56SJohn McCall       HelperInfo &Note = NoteForHelper[NumHelpers++];
30987fe5d56SJohn McCall 
31087fe5d56SJohn McCall       Note.index = i+5;
31187fe5d56SJohn McCall 
31287fe5d56SJohn McCall       if (isa<CXXThisExpr>(E)) {
31387fe5d56SJohn McCall         Note.RequiresCopying = false;
31487fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_OBJECT;
31587fe5d56SJohn McCall 
31687fe5d56SJohn McCall         Builder.CreateStore(LoadCXXThis(), Addr);
31787fe5d56SJohn McCall         continue;
31887fe5d56SJohn McCall       }
31987fe5d56SJohn McCall 
32087fe5d56SJohn McCall       const BlockDeclRefExpr *BDRE = cast<BlockDeclRefExpr>(E);
3212a5deb56SFariborz Jahanian       Note.RequiresCopying = BlockRequiresCopying(BDRE);
322e988bdacSFariborz Jahanian       Note.cxxvar_import =
323e988bdacSFariborz Jahanian         BDRE->getCopyConstructorExpr() ? BDRE : 0;
32487fe5d56SJohn McCall       const ValueDecl *VD = BDRE->getDecl();
32587fe5d56SJohn McCall       QualType T = VD->getType();
326e988bdacSFariborz Jahanian 
32787fe5d56SJohn McCall       if (BDRE->isByRef()) {
32887fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_BYREF;
32987fe5d56SJohn McCall         if (T.isObjCGCWeak())
33087fe5d56SJohn McCall           Note.flag |= BLOCK_FIELD_IS_WEAK;
33187fe5d56SJohn McCall       } else if (T->isBlockPointerType()) {
33287fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_BLOCK;
33387fe5d56SJohn McCall       } else {
33487fe5d56SJohn McCall         Note.flag = BLOCK_FIELD_IS_OBJECT;
33587fe5d56SJohn McCall       }
336aeb0ffd5SMike Stump 
3371db7d04bSMike Stump       if (LocalDeclMap[VD]) {
33897d01d50SMike Stump         if (BDRE->isByRef()) {
33997d01d50SMike Stump           llvm::Value *Loc = LocalDeclMap[VD];
34097d01d50SMike Stump           Loc = Builder.CreateStructGEP(Loc, 1, "forwarding");
341c76493a6SDaniel Dunbar           Loc = Builder.CreateLoad(Loc);
34297d01d50SMike Stump           Builder.CreateStore(Loc, Addr);
34397d01d50SMike Stump           continue;
34487fe5d56SJohn McCall         } else {
3453b836180SFariborz Jahanian           if (BDRE->getCopyConstructorExpr()) {
346ea882cd9SFariborz Jahanian             E = BDRE->getCopyConstructorExpr();
347bd30929eSJohn McCall             PushDestructorCleanup(E->getType(), Addr);
3483b836180SFariborz Jahanian           }
349ea882cd9SFariborz Jahanian             else {
35087fe5d56SJohn McCall               E = new (getContext()) DeclRefExpr(const_cast<ValueDecl*>(VD),
351d1b378e0SFariborz Jahanian                                             VD->getType().getNonReferenceType(),
352d1b378e0SFariborz Jahanian                                             SourceLocation());
35364176c2cSFariborz Jahanian               if (VD->getType()->isReferenceType()) {
354d1b378e0SFariborz Jahanian                 E = new (getContext())
355e302792bSJohn McCall                     UnaryOperator(const_cast<Expr*>(E), UO_AddrOf,
356d1b378e0SFariborz Jahanian                                 getContext().getPointerType(E->getType()),
357ed6c7440SDouglas Gregor                                 SourceLocation());
3581db7d04bSMike Stump               }
35964176c2cSFariborz Jahanian             }
36064176c2cSFariborz Jahanian           }
36187fe5d56SJohn McCall         }
36287fe5d56SJohn McCall 
36397d01d50SMike Stump       if (BDRE->isByRef()) {
3641db7d04bSMike Stump         E = new (getContext())
365e302792bSJohn McCall           UnaryOperator(const_cast<Expr*>(E), UO_AddrOf,
3661db7d04bSMike Stump                         getContext().getPointerType(E->getType()),
3671db7d04bSMike Stump                         SourceLocation());
36897d01d50SMike Stump       }
3691db7d04bSMike Stump 
3707a626f63SJohn McCall       RValue r = EmitAnyExpr(E, AggValueSlot::forAddr(Addr, false, true));
37197d01d50SMike Stump       if (r.isScalar()) {
37297d01d50SMike Stump         llvm::Value *Loc = r.getScalarVal();
373950a9518SDavid Chisnall         const llvm::Type *Ty = Types[i+BlockFields];
37497d01d50SMike Stump         if  (BDRE->isByRef()) {
3752d33d630SMike Stump           // E is now the address of the value field, instead, we want the
3762d33d630SMike Stump           // address of the actual ByRef struct.  We optimize this slightly
3772d33d630SMike Stump           // compared to gcc by not grabbing the forwarding slot as this must
3782d33d630SMike Stump           // be done during Block_copy for us, and we can postpone the work
3792d33d630SMike Stump           // until then.
38040775003SKen Dyck           CharUnits offset = BlockDecls[BDRE->getDecl()];
3812d33d630SMike Stump 
3822d33d630SMike Stump           llvm::Value *BlockLiteral = LoadBlockStruct();
3832d33d630SMike Stump 
3842d33d630SMike Stump           Loc = Builder.CreateGEP(BlockLiteral,
3855e016ae9SChris Lattner                      llvm::ConstantInt::get(Int64Ty, offset.getQuantity()),
3862d33d630SMike Stump                                   "block.literal");
3879793f0e4SOwen Anderson           Ty = llvm::PointerType::get(Ty, 0);
38897d01d50SMike Stump           Loc = Builder.CreateBitCast(Loc, Ty);
389c76493a6SDaniel Dunbar           Loc = Builder.CreateLoad(Loc);
3902d33d630SMike Stump           // Loc = Builder.CreateBitCast(Loc, Ty);
39197d01d50SMike Stump         }
39297d01d50SMike Stump         Builder.CreateStore(Loc, Addr);
39397d01d50SMike Stump       } else if (r.isComplex())
394b750d928SMike Stump         // FIXME: implement
395b750d928SMike Stump         ErrorUnsupported(BE, "complex in block literal");
396b750d928SMike Stump       else if (r.isAggregate())
397b750d928SMike Stump         ; // Already created into the destination
398b750d928SMike Stump       else
399b750d928SMike Stump         assert (0 && "bad block variable");
400b750d928SMike Stump       // FIXME: Ensure that the offset created by the backend for
401b750d928SMike Stump       // the struct matches the previously computed offset in BlockDecls.
402b750d928SMike Stump     }
40387fe5d56SJohn McCall     NoteForHelper.resize(NumHelpers);
404d6ef62f0SMike Stump 
405d6ef62f0SMike Stump     // __descriptor
406c05349e5SFariborz Jahanian     llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE, Info, Ty,
407afa3c0a8SFariborz Jahanian                                                        BlockVarLayout,
408aeb0ffd5SMike Stump                                                        &NoteForHelper);
409aeb0ffd5SMike Stump     Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty);
410aeb0ffd5SMike Stump     Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp"));
411b750d928SMike Stump   }
412b750d928SMike Stump 
413b750d928SMike Stump   QualType BPT = BE->getType();
414989908fbSFariborz Jahanian   V = Builder.CreateBitCast(V, ConvertType(BPT));
415989908fbSFariborz Jahanian   // See if this is a __weak block variable and the must call objc_read_weak
416989908fbSFariborz Jahanian   // on it.
417989908fbSFariborz Jahanian   const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>();
418989908fbSFariborz Jahanian   QualType RES = ftype->getResultType();
419989908fbSFariborz Jahanian   if (RES.isObjCGCWeak()) {
420989908fbSFariborz Jahanian     // Must cast argument to id*
421989908fbSFariborz Jahanian     const llvm::Type *ObjectPtrTy =
422989908fbSFariborz Jahanian       ConvertType(CGM.getContext().getObjCIdType());
423989908fbSFariborz Jahanian     const llvm::Type *PtrObjectPtrTy =
424989908fbSFariborz Jahanian       llvm::PointerType::getUnqual(ObjectPtrTy);
425989908fbSFariborz Jahanian     V = Builder.CreateBitCast(V, PtrObjectPtrTy);
426989908fbSFariborz Jahanian     V =  CGM.getObjCRuntime().EmitObjCWeakRead(*this, V);
427989908fbSFariborz Jahanian   }
428989908fbSFariborz Jahanian   return V;
429b750d928SMike Stump }
43085284bacSMike Stump 
43185284bacSMike Stump 
43295435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() {
433650c932dSMike Stump   if (BlockDescriptorType)
434650c932dSMike Stump     return BlockDescriptorType;
4352437cbfaSAnders Carlsson 
4362437cbfaSAnders Carlsson   const llvm::Type *UnsignedLongTy =
437650c932dSMike Stump     getTypes().ConvertType(getContext().UnsignedLongTy);
4382437cbfaSAnders Carlsson 
4392437cbfaSAnders Carlsson   // struct __block_descriptor {
4402437cbfaSAnders Carlsson   //   unsigned long reserved;
4412437cbfaSAnders Carlsson   //   unsigned long block_size;
442fc83aa04SBlaine Garst   //
443fc83aa04SBlaine Garst   //   // later, the following will be added
444fc83aa04SBlaine Garst   //
445fc83aa04SBlaine Garst   //   struct {
446fc83aa04SBlaine Garst   //     void (*copyHelper)();
447fc83aa04SBlaine Garst   //     void (*copyHelper)();
448fc83aa04SBlaine Garst   //   } helpers;                // !!! optional
449fc83aa04SBlaine Garst   //
450fc83aa04SBlaine Garst   //   const char *signature;   // the block signature
451fc83aa04SBlaine Garst   //   const char *layout;      // reserved
4522437cbfaSAnders Carlsson   // };
453758428f4SOwen Anderson   BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(),
454758428f4SOwen Anderson                                               UnsignedLongTy,
4552437cbfaSAnders Carlsson                                               UnsignedLongTy,
4562437cbfaSAnders Carlsson                                               NULL);
4572437cbfaSAnders Carlsson 
458650c932dSMike Stump   getModule().addTypeName("struct.__block_descriptor",
459650c932dSMike Stump                           BlockDescriptorType);
4602437cbfaSAnders Carlsson 
461650c932dSMike Stump   return BlockDescriptorType;
4622437cbfaSAnders Carlsson }
4632437cbfaSAnders Carlsson 
46495435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() {
465005c9a62SMike Stump   if (GenericBlockLiteralType)
466005c9a62SMike Stump     return GenericBlockLiteralType;
4672437cbfaSAnders Carlsson 
4682437cbfaSAnders Carlsson   const llvm::Type *BlockDescPtrTy =
4699793f0e4SOwen Anderson     llvm::PointerType::getUnqual(getBlockDescriptorType());
4702437cbfaSAnders Carlsson 
47192bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
47292bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
47392bbd6d4SMike Stump 
4742437cbfaSAnders Carlsson   // struct __block_literal_generic {
4755d2534adSMike Stump   //   void *__isa;
4765d2534adSMike Stump   //   int __flags;
4775d2534adSMike Stump   //   int __reserved;
4785d2534adSMike Stump   //   void (*__invoke)(void *);
4795d2534adSMike Stump   //   struct __block_descriptor *__descriptor;
4802437cbfaSAnders Carlsson   // };
481758428f4SOwen Anderson   GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(),
482758428f4SOwen Anderson                                                   PtrToInt8Ty,
48392bbd6d4SMike Stump                                                   IntTy,
48492bbd6d4SMike Stump                                                   IntTy,
485626aecc4SMike Stump                                                   PtrToInt8Ty,
4862437cbfaSAnders Carlsson                                                   BlockDescPtrTy,
4872437cbfaSAnders Carlsson                                                   NULL);
4882437cbfaSAnders Carlsson 
489005c9a62SMike Stump   getModule().addTypeName("struct.__block_literal_generic",
490005c9a62SMike Stump                           GenericBlockLiteralType);
4912437cbfaSAnders Carlsson 
492005c9a62SMike Stump   return GenericBlockLiteralType;
4932437cbfaSAnders Carlsson }
4942437cbfaSAnders Carlsson 
4955d2534adSMike Stump 
496bfb3671bSAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E,
497bfb3671bSAnders Carlsson                                           ReturnValueSlot ReturnValue) {
4982437cbfaSAnders Carlsson   const BlockPointerType *BPT =
499c23c7e6aSTed Kremenek     E->getCallee()->getType()->getAs<BlockPointerType>();
5002437cbfaSAnders Carlsson 
5012437cbfaSAnders Carlsson   llvm::Value *Callee = EmitScalarExpr(E->getCallee());
5022437cbfaSAnders Carlsson 
5032437cbfaSAnders Carlsson   // Get a pointer to the generic block literal.
5042437cbfaSAnders Carlsson   const llvm::Type *BlockLiteralTy =
5059793f0e4SOwen Anderson     llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType());
5062437cbfaSAnders Carlsson 
5072437cbfaSAnders Carlsson   // Bitcast the callee to a block literal.
5082437cbfaSAnders Carlsson   llvm::Value *BlockLiteral =
5092437cbfaSAnders Carlsson     Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal");
5102437cbfaSAnders Carlsson 
5112437cbfaSAnders Carlsson   // Get the function pointer from the literal.
5122437cbfaSAnders Carlsson   llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp");
5132437cbfaSAnders Carlsson 
5142437cbfaSAnders Carlsson   BlockLiteral =
5152437cbfaSAnders Carlsson     Builder.CreateBitCast(BlockLiteral,
516abd5b90eSBenjamin Kramer                           llvm::Type::getInt8PtrTy(VMContext),
5172437cbfaSAnders Carlsson                           "tmp");
5182437cbfaSAnders Carlsson 
5192437cbfaSAnders Carlsson   // Add the block literal.
5202437cbfaSAnders Carlsson   QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy);
5212437cbfaSAnders Carlsson   CallArgList Args;
5222437cbfaSAnders Carlsson   Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy));
5232437cbfaSAnders Carlsson 
524479e6fc7SAnders Carlsson   QualType FnType = BPT->getPointeeType();
525479e6fc7SAnders Carlsson 
5262437cbfaSAnders Carlsson   // And the rest of the arguments.
5279dd450bbSJohn McCall   EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(),
528479e6fc7SAnders Carlsson                E->arg_begin(), E->arg_end());
5292437cbfaSAnders Carlsson 
5305f50c651SAnders Carlsson   // Load the function.
531c76493a6SDaniel Dunbar   llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp");
5325f50c651SAnders Carlsson 
533ab26cfa5SJohn McCall   const FunctionType *FuncTy = FnType->getAs<FunctionType>();
534ab26cfa5SJohn McCall   QualType ResultType = FuncTy->getResultType();
535a60cbcdfSAnders Carlsson 
536a60cbcdfSAnders Carlsson   const CGFunctionInfo &FnInfo =
537c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args,
538c50c27ccSRafael Espindola                                    FuncTy->getExtInfo());
5395f50c651SAnders Carlsson 
5405f50c651SAnders Carlsson   // Cast the function pointer to the right type.
5415f50c651SAnders Carlsson   const llvm::Type *BlockFTy =
542a60cbcdfSAnders Carlsson     CGM.getTypes().GetFunctionType(FnInfo, false);
5435f50c651SAnders Carlsson 
5449793f0e4SOwen Anderson   const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy);
5455f50c651SAnders Carlsson   Func = Builder.CreateBitCast(Func, BlockFTyPtr);
5465f50c651SAnders Carlsson 
5472437cbfaSAnders Carlsson   // And call the block.
548bfb3671bSAnders Carlsson   return EmitCall(FnInfo, Func, ReturnValue, Args);
5492437cbfaSAnders Carlsson }
5506a60fa24SAnders Carlsson 
55187fe5d56SJohn McCall void CodeGenFunction::AllocateBlockCXXThisPointer(const CXXThisExpr *E) {
55287fe5d56SJohn McCall   assert(BlockCXXThisOffset.isZero() && "already computed 'this' pointer");
55387fe5d56SJohn McCall 
55487fe5d56SJohn McCall   // Figure out what the offset is.
55587fe5d56SJohn McCall   QualType T = E->getType();
55687fe5d56SJohn McCall   std::pair<CharUnits,CharUnits> TypeInfo = getContext().getTypeInfoInChars(T);
55787fe5d56SJohn McCall   CharUnits Offset = getBlockOffset(TypeInfo.first, TypeInfo.second);
55887fe5d56SJohn McCall 
55987fe5d56SJohn McCall   BlockCXXThisOffset = Offset;
56087fe5d56SJohn McCall   BlockLayout.push_back(E);
56187fe5d56SJohn McCall }
56287fe5d56SJohn McCall 
56387fe5d56SJohn McCall void CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) {
5640168f4b2SAnders Carlsson   const ValueDecl *VD = E->getDecl();
56587fe5d56SJohn McCall   CharUnits &Offset = BlockDecls[VD];
5660168f4b2SAnders Carlsson 
56797d01d50SMike Stump   // See if we have already allocated an offset for this variable.
56887fe5d56SJohn McCall   if (!Offset.isZero())
56987fe5d56SJohn McCall     return;
5707fe9cc1dSMike Stump 
5714446dcf0SMike Stump   // Don't run the expensive check, unless we have to.
572e1b19ba0SMike Stump   if (!BlockHasCopyDispose)
573e1b19ba0SMike Stump     if (E->isByRef()
5742a5deb56SFariborz Jahanian         || BlockRequiresCopying(E))
5754446dcf0SMike Stump       BlockHasCopyDispose = true;
5767fe9cc1dSMike Stump 
57787fe5d56SJohn McCall   const ValueDecl *D = cast<ValueDecl>(E->getDecl());
5787fe9cc1dSMike Stump 
57987fe5d56SJohn McCall   CharUnits Size;
58087fe5d56SJohn McCall   CharUnits Align;
58187fe5d56SJohn McCall 
58287fe5d56SJohn McCall   if (E->isByRef()) {
58387fe5d56SJohn McCall     llvm::tie(Size,Align) =
58487fe5d56SJohn McCall       getContext().getTypeInfoInChars(getContext().VoidPtrTy);
58587fe5d56SJohn McCall   } else {
58687fe5d56SJohn McCall     Size = getContext().getTypeSizeInChars(D->getType());
58787fe5d56SJohn McCall     Align = getContext().getDeclAlign(D);
58887fe5d56SJohn McCall   }
58987fe5d56SJohn McCall 
59087fe5d56SJohn McCall   Offset = getBlockOffset(Size, Align);
59187fe5d56SJohn McCall   BlockLayout.push_back(E);
59297d01d50SMike Stump }
59397d01d50SMike Stump 
5949d42f0f1SJohn McCall llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const ValueDecl *VD,
5959d42f0f1SJohn McCall                                                  bool IsByRef) {
59664176c2cSFariborz Jahanian 
59787fe5d56SJohn McCall   CharUnits offset = BlockDecls[VD];
59887fe5d56SJohn McCall   assert(!offset.isZero() && "getting address of unallocated decl");
5997fe9cc1dSMike Stump 
60097d01d50SMike Stump   llvm::Value *BlockLiteral = LoadBlockStruct();
60197d01d50SMike Stump   llvm::Value *V = Builder.CreateGEP(BlockLiteral,
6025e016ae9SChris Lattner                        llvm::ConstantInt::get(Int64Ty, offset.getQuantity()),
6032d33d630SMike Stump                                      "block.literal");
6049d42f0f1SJohn McCall   if (IsByRef) {
60597d01d50SMike Stump     const llvm::Type *PtrStructTy
6060168f4b2SAnders Carlsson       = llvm::PointerType::get(BuildByRefType(VD), 0);
607efd7caa8SMike Stump     // The block literal will need a copy/destroy helper.
608efd7caa8SMike Stump     BlockHasCopyDispose = true;
6090168f4b2SAnders Carlsson 
6100168f4b2SAnders Carlsson     const llvm::Type *Ty = PtrStructTy;
6119793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
61297d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
613c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
61497d01d50SMike Stump     V = Builder.CreateStructGEP(V, 1, "forwarding");
615c76493a6SDaniel Dunbar     V = Builder.CreateLoad(V);
61697d01d50SMike Stump     V = Builder.CreateBitCast(V, PtrStructTy);
6170168f4b2SAnders Carlsson     V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD),
6180168f4b2SAnders Carlsson                                 VD->getNameAsString());
619eeb23379SFariborz Jahanian     if (VD->getType()->isReferenceType())
620eeb23379SFariborz Jahanian       V = Builder.CreateLoad(V);
62197d01d50SMike Stump   } else {
62256514161SJohn McCall     const llvm::Type *Ty = CGM.getTypes().ConvertTypeForMem(VD->getType());
6239793f0e4SOwen Anderson     Ty = llvm::PointerType::get(Ty, 0);
62497d01d50SMike Stump     V = Builder.CreateBitCast(V, Ty);
625d1b378e0SFariborz Jahanian     if (VD->getType()->isReferenceType())
62664176c2cSFariborz Jahanian       V = Builder.CreateLoad(V, "ref.tmp");
62797d01d50SMike Stump   }
62897d01d50SMike Stump   return V;
62997d01d50SMike Stump }
63097d01d50SMike Stump 
6312d5a2878SMike Stump llvm::Constant *
6326c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) {
6336a60fa24SAnders Carlsson   // Generate the block descriptor.
6346a60fa24SAnders Carlsson   const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy);
63592bbd6d4SMike Stump   const llvm::IntegerType *IntTy = cast<llvm::IntegerType>(
63692bbd6d4SMike Stump     getTypes().ConvertType(getContext().IntTy));
6376a60fa24SAnders Carlsson 
638fc83aa04SBlaine Garst   llvm::Constant *DescriptorFields[4];
6396a60fa24SAnders Carlsson 
6406a60fa24SAnders Carlsson   // Reserved
6410b75f23bSOwen Anderson   DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy);
6426a60fa24SAnders Carlsson 
6436a60fa24SAnders Carlsson   // Block literal size. For global blocks we just use the size of the generic
6446a60fa24SAnders Carlsson   // block literal struct.
64598ca7943SKen Dyck   CharUnits BlockLiteralSize =
64698ca7943SKen Dyck     CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType());
647170229f6SOwen Anderson   DescriptorFields[1] =
64840775003SKen Dyck     llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity());
6496a60fa24SAnders Carlsson 
650fc83aa04SBlaine Garst   // signature.  non-optional ObjC-style method descriptor @encode sequence
651fc83aa04SBlaine Garst   std::string BlockTypeEncoding;
652fc83aa04SBlaine Garst   CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding);
653fc83aa04SBlaine Garst 
654fc83aa04SBlaine Garst   DescriptorFields[2] = llvm::ConstantExpr::getBitCast(
655fc83aa04SBlaine Garst           CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty);
656fc83aa04SBlaine Garst 
657fc83aa04SBlaine Garst   // layout
658fc83aa04SBlaine Garst   DescriptorFields[3] =
659fc83aa04SBlaine Garst     llvm::ConstantInt::get(UnsignedLongTy,0);
660fc83aa04SBlaine Garst 
661fc83aa04SBlaine Garst   // build the structure from the 4 elements
6626a60fa24SAnders Carlsson   llvm::Constant *DescriptorStruct =
663fc83aa04SBlaine Garst     llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false);
6646a60fa24SAnders Carlsson 
6656a60fa24SAnders Carlsson   llvm::GlobalVariable *Descriptor =
666c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true,
6676a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
668c10c8d3eSOwen Anderson                              DescriptorStruct, "__block_descriptor_global");
6696a60fa24SAnders Carlsson 
670950a9518SDavid Chisnall   int FieldCount = 5;
6716a60fa24SAnders Carlsson   // Generate the constants for the block literal.
672950a9518SDavid Chisnall 
673950a9518SDavid Chisnall   std::vector<llvm::Constant*> LiteralFields(FieldCount);
6746a60fa24SAnders Carlsson 
6759d42f0f1SJohn McCall   CGBlockInfo Info(n);
676afa3c0a8SFariborz Jahanian   llvm::Constant *BlockVarLayout;
6775469f29aSMike Stump   llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
678cb2fbcb0SMike Stump   llvm::Function *Fn
679d5010898SFariborz Jahanian     = CodeGenFunction(CGM).GenerateBlockFunction(GlobalDecl(), BE,
680afa3c0a8SFariborz Jahanian                                                  Info, 0, BlockVarLayout,
681afa3c0a8SFariborz Jahanian                                                  LocalDeclMap);
6829d42f0f1SJohn McCall   assert(Info.BlockSize == BlockLiteralSize
683cb2fbcb0SMike Stump          && "no imports allowed for global block");
6846a60fa24SAnders Carlsson 
6856a60fa24SAnders Carlsson   // isa
686900546d2SDaniel Dunbar   LiteralFields[0] = CGM.getNSConcreteGlobalBlock();
6876a60fa24SAnders Carlsson 
688d5010898SFariborz Jahanian   // __flags
689d5010898SFariborz Jahanian   unsigned flags = computeBlockFlag(CGM, BE,
690d5010898SFariborz Jahanian                                     (BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE));
691fc83aa04SBlaine Garst   LiteralFields[1] =
692d5010898SFariborz Jahanian     llvm::ConstantInt::get(IntTy, flags);
6936a60fa24SAnders Carlsson 
6946a60fa24SAnders Carlsson   // Reserved
6950b75f23bSOwen Anderson   LiteralFields[2] = llvm::Constant::getNullValue(IntTy);
6966a60fa24SAnders Carlsson 
6976a60fa24SAnders Carlsson   // Function
6986a60fa24SAnders Carlsson   LiteralFields[3] = Fn;
6996a60fa24SAnders Carlsson 
7006a60fa24SAnders Carlsson   // Descriptor
7016a60fa24SAnders Carlsson   LiteralFields[4] = Descriptor;
7026a60fa24SAnders Carlsson 
7036a60fa24SAnders Carlsson   llvm::Constant *BlockLiteralStruct =
704950a9518SDavid Chisnall     llvm::ConstantStruct::get(VMContext, LiteralFields, false);
7056a60fa24SAnders Carlsson 
7066a60fa24SAnders Carlsson   llvm::GlobalVariable *BlockLiteral =
707c10c8d3eSOwen Anderson     new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true,
7086a60fa24SAnders Carlsson                              llvm::GlobalVariable::InternalLinkage,
709c10c8d3eSOwen Anderson                              BlockLiteralStruct, "__block_literal_global");
7106a60fa24SAnders Carlsson 
7116a60fa24SAnders Carlsson   return BlockLiteral;
7126a60fa24SAnders Carlsson }
7136a60fa24SAnders Carlsson 
714cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() {
71538382028SMike Stump   llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()],
71638382028SMike Stump                                       "self");
71738382028SMike Stump   // For now, we codegen based upon byte offsets.
71838382028SMike Stump   return Builder.CreateBitCast(V, PtrToInt8Ty);
719cb2fbcb0SMike Stump }
720cb2fbcb0SMike Stump 
7214446dcf0SMike Stump llvm::Function *
7229b5528d2SFariborz Jahanian CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, const BlockExpr *BExpr,
7239d42f0f1SJohn McCall                                        CGBlockInfo &Info,
724692c6e37SMike Stump                                        const Decl *OuterFuncDecl,
725afa3c0a8SFariborz Jahanian                                        llvm::Constant *& BlockVarLayout,
7269d42f0f1SJohn McCall                                   llvm::DenseMap<const Decl*, llvm::Value*> ldm) {
7279074ed8cSDevang Patel 
7289074ed8cSDevang Patel   // Check if we should generate debug info for this block.
7299074ed8cSDevang Patel   if (CGM.getDebugInfo())
7309074ed8cSDevang Patel     DebugInfo = CGM.getDebugInfo();
7319074ed8cSDevang Patel 
7325469f29aSMike Stump   // Arrange for local static and local extern declarations to appear
7335469f29aSMike Stump   // to be local to this function as well, as they are directly referenced
7345469f29aSMike Stump   // in a block.
7355469f29aSMike Stump   for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin();
7365469f29aSMike Stump        i != ldm.end();
7375469f29aSMike Stump        ++i) {
7385469f29aSMike Stump     const VarDecl *VD = dyn_cast<VarDecl>(i->first);
7395469f29aSMike Stump 
7408e7d656aSJohn McCall     if (VD->getStorageClass() == SC_Static || VD->hasExternalStorage())
7415469f29aSMike Stump       LocalDeclMap[VD] = i->second;
7425469f29aSMike Stump   }
7435469f29aSMike Stump 
74498ca7943SKen Dyck   BlockOffset =
74598ca7943SKen Dyck       CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType());
7465262b119SKen Dyck   BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
74709a9b6e3SEli Friedman 
748aae4349dSFariborz Jahanian   const FunctionType *BlockFunctionType = BExpr->getFunctionType();
749aae4349dSFariborz Jahanian   QualType ResultType;
750c50c27ccSRafael Espindola   FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType);
751aae4349dSFariborz Jahanian   bool IsVariadic;
752a4f6b6b1SFariborz Jahanian   if (const FunctionProtoType *FTy =
753a4f6b6b1SFariborz Jahanian       dyn_cast<FunctionProtoType>(BlockFunctionType)) {
754aae4349dSFariborz Jahanian     ResultType = FTy->getResultType();
755aae4349dSFariborz Jahanian     IsVariadic = FTy->isVariadic();
756658fe02dSMike Stump   } else {
757aae4349dSFariborz Jahanian     // K&R style block.
758aae4349dSFariborz Jahanian     ResultType = BlockFunctionType->getResultType();
759aae4349dSFariborz Jahanian     IsVariadic = false;
760aae4349dSFariborz Jahanian   }
7616a60fa24SAnders Carlsson 
7626a60fa24SAnders Carlsson   FunctionArgList Args;
7636a60fa24SAnders Carlsson 
7647fe9cc1dSMike Stump   CurFuncDecl = OuterFuncDecl;
7657fe9cc1dSMike Stump 
7663385fe12SChris Lattner   const BlockDecl *BD = BExpr->getBlockDecl();
7676a60fa24SAnders Carlsson 
7687fe9cc1dSMike Stump   IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor");
769d015328fSMike Stump 
77087fe5d56SJohn McCall   // Build the block struct now.
7719d42f0f1SJohn McCall   AllocateAllBlockDeclRefs(*this, Info);
7727fe9cc1dSMike Stump 
773afa3c0a8SFariborz Jahanian   // Capture block layout info. here.
774afa3c0a8SFariborz Jahanian   if (CGM.getContext().getLangOptions().ObjC1)
775933c6723SFariborz Jahanian     BlockVarLayout = CGM.getObjCRuntime().GCBlockLayout(*this, BlockLayout);
776afa3c0a8SFariborz Jahanian   else
777afa3c0a8SFariborz Jahanian     BlockVarLayout = llvm::Constant::getNullValue(PtrToInt8Ty);
778afa3c0a8SFariborz Jahanian 
779e1b19ba0SMike Stump   QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose,
78087fe5d56SJohn McCall                                                   BlockLayout);
78187fe5d56SJohn McCall 
7826a60fa24SAnders Carlsson   // FIXME: This leaks
7836a60fa24SAnders Carlsson   ImplicitParamDecl *SelfDecl =
7844d4dcc8eSJohn McCall     ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD),
785d015328fSMike Stump                               SourceLocation(), II,
786d015328fSMike Stump                               ParmTy);
7876a60fa24SAnders Carlsson 
7886a60fa24SAnders Carlsson   Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType()));
789cb2fbcb0SMike Stump   BlockStructDecl = SelfDecl;
7906a60fa24SAnders Carlsson 
791c4b30e59SSteve Naroff   for (BlockDecl::param_const_iterator i = BD->param_begin(),
7926a60fa24SAnders Carlsson        e = BD->param_end(); i != e; ++i)
793eecd39f2SMike Stump     Args.push_back(std::make_pair(*i, (*i)->getType()));
7946a60fa24SAnders Carlsson 
7956a60fa24SAnders Carlsson   const CGFunctionInfo &FI =
796c50c27ccSRafael Espindola     CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo);
7976a60fa24SAnders Carlsson 
7986a60fa24SAnders Carlsson   CodeGenTypes &Types = CGM.getTypes();
799aae4349dSFariborz Jahanian   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic);
8006a60fa24SAnders Carlsson 
8017e10f369SDouglas Gregor   MangleBuffer Name;
8029b5528d2SFariborz Jahanian   CGM.getMangledName(GD, Name, BD);
8036a60fa24SAnders Carlsson   llvm::Function *Fn =
80402df9da2SDouglas Gregor     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
80502df9da2SDouglas Gregor                            Name.getString(), &CGM.getModule());
8066a60fa24SAnders Carlsson 
807c3e7cff6SDaniel Dunbar   CGM.SetInternalFunctionAttributes(BD, Fn, FI);
808f7f020bbSFariborz Jahanian   StartFunction(BD, ResultType, Fn, Args,
809f7f020bbSFariborz Jahanian                 BExpr->getBody()->getLocEnd());
810f7f020bbSFariborz Jahanian 
811f7f020bbSFariborz Jahanian   CurFuncDecl = OuterFuncDecl;
812c3e7cff6SDaniel Dunbar 
81336ad0e99SFariborz Jahanian   QualType FnType(BlockFunctionType, 0);
814c42461e1SFariborz Jahanian   bool HasPrototype = isa<FunctionProtoType>(BlockFunctionType);
81536ad0e99SFariborz Jahanian 
81636ad0e99SFariborz Jahanian   IdentifierInfo *ID = &getContext().Idents.get(Name.getString());
81736ad0e99SFariborz Jahanian   CurCodeDecl = FunctionDecl::Create(getContext(),
81836ad0e99SFariborz Jahanian                                      getContext().getTranslationUnitDecl(),
81936ad0e99SFariborz Jahanian                                      SourceLocation(), ID, FnType,
82036ad0e99SFariborz Jahanian                                      0,
8218e7d656aSJohn McCall                                      SC_Static,
8228e7d656aSJohn McCall                                      SC_None,
82336ad0e99SFariborz Jahanian                                      false, HasPrototype);
824f7f020bbSFariborz Jahanian   if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FnType)) {
825f7f020bbSFariborz Jahanian     const FunctionDecl *CFD = dyn_cast<FunctionDecl>(CurCodeDecl);
826f7f020bbSFariborz Jahanian     FunctionDecl *FD = const_cast<FunctionDecl *>(CFD);
827f7f020bbSFariborz Jahanian     llvm::SmallVector<ParmVarDecl*, 16> Params;
828f7f020bbSFariborz Jahanian     for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
829f7f020bbSFariborz Jahanian       Params.push_back(ParmVarDecl::Create(getContext(), FD,
830f7f020bbSFariborz Jahanian                                            SourceLocation(), 0,
831f7f020bbSFariborz Jahanian                                            FT->getArgType(i), /*TInfo=*/0,
8328e7d656aSJohn McCall                                            SC_None, SC_None, 0));
833f7f020bbSFariborz Jahanian     FD->setParams(Params.data(), Params.size());
834f7f020bbSFariborz Jahanian   }
83536ad0e99SFariborz Jahanian 
836017460abSMike Stump 
83787fe5d56SJohn McCall   // If we have a C++ 'this' reference, go ahead and force it into
83887fe5d56SJohn McCall   // existence now.
83987fe5d56SJohn McCall   if (Info.CXXThisRef) {
84087fe5d56SJohn McCall     assert(!BlockCXXThisOffset.isZero() &&
84187fe5d56SJohn McCall            "haven't yet allocated 'this' reference");
84287fe5d56SJohn McCall 
84387fe5d56SJohn McCall     // TODO: I have a dream that one day this will be typed.
84487fe5d56SJohn McCall     llvm::Value *BlockLiteral = LoadBlockStruct();
84587fe5d56SJohn McCall     llvm::Value *ThisPtrRaw =
84687fe5d56SJohn McCall       Builder.CreateConstInBoundsGEP1_64(BlockLiteral,
84787fe5d56SJohn McCall                                          BlockCXXThisOffset.getQuantity(),
84887fe5d56SJohn McCall                                          "this.ptr.raw");
84987fe5d56SJohn McCall 
85087fe5d56SJohn McCall     const llvm::Type *Ty =
85187fe5d56SJohn McCall       CGM.getTypes().ConvertType(Info.CXXThisRef->getType());
85287fe5d56SJohn McCall     Ty = llvm::PointerType::get(Ty, 0);
85387fe5d56SJohn McCall     llvm::Value *ThisPtr = Builder.CreateBitCast(ThisPtrRaw, Ty, "this.ptr");
85487fe5d56SJohn McCall 
85587fe5d56SJohn McCall     CXXThisValue = Builder.CreateLoad(ThisPtr, "this");
85687fe5d56SJohn McCall   }
85787fe5d56SJohn McCall 
8589d42f0f1SJohn McCall   // If we have an Objective C 'self' reference, go ahead and force it
8599d42f0f1SJohn McCall   // into existence now.
8609d42f0f1SJohn McCall   if (Info.NeedsObjCSelf) {
8619d42f0f1SJohn McCall     ValueDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
8629d42f0f1SJohn McCall     LocalDeclMap[Self] = GetAddrOfBlockDecl(Self, false);
8639d42f0f1SJohn McCall   }
8649d42f0f1SJohn McCall 
865017460abSMike Stump   // Save a spot to insert the debug information for all the BlockDeclRefDecls.
866017460abSMike Stump   llvm::BasicBlock *entry = Builder.GetInsertBlock();
867017460abSMike Stump   llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint();
868017460abSMike Stump   --entry_ptr;
869017460abSMike Stump 
8703385fe12SChris Lattner   EmitStmt(BExpr->getBody());
871017460abSMike Stump 
8727d69911aSMike Stump   // Remember where we were...
8737d69911aSMike Stump   llvm::BasicBlock *resume = Builder.GetInsertBlock();
874017460abSMike Stump 
8757d69911aSMike Stump   // Go back to the entry.
876017460abSMike Stump   ++entry_ptr;
877017460abSMike Stump   Builder.SetInsertPoint(entry, entry_ptr);
878017460abSMike Stump 
8792e722b91SMike Stump   if (CGDebugInfo *DI = getDebugInfo()) {
8802e722b91SMike Stump     // Emit debug information for all the BlockDeclRefDecls.
88187fe5d56SJohn McCall     // FIXME: also for 'this'
88287fe5d56SJohn McCall     for (unsigned i = 0, e = BlockLayout.size(); i != e; ++i) {
883bf78478dSChris Lattner       if (const BlockDeclRefExpr *BDRE =
88487fe5d56SJohn McCall             dyn_cast<BlockDeclRefExpr>(BlockLayout[i])) {
8852e722b91SMike Stump         const ValueDecl *D = BDRE->getDecl();
8862e722b91SMike Stump         DI->setLocation(D->getLocation());
8872e722b91SMike Stump         DI->EmitDeclareOfBlockDeclRefVariable(BDRE,
8882e722b91SMike Stump                                              LocalDeclMap[getBlockStructDecl()],
8892e722b91SMike Stump                                               Builder, this);
8902e722b91SMike Stump       }
8912e722b91SMike Stump     }
8922e722b91SMike Stump   }
8937d69911aSMike Stump   // And resume where we left off.
8947d69911aSMike Stump   if (resume == 0)
8957d69911aSMike Stump     Builder.ClearInsertionPoint();
8967d69911aSMike Stump   else
8977d69911aSMike Stump     Builder.SetInsertPoint(resume);
8982e722b91SMike Stump 
8993385fe12SChris Lattner   FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc());
9006a60fa24SAnders Carlsson 
901b750d928SMike Stump   // The runtime needs a minimum alignment of a void *.
9025262b119SKen Dyck   CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy);
90340775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
9045262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(),
9055262b119SKen Dyck                                MinAlign.getQuantity()));
906b750d928SMike Stump 
9079d42f0f1SJohn McCall   Info.BlockSize = BlockOffset;
9089d42f0f1SJohn McCall   Info.BlockAlign = BlockAlign;
9099d42f0f1SJohn McCall   Info.BlockLayout = BlockLayout;
9109d42f0f1SJohn McCall   Info.BlockHasCopyDispose = BlockHasCopyDispose;
9116a60fa24SAnders Carlsson   return Fn;
9126a60fa24SAnders Carlsson }
9131db7d04bSMike Stump 
91487fe5d56SJohn McCall CharUnits BlockFunction::getBlockOffset(CharUnits Size, CharUnits Align) {
9155262b119SKen Dyck   assert((Align.isPositive()) && "alignment must be 1 byte or more");
9161db7d04bSMike Stump 
91740775003SKen Dyck   CharUnits OldOffset = BlockOffset;
9181db7d04bSMike Stump 
9191db7d04bSMike Stump   // Ensure proper alignment, even if it means we have to have a gap
92040775003SKen Dyck   BlockOffset = CharUnits::fromQuantity(
9215262b119SKen Dyck       llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity()));
9221db7d04bSMike Stump   BlockAlign = std::max(Align, BlockAlign);
9231db7d04bSMike Stump 
92440775003SKen Dyck   CharUnits Pad = BlockOffset - OldOffset;
92540775003SKen Dyck   if (Pad.isPositive()) {
9261db7d04bSMike Stump     QualType PadTy = getContext().getConstantArrayType(getContext().CharTy,
92740775003SKen Dyck                                                        llvm::APInt(32,
92840775003SKen Dyck                                                          Pad.getQuantity()),
9291db7d04bSMike Stump                                                        ArrayType::Normal, 0);
9306a047c97SDouglas Gregor     ValueDecl *PadDecl = VarDecl::Create(getContext(),
9316a047c97SDouglas Gregor                                          getContext().getTranslationUnitDecl(),
9326a047c97SDouglas Gregor                                          SourceLocation(),
933c4df4076SDouglas Gregor                                          0, QualType(PadTy), 0,
9348e7d656aSJohn McCall                                          SC_None, SC_None);
93587fe5d56SJohn McCall     Expr *E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(),
936ed6c7440SDouglas Gregor                                              SourceLocation());
93787fe5d56SJohn McCall     BlockLayout.push_back(E);
9381db7d04bSMike Stump   }
9391db7d04bSMike Stump 
9401db7d04bSMike Stump   BlockOffset += Size;
9411db7d04bSMike Stump   return BlockOffset - Size;
9421db7d04bSMike Stump }
94397d01d50SMike Stump 
944aeb0ffd5SMike Stump llvm::Constant *BlockFunction::
945aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T,
94667645930SMike Stump                            std::vector<HelperInfo> *NoteForHelperp) {
9470c743277SMike Stump   QualType R = getContext().VoidTy;
9480c743277SMike Stump 
9490c743277SMike Stump   FunctionArgList Args;
9500c743277SMike Stump   // FIXME: This leaks
951aeb0ffd5SMike Stump   ImplicitParamDecl *Dst =
9527fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9537fe9cc1dSMike Stump                               SourceLocation(), 0,
954aeb0ffd5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
955aeb0ffd5SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
9560c743277SMike Stump   ImplicitParamDecl *Src =
9577fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
9587fe9cc1dSMike Stump                               SourceLocation(), 0,
9590c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
9600c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
9610c743277SMike Stump 
9620c743277SMike Stump   const CGFunctionInfo &FI =
963c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
9640c743277SMike Stump 
965cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
966cbc2bcafSMike Stump   // internal linkage.
9670c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
9680c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
9690c743277SMike Stump 
9700c743277SMike Stump   llvm::Function *Fn =
9710c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
972d6b28fc6SBenjamin Kramer                            "__copy_helper_block_", &CGM.getModule());
9730c743277SMike Stump 
9740c743277SMike Stump   IdentifierInfo *II
9750c743277SMike Stump     = &CGM.getContext().Idents.get("__copy_helper_block_");
9760c743277SMike Stump 
9770c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
9780c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
97960ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
9808e7d656aSJohn McCall                                           SC_Static,
9818e7d656aSJohn McCall                                           SC_None,
982c4df4076SDouglas Gregor                                           false,
9830c743277SMike Stump                                           true);
9840c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
985aeb0ffd5SMike Stump 
986aeb0ffd5SMike Stump   llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
987aeb0ffd5SMike Stump   llvm::Type *PtrPtrT;
98867645930SMike Stump 
98967645930SMike Stump   if (NoteForHelperp) {
99067645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
99167645930SMike Stump 
9929793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
993aeb0ffd5SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
994aeb0ffd5SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
995aeb0ffd5SMike Stump 
996aeb0ffd5SMike Stump     llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst);
9973b65ac26SMike Stump     llvm::Type *PtrPtrT;
9989793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
9993b65ac26SMike Stump     DstObj = Builder.CreateBitCast(DstObj, PtrPtrT);
10003b65ac26SMike Stump     DstObj = Builder.CreateLoad(DstObj);
1001aeb0ffd5SMike Stump 
1002aeb0ffd5SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
1003aeb0ffd5SMike Stump       int flag = NoteForHelper[i].flag;
1004aeb0ffd5SMike Stump       int index = NoteForHelper[i].index;
1005aeb0ffd5SMike Stump 
1006aeb0ffd5SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
1007aeb0ffd5SMike Stump           || NoteForHelper[i].RequiresCopying) {
1008aeb0ffd5SMike Stump         llvm::Value *Srcv = SrcObj;
1009aeb0ffd5SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
1010aeb0ffd5SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
10119793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
1012aeb0ffd5SMike Stump         llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index);
1013e988bdacSFariborz Jahanian         if (NoteForHelper[i].cxxvar_import) {
1014e988bdacSFariborz Jahanian           CGF.EmitSynthesizedCXXCopyCtor(Dstv, Srcv,
1015e988bdacSFariborz Jahanian                                          NoteForHelper[i].cxxvar_import);
1016e988bdacSFariborz Jahanian         }
1017e988bdacSFariborz Jahanian         else {
1018e988bdacSFariborz Jahanian           Srcv = Builder.CreateLoad(Srcv);
1019aeb0ffd5SMike Stump           Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty);
10205e016ae9SChris Lattner           llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1021900546d2SDaniel Dunbar           llvm::Value *F = CGM.getBlockObjectAssign();
1022aeb0ffd5SMike Stump           Builder.CreateCall3(F, Dstv, Srcv, N);
1023aeb0ffd5SMike Stump         }
1024aeb0ffd5SMike Stump       }
102567645930SMike Stump     }
1026e988bdacSFariborz Jahanian   }
1027aeb0ffd5SMike Stump 
10280c743277SMike Stump   CGF.FinishFunction();
10290c743277SMike Stump 
1030ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
103197d01d50SMike Stump }
103297d01d50SMike Stump 
1033d6ef62f0SMike Stump llvm::Constant *BlockFunction::
1034aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose,
1035aeb0ffd5SMike Stump                               const llvm::StructType* T,
103667645930SMike Stump                               std::vector<HelperInfo> *NoteForHelperp) {
10370c743277SMike Stump   QualType R = getContext().VoidTy;
10380c743277SMike Stump 
10390c743277SMike Stump   FunctionArgList Args;
10400c743277SMike Stump   // FIXME: This leaks
10410c743277SMike Stump   ImplicitParamDecl *Src =
10427fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
10437fe9cc1dSMike Stump                               SourceLocation(), 0,
10440c743277SMike Stump                               getContext().getPointerType(getContext().VoidTy));
10450c743277SMike Stump 
10460c743277SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
10470c743277SMike Stump 
10480c743277SMike Stump   const CGFunctionInfo &FI =
1049c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
10500c743277SMike Stump 
1051cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1052cbc2bcafSMike Stump   // internal linkage.
10530c743277SMike Stump   CodeGenTypes &Types = CGM.getTypes();
10540c743277SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
10550c743277SMike Stump 
10560c743277SMike Stump   llvm::Function *Fn =
10570c743277SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1058d6b28fc6SBenjamin Kramer                            "__destroy_helper_block_", &CGM.getModule());
10590c743277SMike Stump 
10600c743277SMike Stump   IdentifierInfo *II
10610c743277SMike Stump     = &CGM.getContext().Idents.get("__destroy_helper_block_");
10620c743277SMike Stump 
10630c743277SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
10640c743277SMike Stump                                           getContext().getTranslationUnitDecl(),
106560ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
10668e7d656aSJohn McCall                                           SC_Static,
10678e7d656aSJohn McCall                                           SC_None,
1068c4df4076SDouglas Gregor                                           false, true);
10690c743277SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
10706f7d9f87SMike Stump 
107167645930SMike Stump   if (NoteForHelperp) {
107267645930SMike Stump     std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp;
107367645930SMike Stump 
10746f7d9f87SMike Stump     llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src);
10756f7d9f87SMike Stump     llvm::Type *PtrPtrT;
10769793f0e4SOwen Anderson     PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0);
10776f7d9f87SMike Stump     SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT);
10786f7d9f87SMike Stump     SrcObj = Builder.CreateLoad(SrcObj);
1079e988bdacSFariborz Jahanian     EHScopeStack::stable_iterator CleanupDepth = CGF.EHStack.stable_begin();
10806f7d9f87SMike Stump     for (unsigned i=0; i < NoteForHelper.size(); ++i) {
10816f7d9f87SMike Stump       int flag = NoteForHelper[i].flag;
10826f7d9f87SMike Stump       int index = NoteForHelper[i].index;
10836f7d9f87SMike Stump 
10846f7d9f87SMike Stump       if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF)
10856f7d9f87SMike Stump           || NoteForHelper[i].RequiresCopying) {
10866f7d9f87SMike Stump         llvm::Value *Srcv = SrcObj;
10876f7d9f87SMike Stump         Srcv = Builder.CreateStructGEP(Srcv, index);
10886f7d9f87SMike Stump         Srcv = Builder.CreateBitCast(Srcv,
10899793f0e4SOwen Anderson                                      llvm::PointerType::get(PtrToInt8Ty, 0));
1090e988bdacSFariborz Jahanian         if (NoteForHelper[i].cxxvar_import) {
1091e988bdacSFariborz Jahanian           const BlockDeclRefExpr *BDRE = NoteForHelper[i].cxxvar_import;
1092e988bdacSFariborz Jahanian           const Expr *E = BDRE->getCopyConstructorExpr();
1093e988bdacSFariborz Jahanian           QualType ClassTy = E->getType();
1094e988bdacSFariborz Jahanian           QualType PtrClassTy = getContext().getPointerType(ClassTy);
1095e988bdacSFariborz Jahanian           const llvm::Type *t = CGM.getTypes().ConvertType(PtrClassTy);
1096e988bdacSFariborz Jahanian           Srcv = Builder.CreateBitCast(Srcv, t);
1097e988bdacSFariborz Jahanian           CGF.PushDestructorCleanup(ClassTy, Srcv);
1098e988bdacSFariborz Jahanian         }
1099e988bdacSFariborz Jahanian         else {
11006f7d9f87SMike Stump           Srcv = Builder.CreateLoad(Srcv);
11016f7d9f87SMike Stump           BuildBlockRelease(Srcv, flag);
11026f7d9f87SMike Stump         }
11036f7d9f87SMike Stump       }
110467645930SMike Stump     }
1105e988bdacSFariborz Jahanian     CGF.PopCleanupBlocks(CleanupDepth);
1106e988bdacSFariborz Jahanian   }
11076f7d9f87SMike Stump 
11080c743277SMike Stump   CGF.FinishFunction();
11090c743277SMike Stump 
1110ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
11110c743277SMike Stump }
11120c743277SMike Stump 
1113aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T,
111467645930SMike Stump                                        std::vector<HelperInfo> *NoteForHelper) {
1115aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose,
1116aeb0ffd5SMike Stump                                                          T, NoteForHelper);
11170c743277SMike Stump }
11180c743277SMike Stump 
1119aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T,
112067645930SMike Stump                                       std::vector<HelperInfo> *NoteForHelperp) {
1121aeb0ffd5SMike Stump   return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose,
112267645930SMike Stump                                                             T, NoteForHelperp);
112397d01d50SMike Stump }
1124626aecc4SMike Stump 
1125f89230d9SMike Stump llvm::Constant *BlockFunction::
1126f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) {
1127ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1128ee2a5ee5SMike Stump 
1129ee2a5ee5SMike Stump   FunctionArgList Args;
1130ee2a5ee5SMike Stump   // FIXME: This leaks
1131f89230d9SMike Stump   ImplicitParamDecl *Dst =
11327fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11337fe9cc1dSMike Stump                               SourceLocation(), 0,
1134f89230d9SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1135f89230d9SMike Stump   Args.push_back(std::make_pair(Dst, Dst->getType()));
1136f89230d9SMike Stump 
1137f89230d9SMike Stump   // FIXME: This leaks
1138ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
11397fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
11407fe9cc1dSMike Stump                               SourceLocation(), 0,
1141ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1142ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1143ee2a5ee5SMike Stump 
1144ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1145c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1146ee2a5ee5SMike Stump 
1147ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1148ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1149ee2a5ee5SMike Stump 
1150cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1151cbc2bcafSMike Stump   // internal linkage.
1152ee2a5ee5SMike Stump   llvm::Function *Fn =
1153ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1154d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_copy_", &CGM.getModule());
1155ee2a5ee5SMike Stump 
1156ee2a5ee5SMike Stump   IdentifierInfo *II
1157ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_");
1158ee2a5ee5SMike Stump 
1159ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1160ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
116160ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
11628e7d656aSJohn McCall                                           SC_Static,
11638e7d656aSJohn McCall                                           SC_None,
1164c4df4076SDouglas Gregor                                           false, true);
1165ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1166f89230d9SMike Stump 
1167f89230d9SMike Stump   // dst->x
1168f89230d9SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Dst);
11699793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
11703b65ac26SMike Stump   V = Builder.CreateLoad(V);
1171f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
1172f89230d9SMike Stump   llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty);
1173f89230d9SMike Stump 
1174f89230d9SMike Stump   // src->x
1175f89230d9SMike Stump   V = CGF.GetAddrOfLocalVar(Src);
1176f89230d9SMike Stump   V = Builder.CreateLoad(V);
1177f89230d9SMike Stump   V = Builder.CreateBitCast(V, T);
1178f89230d9SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
11799793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
1180f89230d9SMike Stump   llvm::Value *SrcObj = Builder.CreateLoad(V);
1181f89230d9SMike Stump 
1182f89230d9SMike Stump   flag |= BLOCK_BYREF_CALLER;
1183f89230d9SMike Stump 
11845e016ae9SChris Lattner   llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1185900546d2SDaniel Dunbar   llvm::Value *F = CGM.getBlockObjectAssign();
1186f89230d9SMike Stump   Builder.CreateCall3(F, DstObj, SrcObj, N);
1187f89230d9SMike Stump 
1188ee2a5ee5SMike Stump   CGF.FinishFunction();
1189ee2a5ee5SMike Stump 
1190ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1191ee2a5ee5SMike Stump }
1192ee2a5ee5SMike Stump 
1193fbe25dd1SMike Stump llvm::Constant *
1194fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T,
1195fbe25dd1SMike Stump                                                   int flag) {
1196ee2a5ee5SMike Stump   QualType R = getContext().VoidTy;
1197ee2a5ee5SMike Stump 
1198ee2a5ee5SMike Stump   FunctionArgList Args;
1199ee2a5ee5SMike Stump   // FIXME: This leaks
1200ee2a5ee5SMike Stump   ImplicitParamDecl *Src =
12017fe9cc1dSMike Stump     ImplicitParamDecl::Create(getContext(), 0,
12027fe9cc1dSMike Stump                               SourceLocation(), 0,
1203ee2a5ee5SMike Stump                               getContext().getPointerType(getContext().VoidTy));
1204ee2a5ee5SMike Stump 
1205ee2a5ee5SMike Stump   Args.push_back(std::make_pair(Src, Src->getType()));
1206ee2a5ee5SMike Stump 
1207ee2a5ee5SMike Stump   const CGFunctionInfo &FI =
1208c50c27ccSRafael Espindola       CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo());
1209ee2a5ee5SMike Stump 
1210ee2a5ee5SMike Stump   CodeGenTypes &Types = CGM.getTypes();
1211ee2a5ee5SMike Stump   const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false);
1212ee2a5ee5SMike Stump 
1213cbc2bcafSMike Stump   // FIXME: We'd like to put these into a mergable by content, with
1214cbc2bcafSMike Stump   // internal linkage.
1215ee2a5ee5SMike Stump   llvm::Function *Fn =
1216ee2a5ee5SMike Stump     llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
1217d6b28fc6SBenjamin Kramer                            "__Block_byref_id_object_dispose_",
1218ee2a5ee5SMike Stump                            &CGM.getModule());
1219ee2a5ee5SMike Stump 
1220ee2a5ee5SMike Stump   IdentifierInfo *II
1221ee2a5ee5SMike Stump     = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_");
1222ee2a5ee5SMike Stump 
1223ee2a5ee5SMike Stump   FunctionDecl *FD = FunctionDecl::Create(getContext(),
1224ee2a5ee5SMike Stump                                           getContext().getTranslationUnitDecl(),
122560ed5604SArgyrios Kyrtzidis                                           SourceLocation(), II, R, 0,
12268e7d656aSJohn McCall                                           SC_Static,
12278e7d656aSJohn McCall                                           SC_None,
1228c4df4076SDouglas Gregor                                           false, true);
1229ee2a5ee5SMike Stump   CGF.StartFunction(FD, R, Fn, Args, SourceLocation());
1230fbe25dd1SMike Stump 
1231fbe25dd1SMike Stump   llvm::Value *V = CGF.GetAddrOfLocalVar(Src);
12329793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0));
12333b65ac26SMike Stump   V = Builder.CreateLoad(V);
1234fbe25dd1SMike Stump   V = Builder.CreateStructGEP(V, 6, "x");
12359793f0e4SOwen Anderson   V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0));
12363b65ac26SMike Stump   V = Builder.CreateLoad(V);
1237fbe25dd1SMike Stump 
1238fbe25dd1SMike Stump   flag |= BLOCK_BYREF_CALLER;
1239fbe25dd1SMike Stump   BuildBlockRelease(V, flag);
1240ee2a5ee5SMike Stump   CGF.FinishFunction();
1241ee2a5ee5SMike Stump 
1242ade90fd1SOwen Anderson   return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty);
1243ee2a5ee5SMike Stump }
1244ee2a5ee5SMike Stump 
1245f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T,
1246e08ea787SChris Lattner                                                     int Flag, unsigned Align) {
1247e08ea787SChris Lattner   // All alignments below that of pointer alignment collapse down to just
1248cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1249cbc2bcafSMike Stump   // with.
1250cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1251e08ea787SChris Lattner 
1252cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1253cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1254cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1255e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1256e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.AssignCache[Kind];
1257cbc2bcafSMike Stump   if (Entry)
1258cbc2bcafSMike Stump     return Entry;
1259e08ea787SChris Lattner   return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag);
1260ee2a5ee5SMike Stump }
1261ee2a5ee5SMike Stump 
1262fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T,
1263e08ea787SChris Lattner                                                        int Flag,
1264cbc2bcafSMike Stump                                                        unsigned Align) {
1265cbc2bcafSMike Stump   // All alignments below that of pointer alignment collpase down to just
1266cbc2bcafSMike Stump   // pointer alignment, as we always have at least that much alignment to begin
1267cbc2bcafSMike Stump   // with.
1268cbc2bcafSMike Stump   Align /= unsigned(CGF.Target.getPointerAlign(0)/8);
1269e08ea787SChris Lattner 
1270cbc2bcafSMike Stump   // As an optimization, we only generate a single function of each kind we
1271cbc2bcafSMike Stump   // might need.  We need a different one for each alignment and for each
1272cbc2bcafSMike Stump   // setting of flags.  We mix Align and flag to get the kind.
1273e08ea787SChris Lattner   uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag;
1274e08ea787SChris Lattner   llvm::Constant *&Entry = CGM.DestroyCache[Kind];
1275cbc2bcafSMike Stump   if (Entry)
1276cbc2bcafSMike Stump     return Entry;
1277e08ea787SChris Lattner   return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag);
1278ee2a5ee5SMike Stump }
1279ee2a5ee5SMike Stump 
1280fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) {
1281900546d2SDaniel Dunbar   llvm::Value *F = CGM.getBlockObjectDispose();
1282fbe25dd1SMike Stump   llvm::Value *N;
1283626aecc4SMike Stump   V = Builder.CreateBitCast(V, PtrToInt8Ty);
12845e016ae9SChris Lattner   N = llvm::ConstantInt::get(CGF.Int32Ty, flag);
1285626aecc4SMike Stump   Builder.CreateCall2(F, V, N);
1286626aecc4SMike Stump }
12874446dcf0SMike Stump 
12884446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); }
1289aeb0ffd5SMike Stump 
1290aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf,
1291aeb0ffd5SMike Stump                              CGBuilderTy &B)
12925e016ae9SChris Lattner   : CGM(cgm), VMContext(cgm.getLLVMContext()), CGF(cgf), Builder(B) {
129341a75027SOwen Anderson   PtrToInt8Ty = llvm::PointerType::getUnqual(
129441a75027SOwen Anderson             llvm::Type::getInt8Ty(VMContext));
1295aeb0ffd5SMike Stump 
1296aeb0ffd5SMike Stump   BlockHasCopyDispose = false;
1297aeb0ffd5SMike Stump }
1298