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) 289d42f0f1SJohn McCall : Name(N), CXXThisRef(0), NeedsObjCSelf(false) { 299d42f0f1SJohn McCall 309d42f0f1SJohn McCall // Skip asm prefix, if any. 319d42f0f1SJohn McCall if (Name && Name[0] == '\01') 329d42f0f1SJohn McCall ++Name; 339d42f0f1SJohn McCall } 349d42f0f1SJohn McCall 359d42f0f1SJohn McCall 36d6ef62f0SMike Stump llvm::Constant *CodeGenFunction:: 37c05349e5SFariborz Jahanian BuildDescriptorBlockDecl(const BlockExpr *BE, const CGBlockInfo &Info, 38d2142cffSMike Stump const llvm::StructType* Ty, 39afa3c0a8SFariborz Jahanian llvm::Constant *BlockVarLayout, 40aeb0ffd5SMike Stump std::vector<HelperInfo> *NoteForHelper) { 41c05349e5SFariborz Jahanian bool BlockHasCopyDispose = Info.BlockHasCopyDispose; 42c05349e5SFariborz Jahanian CharUnits Size = Info.BlockSize; 43c2c38331SMike Stump const llvm::Type *UnsignedLongTy 44c2c38331SMike Stump = CGM.getTypes().ConvertType(getContext().UnsignedLongTy); 4585284bacSMike Stump llvm::Constant *C; 4685284bacSMike Stump std::vector<llvm::Constant*> Elts; 4785284bacSMike Stump 4885284bacSMike Stump // reserved 49b7a2fe6fSOwen Anderson C = llvm::ConstantInt::get(UnsignedLongTy, 0); 5085284bacSMike Stump Elts.push_back(C); 5185284bacSMike Stump 5285284bacSMike Stump // Size 532ac40a9fSMike Stump // FIXME: What is the right way to say this doesn't fit? We should give 542ac40a9fSMike Stump // a user diagnostic in that case. Better fix would be to change the 552ac40a9fSMike Stump // API to size_t. 5640775003SKen Dyck C = llvm::ConstantInt::get(UnsignedLongTy, Size.getQuantity()); 5785284bacSMike Stump Elts.push_back(C); 5885284bacSMike Stump 59fc83aa04SBlaine Garst // optional copy/dispose helpers 6085284bacSMike Stump if (BlockHasCopyDispose) { 6185284bacSMike Stump // copy_func_helper_decl 6267645930SMike Stump Elts.push_back(BuildCopyHelper(Ty, NoteForHelper)); 6385284bacSMike Stump 6485284bacSMike Stump // destroy_func_decl 6567645930SMike Stump Elts.push_back(BuildDestroyHelper(Ty, NoteForHelper)); 6685284bacSMike Stump } 6785284bacSMike Stump 68fc83aa04SBlaine Garst // Signature. non-optional ObjC-style method descriptor @encode sequence 69fc83aa04SBlaine Garst std::string BlockTypeEncoding; 70fc83aa04SBlaine Garst CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding); 71fc83aa04SBlaine Garst 72fc83aa04SBlaine Garst Elts.push_back(llvm::ConstantExpr::getBitCast( 73fc83aa04SBlaine Garst CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty)); 74fc83aa04SBlaine Garst 75fc83aa04SBlaine Garst // Layout. 76afa3c0a8SFariborz Jahanian C = BlockVarLayout; 77c05349e5SFariborz Jahanian 78fc83aa04SBlaine Garst Elts.push_back(C); 79fc83aa04SBlaine Garst 8041eaf0acSNick Lewycky C = llvm::ConstantStruct::get(VMContext, Elts, false); 8185284bacSMike Stump 82c10c8d3eSOwen Anderson C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true, 8385284bacSMike Stump llvm::GlobalValue::InternalLinkage, 84c10c8d3eSOwen Anderson C, "__block_descriptor_tmp"); 8585284bacSMike Stump return C; 8685284bacSMike Stump } 8785284bacSMike Stump 889d42f0f1SJohn McCall static void CollectBlockDeclRefInfo(const Stmt *S, CGBlockInfo &Info) { 89ed5e69feSAnders Carlsson for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end(); 90ed5e69feSAnders Carlsson I != E; ++I) 91dd942713SDaniel Dunbar if (*I) 929d42f0f1SJohn McCall CollectBlockDeclRefInfo(*I, Info); 93ed5e69feSAnders Carlsson 947fe9cc1dSMike Stump // We want to ensure we walk down into block literals so we can find 957fe9cc1dSMike Stump // all nested BlockDeclRefExprs. 96066b6166SMike Stump if (const BlockExpr *BE = dyn_cast<BlockExpr>(S)) { 979d42f0f1SJohn McCall Info.InnerBlocks.insert(BE->getBlockDecl()); 989d42f0f1SJohn McCall CollectBlockDeclRefInfo(BE->getBody(), Info); 99066b6166SMike Stump } 1007fe9cc1dSMike Stump 1019d42f0f1SJohn McCall else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) { 1029d42f0f1SJohn McCall const ValueDecl *D = BDRE->getDecl(); 103ed5e69feSAnders Carlsson // FIXME: Handle enums. 1049d42f0f1SJohn McCall if (isa<FunctionDecl>(D)) 105ed5e69feSAnders Carlsson return; 106ed5e69feSAnders Carlsson 1079d42f0f1SJohn McCall if (isa<ImplicitParamDecl>(D) && 1089d42f0f1SJohn McCall isa<ObjCMethodDecl>(D->getDeclContext()) && 1099d42f0f1SJohn McCall cast<ObjCMethodDecl>(D->getDeclContext())->getSelfDecl() == D) { 1109d42f0f1SJohn McCall Info.NeedsObjCSelf = true; 1119d42f0f1SJohn McCall return; 1129d42f0f1SJohn McCall } 1139d42f0f1SJohn McCall 114066b6166SMike Stump // Only Decls that escape are added. 1159d42f0f1SJohn McCall if (!Info.InnerBlocks.count(D->getDeclContext())) 116066b6166SMike Stump Info.DeclRefs.push_back(BDRE); 117ed5e69feSAnders Carlsson } 11887fe5d56SJohn McCall 1199d42f0f1SJohn McCall // Make sure to capture implicit 'self' references due to super calls. 1207ea01c3fSChandler Carruth else if (const ObjCMessageExpr *E = dyn_cast<ObjCMessageExpr>(S)) { 1219d42f0f1SJohn McCall if (E->getReceiverKind() == ObjCMessageExpr::SuperClass || 1229d42f0f1SJohn McCall E->getReceiverKind() == ObjCMessageExpr::SuperInstance) 1239d42f0f1SJohn McCall Info.NeedsObjCSelf = true; 1247ea01c3fSChandler Carruth } 1259d42f0f1SJohn McCall 1269d42f0f1SJohn McCall // Getter/setter uses may also cause implicit super references, 1279d42f0f1SJohn McCall // which we can check for with: 1289d42f0f1SJohn McCall else if (isa<ObjCSuperExpr>(S)) 1299d42f0f1SJohn McCall Info.NeedsObjCSelf = true; 1309d42f0f1SJohn McCall 1319d42f0f1SJohn McCall else if (isa<CXXThisExpr>(S)) 13287fe5d56SJohn McCall Info.CXXThisRef = cast<CXXThisExpr>(S); 133ed5e69feSAnders Carlsson } 134ed5e69feSAnders Carlsson 1359d42f0f1SJohn McCall /// CanBlockBeGlobal - Given a CGBlockInfo struct, determines if a block can be 1362d33d630SMike Stump /// declared as a global variable instead of on the stack. 1379d42f0f1SJohn McCall static bool CanBlockBeGlobal(const CGBlockInfo &Info) { 1387fe9cc1dSMike Stump return Info.DeclRefs.empty(); 1397fe9cc1dSMike Stump } 1407fe9cc1dSMike Stump 1417fe9cc1dSMike Stump /// AllocateAllBlockDeclRefs - Preallocate all nested BlockDeclRefExprs to 1427fe9cc1dSMike Stump /// ensure we can generate the debug information for the parameter for the block 1437fe9cc1dSMike Stump /// invoke function. 1449d42f0f1SJohn McCall static void AllocateAllBlockDeclRefs(CodeGenFunction &CGF, CGBlockInfo &Info) { 14587fe5d56SJohn McCall if (Info.CXXThisRef) 1469d42f0f1SJohn McCall CGF.AllocateBlockCXXThisPointer(Info.CXXThisRef); 1477fe9cc1dSMike Stump 1487fe9cc1dSMike Stump for (size_t i = 0; i < Info.DeclRefs.size(); ++i) 1499d42f0f1SJohn McCall CGF.AllocateBlockDecl(Info.DeclRefs[i]); 1509d42f0f1SJohn McCall 1519d42f0f1SJohn McCall if (Info.NeedsObjCSelf) { 1529d42f0f1SJohn McCall ValueDecl *Self = cast<ObjCMethodDecl>(CGF.CurFuncDecl)->getSelfDecl(); 1539d42f0f1SJohn McCall BlockDeclRefExpr *BDRE = 1549d42f0f1SJohn McCall new (CGF.getContext()) BlockDeclRefExpr(Self, Self->getType(), 1559d42f0f1SJohn McCall SourceLocation(), false); 1569d42f0f1SJohn McCall Info.DeclRefs.push_back(BDRE); 1579d42f0f1SJohn McCall CGF.AllocateBlockDecl(BDRE); 1589d42f0f1SJohn McCall } 159ed5e69feSAnders Carlsson } 160ed5e69feSAnders Carlsson 161d5010898SFariborz Jahanian static unsigned computeBlockFlag(CodeGenModule &CGM, 162d5010898SFariborz Jahanian const BlockExpr *BE, unsigned flags) { 163d5010898SFariborz Jahanian QualType BPT = BE->getType(); 164d5010898SFariborz Jahanian const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>(); 165d5010898SFariborz Jahanian QualType ResultType = ftype->getResultType(); 166d5010898SFariborz Jahanian 167d5010898SFariborz Jahanian CallArgList Args; 168d5010898SFariborz Jahanian CodeGenTypes &Types = CGM.getTypes(); 169d5010898SFariborz Jahanian const CGFunctionInfo &FnInfo = Types.getFunctionInfo(ResultType, Args, 170d5010898SFariborz Jahanian FunctionType::ExtInfo()); 171d5010898SFariborz Jahanian if (CGM.ReturnTypeUsesSRet(FnInfo)) 172d5010898SFariborz Jahanian flags |= CodeGenFunction::BLOCK_USE_STRET; 173d5010898SFariborz Jahanian return flags; 174d5010898SFariborz Jahanian } 175d5010898SFariborz Jahanian 1762d33d630SMike Stump // FIXME: Push most into CGM, passing down a few bits, like current function 1772d33d630SMike Stump // name. 178b750d928SMike Stump llvm::Value *CodeGenFunction::BuildBlockLiteralTmp(const BlockExpr *BE) { 179ed5e69feSAnders Carlsson std::string Name = CurFn->getName(); 1809d42f0f1SJohn McCall CGBlockInfo Info(Name.c_str()); 1819d42f0f1SJohn McCall Info.InnerBlocks.insert(BE->getBlockDecl()); 1829d42f0f1SJohn McCall CollectBlockDeclRefInfo(BE->getBody(), Info); 183ed5e69feSAnders Carlsson 184ed5e69feSAnders Carlsson // Check if the block can be global. 1852d33d630SMike Stump // FIXME: This test doesn't work for nested blocks yet. Longer term, I'd like 1862d33d630SMike Stump // to just have one code path. We should move this function into CGM and pass 1872d33d630SMike Stump // CGF, then we can just check to see if CGF is 0. 18897d01d50SMike Stump if (0 && CanBlockBeGlobal(Info)) 189ed5e69feSAnders Carlsson return CGM.GetAddrOfGlobalBlock(BE, Name.c_str()); 19085284bacSMike Stump 191950a9518SDavid Chisnall size_t BlockFields = 5; 192950a9518SDavid Chisnall 193950a9518SDavid Chisnall std::vector<llvm::Constant*> Elts(BlockFields); 194950a9518SDavid Chisnall 19585284bacSMike Stump llvm::Constant *C; 196b750d928SMike Stump llvm::Value *V; 19785284bacSMike Stump 19885284bacSMike Stump { 199afa3c0a8SFariborz Jahanian llvm::Constant *BlockVarLayout; 20085284bacSMike Stump // C = BuildBlockStructInitlist(); 201f27ab71dSBlaine Garst unsigned int flags = BLOCK_HAS_SIGNATURE; 202950a9518SDavid Chisnall 2034446dcf0SMike Stump // We run this first so that we set BlockHasCopyDispose from the entire 2044446dcf0SMike Stump // block literal. 2054446dcf0SMike Stump // __invoke 2064446dcf0SMike Stump llvm::Function *Fn 2079b5528d2SFariborz Jahanian = CodeGenFunction(CGM).GenerateBlockFunction(CurGD, BE, Info, CurFuncDecl, 208afa3c0a8SFariborz Jahanian BlockVarLayout, 2099d42f0f1SJohn McCall LocalDeclMap); 2109d42f0f1SJohn McCall BlockHasCopyDispose |= Info.BlockHasCopyDispose; 2114446dcf0SMike Stump Elts[3] = Fn; 2124446dcf0SMike Stump 21318bb9284SMike Stump // FIXME: Don't use BlockHasCopyDispose, it is set more often then 21418bb9284SMike Stump // necessary, for example: { ^{ __block int i; ^{ i = 1; }(); }(); } 2159d42f0f1SJohn McCall if (Info.BlockHasCopyDispose) 21685284bacSMike Stump flags |= BLOCK_HAS_COPY_DISPOSE; 21785284bacSMike Stump 218499ae7ecSMike Stump // __isa 2197ab278dbSMike Stump C = CGM.getNSConcreteStackBlock(); 220ade90fd1SOwen Anderson C = llvm::ConstantExpr::getBitCast(C, PtrToInt8Ty); 2214446dcf0SMike Stump Elts[0] = C; 22285284bacSMike Stump 22385284bacSMike Stump // __flags 224d5010898SFariborz Jahanian flags = computeBlockFlag(CGM, BE, flags); 22585284bacSMike Stump const llvm::IntegerType *IntTy = cast<llvm::IntegerType>( 22685284bacSMike Stump CGM.getTypes().ConvertType(CGM.getContext().IntTy)); 227b7a2fe6fSOwen Anderson C = llvm::ConstantInt::get(IntTy, flags); 2284446dcf0SMike Stump Elts[1] = C; 22985284bacSMike Stump 23085284bacSMike Stump // __reserved 231b7a2fe6fSOwen Anderson C = llvm::ConstantInt::get(IntTy, 0); 2324446dcf0SMike Stump Elts[2] = C; 23385284bacSMike Stump 2349d42f0f1SJohn McCall if (Info.BlockLayout.empty()) { 235d6ef62f0SMike Stump // __descriptor 236afa3c0a8SFariborz Jahanian C = llvm::Constant::getNullValue(PtrToInt8Ty); 237afa3c0a8SFariborz Jahanian Elts[4] = BuildDescriptorBlockDecl(BE, Info, 0, C, 0); 238d6ef62f0SMike Stump 2393a139f37SMike Stump // Optimize to being a global block. 2403a139f37SMike Stump Elts[0] = CGM.getNSConcreteGlobalBlock(); 241f27ab71dSBlaine Garst 242b7a2fe6fSOwen Anderson Elts[1] = llvm::ConstantInt::get(IntTy, flags|BLOCK_IS_GLOBAL); 2433a139f37SMike Stump 24441eaf0acSNick Lewycky C = llvm::ConstantStruct::get(VMContext, Elts, false); 24585284bacSMike Stump 246c10c8d3eSOwen Anderson C = new llvm::GlobalVariable(CGM.getModule(), C->getType(), true, 247d6b28fc6SBenjamin Kramer llvm::GlobalValue::InternalLinkage, C, 248d6b28fc6SBenjamin Kramer "__block_holder_tmp_" + 249d6b28fc6SBenjamin Kramer llvm::Twine(CGM.getGlobalUniqueCount())); 2505d2534adSMike Stump QualType BPT = BE->getType(); 251ade90fd1SOwen Anderson C = llvm::ConstantExpr::getBitCast(C, ConvertType(BPT)); 25285284bacSMike Stump return C; 25385284bacSMike Stump } 25485284bacSMike Stump 2559d42f0f1SJohn McCall std::vector<const llvm::Type *> Types(BlockFields+Info.BlockLayout.size()); 256aeb0ffd5SMike Stump for (int i=0; i<4; ++i) 257b750d928SMike Stump Types[i] = Elts[i]->getType(); 258aeb0ffd5SMike Stump Types[4] = PtrToInt8Ty; 25985284bacSMike Stump 2609d42f0f1SJohn McCall for (unsigned i = 0, n = Info.BlockLayout.size(); i != n; ++i) { 2619d42f0f1SJohn McCall const Expr *E = Info.BlockLayout[i]; 2621db7d04bSMike Stump const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E); 2631db7d04bSMike Stump QualType Ty = E->getType(); 26497d01d50SMike Stump if (BDRE && BDRE->isByRef()) { 265d1b378e0SFariborz Jahanian Types[i+BlockFields] = 266d1b378e0SFariborz Jahanian llvm::PointerType::get(BuildByRefType(BDRE->getDecl()), 0); 267d1b378e0SFariborz Jahanian } else if (BDRE && BDRE->getDecl()->getType()->isReferenceType()) { 268d1b378e0SFariborz Jahanian Types[i+BlockFields] = llvm::PointerType::get(ConvertType(Ty), 0); 26997d01d50SMike Stump } else 270950a9518SDavid Chisnall Types[i+BlockFields] = ConvertType(Ty); 2711db7d04bSMike Stump } 272b750d928SMike Stump 273758428f4SOwen Anderson llvm::StructType *Ty = llvm::StructType::get(VMContext, Types, true); 274b750d928SMike Stump 275b750d928SMike Stump llvm::AllocaInst *A = CreateTempAlloca(Ty); 2769d42f0f1SJohn McCall A->setAlignment(Info.BlockAlign.getQuantity()); 277b750d928SMike Stump V = A; 278b750d928SMike Stump 27987fe5d56SJohn McCall // Build layout / cleanup information for all the data entries in the 28087fe5d56SJohn McCall // layout, and write the enclosing fields into the type. 2819d42f0f1SJohn McCall std::vector<HelperInfo> NoteForHelper(Info.BlockLayout.size()); 28287fe5d56SJohn McCall unsigned NumHelpers = 0; 283aeb0ffd5SMike Stump 284aeb0ffd5SMike Stump for (unsigned i=0; i<4; ++i) 285b750d928SMike Stump Builder.CreateStore(Elts[i], Builder.CreateStructGEP(V, i, "block.tmp")); 286b750d928SMike Stump 2879d42f0f1SJohn McCall for (unsigned i=0; i < Info.BlockLayout.size(); ++i) { 2889d42f0f1SJohn McCall const Expr *E = Info.BlockLayout[i]; 289b750d928SMike Stump 2901db7d04bSMike Stump // Skip padding. 29187fe5d56SJohn McCall if (isa<DeclRefExpr>(E)) continue; 2921db7d04bSMike Stump 293950a9518SDavid Chisnall llvm::Value* Addr = Builder.CreateStructGEP(V, i+BlockFields, "tmp"); 29487fe5d56SJohn McCall HelperInfo &Note = NoteForHelper[NumHelpers++]; 29587fe5d56SJohn McCall 29687fe5d56SJohn McCall Note.index = i+5; 29787fe5d56SJohn McCall 29887fe5d56SJohn McCall if (isa<CXXThisExpr>(E)) { 29987fe5d56SJohn McCall Note.RequiresCopying = false; 30087fe5d56SJohn McCall Note.flag = BLOCK_FIELD_IS_OBJECT; 30187fe5d56SJohn McCall 30287fe5d56SJohn McCall Builder.CreateStore(LoadCXXThis(), Addr); 30387fe5d56SJohn McCall continue; 30487fe5d56SJohn McCall } 30587fe5d56SJohn McCall 30687fe5d56SJohn McCall const BlockDeclRefExpr *BDRE = cast<BlockDeclRefExpr>(E); 30787fe5d56SJohn McCall const ValueDecl *VD = BDRE->getDecl(); 30887fe5d56SJohn McCall QualType T = VD->getType(); 30987fe5d56SJohn McCall 31087fe5d56SJohn McCall Note.RequiresCopying = BlockRequiresCopying(T); 31187fe5d56SJohn McCall 31287fe5d56SJohn McCall if (BDRE->isByRef()) { 31387fe5d56SJohn McCall Note.flag = BLOCK_FIELD_IS_BYREF; 31487fe5d56SJohn McCall if (T.isObjCGCWeak()) 31587fe5d56SJohn McCall Note.flag |= BLOCK_FIELD_IS_WEAK; 31687fe5d56SJohn McCall } else if (T->isBlockPointerType()) { 31787fe5d56SJohn McCall Note.flag = BLOCK_FIELD_IS_BLOCK; 31887fe5d56SJohn McCall } else { 31987fe5d56SJohn McCall Note.flag = BLOCK_FIELD_IS_OBJECT; 32087fe5d56SJohn McCall } 321aeb0ffd5SMike Stump 3221db7d04bSMike Stump if (LocalDeclMap[VD]) { 32397d01d50SMike Stump if (BDRE->isByRef()) { 32497d01d50SMike Stump llvm::Value *Loc = LocalDeclMap[VD]; 32597d01d50SMike Stump Loc = Builder.CreateStructGEP(Loc, 1, "forwarding"); 326c76493a6SDaniel Dunbar Loc = Builder.CreateLoad(Loc); 32797d01d50SMike Stump Builder.CreateStore(Loc, Addr); 32897d01d50SMike Stump continue; 32987fe5d56SJohn McCall } else { 3303b836180SFariborz Jahanian if (BDRE->getCopyConstructorExpr()) { 331ea882cd9SFariborz Jahanian E = BDRE->getCopyConstructorExpr(); 332bd30929eSJohn McCall PushDestructorCleanup(E->getType(), Addr); 3333b836180SFariborz Jahanian } 334ea882cd9SFariborz Jahanian else { 33587fe5d56SJohn McCall E = new (getContext()) DeclRefExpr(const_cast<ValueDecl*>(VD), 336d1b378e0SFariborz Jahanian VD->getType().getNonReferenceType(), 337d1b378e0SFariborz Jahanian SourceLocation()); 33864176c2cSFariborz Jahanian if (VD->getType()->isReferenceType()) { 339d1b378e0SFariborz Jahanian E = new (getContext()) 340*e302792bSJohn McCall UnaryOperator(const_cast<Expr*>(E), UO_AddrOf, 341d1b378e0SFariborz Jahanian getContext().getPointerType(E->getType()), 342ed6c7440SDouglas Gregor SourceLocation()); 3431db7d04bSMike Stump } 34464176c2cSFariborz Jahanian } 34564176c2cSFariborz Jahanian } 34687fe5d56SJohn McCall } 34787fe5d56SJohn McCall 34897d01d50SMike Stump if (BDRE->isByRef()) { 3491db7d04bSMike Stump E = new (getContext()) 350*e302792bSJohn McCall UnaryOperator(const_cast<Expr*>(E), UO_AddrOf, 3511db7d04bSMike Stump getContext().getPointerType(E->getType()), 3521db7d04bSMike Stump SourceLocation()); 35397d01d50SMike Stump } 3541db7d04bSMike Stump 3551db7d04bSMike Stump RValue r = EmitAnyExpr(E, Addr, false); 35697d01d50SMike Stump if (r.isScalar()) { 35797d01d50SMike Stump llvm::Value *Loc = r.getScalarVal(); 358950a9518SDavid Chisnall const llvm::Type *Ty = Types[i+BlockFields]; 35997d01d50SMike Stump if (BDRE->isByRef()) { 3602d33d630SMike Stump // E is now the address of the value field, instead, we want the 3612d33d630SMike Stump // address of the actual ByRef struct. We optimize this slightly 3622d33d630SMike Stump // compared to gcc by not grabbing the forwarding slot as this must 3632d33d630SMike Stump // be done during Block_copy for us, and we can postpone the work 3642d33d630SMike Stump // until then. 36540775003SKen Dyck CharUnits offset = BlockDecls[BDRE->getDecl()]; 3662d33d630SMike Stump 3672d33d630SMike Stump llvm::Value *BlockLiteral = LoadBlockStruct(); 3682d33d630SMike Stump 3692d33d630SMike Stump Loc = Builder.CreateGEP(BlockLiteral, 3705e016ae9SChris Lattner llvm::ConstantInt::get(Int64Ty, offset.getQuantity()), 3712d33d630SMike Stump "block.literal"); 3729793f0e4SOwen Anderson Ty = llvm::PointerType::get(Ty, 0); 37397d01d50SMike Stump Loc = Builder.CreateBitCast(Loc, Ty); 374c76493a6SDaniel Dunbar Loc = Builder.CreateLoad(Loc); 3752d33d630SMike Stump // Loc = Builder.CreateBitCast(Loc, Ty); 37697d01d50SMike Stump } 37797d01d50SMike Stump Builder.CreateStore(Loc, Addr); 37897d01d50SMike Stump } else if (r.isComplex()) 379b750d928SMike Stump // FIXME: implement 380b750d928SMike Stump ErrorUnsupported(BE, "complex in block literal"); 381b750d928SMike Stump else if (r.isAggregate()) 382b750d928SMike Stump ; // Already created into the destination 383b750d928SMike Stump else 384b750d928SMike Stump assert (0 && "bad block variable"); 385b750d928SMike Stump // FIXME: Ensure that the offset created by the backend for 386b750d928SMike Stump // the struct matches the previously computed offset in BlockDecls. 387b750d928SMike Stump } 38887fe5d56SJohn McCall NoteForHelper.resize(NumHelpers); 389d6ef62f0SMike Stump 390d6ef62f0SMike Stump // __descriptor 391c05349e5SFariborz Jahanian llvm::Value *Descriptor = BuildDescriptorBlockDecl(BE, Info, Ty, 392afa3c0a8SFariborz Jahanian BlockVarLayout, 393aeb0ffd5SMike Stump &NoteForHelper); 394aeb0ffd5SMike Stump Descriptor = Builder.CreateBitCast(Descriptor, PtrToInt8Ty); 395aeb0ffd5SMike Stump Builder.CreateStore(Descriptor, Builder.CreateStructGEP(V, 4, "block.tmp")); 396b750d928SMike Stump } 397b750d928SMike Stump 398b750d928SMike Stump QualType BPT = BE->getType(); 399989908fbSFariborz Jahanian V = Builder.CreateBitCast(V, ConvertType(BPT)); 400989908fbSFariborz Jahanian // See if this is a __weak block variable and the must call objc_read_weak 401989908fbSFariborz Jahanian // on it. 402989908fbSFariborz Jahanian const FunctionType *ftype = BPT->getPointeeType()->getAs<FunctionType>(); 403989908fbSFariborz Jahanian QualType RES = ftype->getResultType(); 404989908fbSFariborz Jahanian if (RES.isObjCGCWeak()) { 405989908fbSFariborz Jahanian // Must cast argument to id* 406989908fbSFariborz Jahanian const llvm::Type *ObjectPtrTy = 407989908fbSFariborz Jahanian ConvertType(CGM.getContext().getObjCIdType()); 408989908fbSFariborz Jahanian const llvm::Type *PtrObjectPtrTy = 409989908fbSFariborz Jahanian llvm::PointerType::getUnqual(ObjectPtrTy); 410989908fbSFariborz Jahanian V = Builder.CreateBitCast(V, PtrObjectPtrTy); 411989908fbSFariborz Jahanian V = CGM.getObjCRuntime().EmitObjCWeakRead(*this, V); 412989908fbSFariborz Jahanian } 413989908fbSFariborz Jahanian return V; 414b750d928SMike Stump } 41585284bacSMike Stump 41685284bacSMike Stump 41795435674SMike Stump const llvm::Type *BlockModule::getBlockDescriptorType() { 418650c932dSMike Stump if (BlockDescriptorType) 419650c932dSMike Stump return BlockDescriptorType; 4202437cbfaSAnders Carlsson 4212437cbfaSAnders Carlsson const llvm::Type *UnsignedLongTy = 422650c932dSMike Stump getTypes().ConvertType(getContext().UnsignedLongTy); 4232437cbfaSAnders Carlsson 4242437cbfaSAnders Carlsson // struct __block_descriptor { 4252437cbfaSAnders Carlsson // unsigned long reserved; 4262437cbfaSAnders Carlsson // unsigned long block_size; 427fc83aa04SBlaine Garst // 428fc83aa04SBlaine Garst // // later, the following will be added 429fc83aa04SBlaine Garst // 430fc83aa04SBlaine Garst // struct { 431fc83aa04SBlaine Garst // void (*copyHelper)(); 432fc83aa04SBlaine Garst // void (*copyHelper)(); 433fc83aa04SBlaine Garst // } helpers; // !!! optional 434fc83aa04SBlaine Garst // 435fc83aa04SBlaine Garst // const char *signature; // the block signature 436fc83aa04SBlaine Garst // const char *layout; // reserved 4372437cbfaSAnders Carlsson // }; 438758428f4SOwen Anderson BlockDescriptorType = llvm::StructType::get(UnsignedLongTy->getContext(), 439758428f4SOwen Anderson UnsignedLongTy, 4402437cbfaSAnders Carlsson UnsignedLongTy, 4412437cbfaSAnders Carlsson NULL); 4422437cbfaSAnders Carlsson 443650c932dSMike Stump getModule().addTypeName("struct.__block_descriptor", 444650c932dSMike Stump BlockDescriptorType); 4452437cbfaSAnders Carlsson 446650c932dSMike Stump return BlockDescriptorType; 4472437cbfaSAnders Carlsson } 4482437cbfaSAnders Carlsson 44995435674SMike Stump const llvm::Type *BlockModule::getGenericBlockLiteralType() { 450005c9a62SMike Stump if (GenericBlockLiteralType) 451005c9a62SMike Stump return GenericBlockLiteralType; 4522437cbfaSAnders Carlsson 4532437cbfaSAnders Carlsson const llvm::Type *BlockDescPtrTy = 4549793f0e4SOwen Anderson llvm::PointerType::getUnqual(getBlockDescriptorType()); 4552437cbfaSAnders Carlsson 45692bbd6d4SMike Stump const llvm::IntegerType *IntTy = cast<llvm::IntegerType>( 45792bbd6d4SMike Stump getTypes().ConvertType(getContext().IntTy)); 45892bbd6d4SMike Stump 4592437cbfaSAnders Carlsson // struct __block_literal_generic { 4605d2534adSMike Stump // void *__isa; 4615d2534adSMike Stump // int __flags; 4625d2534adSMike Stump // int __reserved; 4635d2534adSMike Stump // void (*__invoke)(void *); 4645d2534adSMike Stump // struct __block_descriptor *__descriptor; 4652437cbfaSAnders Carlsson // }; 466758428f4SOwen Anderson GenericBlockLiteralType = llvm::StructType::get(IntTy->getContext(), 467758428f4SOwen Anderson PtrToInt8Ty, 46892bbd6d4SMike Stump IntTy, 46992bbd6d4SMike Stump IntTy, 470626aecc4SMike Stump PtrToInt8Ty, 4712437cbfaSAnders Carlsson BlockDescPtrTy, 4722437cbfaSAnders Carlsson NULL); 4732437cbfaSAnders Carlsson 474005c9a62SMike Stump getModule().addTypeName("struct.__block_literal_generic", 475005c9a62SMike Stump GenericBlockLiteralType); 4762437cbfaSAnders Carlsson 477005c9a62SMike Stump return GenericBlockLiteralType; 4782437cbfaSAnders Carlsson } 4792437cbfaSAnders Carlsson 4805d2534adSMike Stump 481bfb3671bSAnders Carlsson RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr* E, 482bfb3671bSAnders Carlsson ReturnValueSlot ReturnValue) { 4832437cbfaSAnders Carlsson const BlockPointerType *BPT = 484c23c7e6aSTed Kremenek E->getCallee()->getType()->getAs<BlockPointerType>(); 4852437cbfaSAnders Carlsson 4862437cbfaSAnders Carlsson llvm::Value *Callee = EmitScalarExpr(E->getCallee()); 4872437cbfaSAnders Carlsson 4882437cbfaSAnders Carlsson // Get a pointer to the generic block literal. 4892437cbfaSAnders Carlsson const llvm::Type *BlockLiteralTy = 4909793f0e4SOwen Anderson llvm::PointerType::getUnqual(CGM.getGenericBlockLiteralType()); 4912437cbfaSAnders Carlsson 4922437cbfaSAnders Carlsson // Bitcast the callee to a block literal. 4932437cbfaSAnders Carlsson llvm::Value *BlockLiteral = 4942437cbfaSAnders Carlsson Builder.CreateBitCast(Callee, BlockLiteralTy, "block.literal"); 4952437cbfaSAnders Carlsson 4962437cbfaSAnders Carlsson // Get the function pointer from the literal. 4972437cbfaSAnders Carlsson llvm::Value *FuncPtr = Builder.CreateStructGEP(BlockLiteral, 3, "tmp"); 4982437cbfaSAnders Carlsson 4992437cbfaSAnders Carlsson BlockLiteral = 5002437cbfaSAnders Carlsson Builder.CreateBitCast(BlockLiteral, 501abd5b90eSBenjamin Kramer llvm::Type::getInt8PtrTy(VMContext), 5022437cbfaSAnders Carlsson "tmp"); 5032437cbfaSAnders Carlsson 5042437cbfaSAnders Carlsson // Add the block literal. 5052437cbfaSAnders Carlsson QualType VoidPtrTy = getContext().getPointerType(getContext().VoidTy); 5062437cbfaSAnders Carlsson CallArgList Args; 5072437cbfaSAnders Carlsson Args.push_back(std::make_pair(RValue::get(BlockLiteral), VoidPtrTy)); 5082437cbfaSAnders Carlsson 509479e6fc7SAnders Carlsson QualType FnType = BPT->getPointeeType(); 510479e6fc7SAnders Carlsson 5112437cbfaSAnders Carlsson // And the rest of the arguments. 5129dd450bbSJohn McCall EmitCallArgs(Args, FnType->getAs<FunctionProtoType>(), 513479e6fc7SAnders Carlsson E->arg_begin(), E->arg_end()); 5142437cbfaSAnders Carlsson 5155f50c651SAnders Carlsson // Load the function. 516c76493a6SDaniel Dunbar llvm::Value *Func = Builder.CreateLoad(FuncPtr, "tmp"); 5175f50c651SAnders Carlsson 518ab26cfa5SJohn McCall const FunctionType *FuncTy = FnType->getAs<FunctionType>(); 519ab26cfa5SJohn McCall QualType ResultType = FuncTy->getResultType(); 520a60cbcdfSAnders Carlsson 521a60cbcdfSAnders Carlsson const CGFunctionInfo &FnInfo = 522c50c27ccSRafael Espindola CGM.getTypes().getFunctionInfo(ResultType, Args, 523c50c27ccSRafael Espindola FuncTy->getExtInfo()); 5245f50c651SAnders Carlsson 5255f50c651SAnders Carlsson // Cast the function pointer to the right type. 5265f50c651SAnders Carlsson const llvm::Type *BlockFTy = 527a60cbcdfSAnders Carlsson CGM.getTypes().GetFunctionType(FnInfo, false); 5285f50c651SAnders Carlsson 5299793f0e4SOwen Anderson const llvm::Type *BlockFTyPtr = llvm::PointerType::getUnqual(BlockFTy); 5305f50c651SAnders Carlsson Func = Builder.CreateBitCast(Func, BlockFTyPtr); 5315f50c651SAnders Carlsson 5322437cbfaSAnders Carlsson // And call the block. 533bfb3671bSAnders Carlsson return EmitCall(FnInfo, Func, ReturnValue, Args); 5342437cbfaSAnders Carlsson } 5356a60fa24SAnders Carlsson 53687fe5d56SJohn McCall void CodeGenFunction::AllocateBlockCXXThisPointer(const CXXThisExpr *E) { 53787fe5d56SJohn McCall assert(BlockCXXThisOffset.isZero() && "already computed 'this' pointer"); 53887fe5d56SJohn McCall 53987fe5d56SJohn McCall // Figure out what the offset is. 54087fe5d56SJohn McCall QualType T = E->getType(); 54187fe5d56SJohn McCall std::pair<CharUnits,CharUnits> TypeInfo = getContext().getTypeInfoInChars(T); 54287fe5d56SJohn McCall CharUnits Offset = getBlockOffset(TypeInfo.first, TypeInfo.second); 54387fe5d56SJohn McCall 54487fe5d56SJohn McCall BlockCXXThisOffset = Offset; 54587fe5d56SJohn McCall BlockLayout.push_back(E); 54687fe5d56SJohn McCall } 54787fe5d56SJohn McCall 54887fe5d56SJohn McCall void CodeGenFunction::AllocateBlockDecl(const BlockDeclRefExpr *E) { 5490168f4b2SAnders Carlsson const ValueDecl *VD = E->getDecl(); 55087fe5d56SJohn McCall CharUnits &Offset = BlockDecls[VD]; 5510168f4b2SAnders Carlsson 55297d01d50SMike Stump // See if we have already allocated an offset for this variable. 55387fe5d56SJohn McCall if (!Offset.isZero()) 55487fe5d56SJohn McCall return; 5557fe9cc1dSMike Stump 5564446dcf0SMike Stump // Don't run the expensive check, unless we have to. 557e1b19ba0SMike Stump if (!BlockHasCopyDispose) 558e1b19ba0SMike Stump if (E->isByRef() 559e1b19ba0SMike Stump || BlockRequiresCopying(E->getType())) 5604446dcf0SMike Stump BlockHasCopyDispose = true; 5617fe9cc1dSMike Stump 56287fe5d56SJohn McCall const ValueDecl *D = cast<ValueDecl>(E->getDecl()); 5637fe9cc1dSMike Stump 56487fe5d56SJohn McCall CharUnits Size; 56587fe5d56SJohn McCall CharUnits Align; 56687fe5d56SJohn McCall 56787fe5d56SJohn McCall if (E->isByRef()) { 56887fe5d56SJohn McCall llvm::tie(Size,Align) = 56987fe5d56SJohn McCall getContext().getTypeInfoInChars(getContext().VoidPtrTy); 57087fe5d56SJohn McCall } else { 57187fe5d56SJohn McCall Size = getContext().getTypeSizeInChars(D->getType()); 57287fe5d56SJohn McCall Align = getContext().getDeclAlign(D); 57387fe5d56SJohn McCall } 57487fe5d56SJohn McCall 57587fe5d56SJohn McCall Offset = getBlockOffset(Size, Align); 57687fe5d56SJohn McCall BlockLayout.push_back(E); 57797d01d50SMike Stump } 57897d01d50SMike Stump 5799d42f0f1SJohn McCall llvm::Value *CodeGenFunction::GetAddrOfBlockDecl(const ValueDecl *VD, 5809d42f0f1SJohn McCall bool IsByRef) { 58164176c2cSFariborz Jahanian 58287fe5d56SJohn McCall CharUnits offset = BlockDecls[VD]; 58387fe5d56SJohn McCall assert(!offset.isZero() && "getting address of unallocated decl"); 5847fe9cc1dSMike Stump 58597d01d50SMike Stump llvm::Value *BlockLiteral = LoadBlockStruct(); 58697d01d50SMike Stump llvm::Value *V = Builder.CreateGEP(BlockLiteral, 5875e016ae9SChris Lattner llvm::ConstantInt::get(Int64Ty, offset.getQuantity()), 5882d33d630SMike Stump "block.literal"); 5899d42f0f1SJohn McCall if (IsByRef) { 59097d01d50SMike Stump const llvm::Type *PtrStructTy 5910168f4b2SAnders Carlsson = llvm::PointerType::get(BuildByRefType(VD), 0); 592efd7caa8SMike Stump // The block literal will need a copy/destroy helper. 593efd7caa8SMike Stump BlockHasCopyDispose = true; 5940168f4b2SAnders Carlsson 5950168f4b2SAnders Carlsson const llvm::Type *Ty = PtrStructTy; 5969793f0e4SOwen Anderson Ty = llvm::PointerType::get(Ty, 0); 59797d01d50SMike Stump V = Builder.CreateBitCast(V, Ty); 598c76493a6SDaniel Dunbar V = Builder.CreateLoad(V); 59997d01d50SMike Stump V = Builder.CreateStructGEP(V, 1, "forwarding"); 600c76493a6SDaniel Dunbar V = Builder.CreateLoad(V); 60197d01d50SMike Stump V = Builder.CreateBitCast(V, PtrStructTy); 6020168f4b2SAnders Carlsson V = Builder.CreateStructGEP(V, getByRefValueLLVMField(VD), 6030168f4b2SAnders Carlsson VD->getNameAsString()); 604eeb23379SFariborz Jahanian if (VD->getType()->isReferenceType()) 605eeb23379SFariborz Jahanian V = Builder.CreateLoad(V); 60697d01d50SMike Stump } else { 6070168f4b2SAnders Carlsson const llvm::Type *Ty = CGM.getTypes().ConvertType(VD->getType()); 6089793f0e4SOwen Anderson Ty = llvm::PointerType::get(Ty, 0); 60997d01d50SMike Stump V = Builder.CreateBitCast(V, Ty); 610d1b378e0SFariborz Jahanian if (VD->getType()->isReferenceType()) 61164176c2cSFariborz Jahanian V = Builder.CreateLoad(V, "ref.tmp"); 61297d01d50SMike Stump } 61397d01d50SMike Stump return V; 61497d01d50SMike Stump } 61597d01d50SMike Stump 6162d5a2878SMike Stump llvm::Constant * 6176c39666aSMike Stump BlockModule::GetAddrOfGlobalBlock(const BlockExpr *BE, const char * n) { 6186a60fa24SAnders Carlsson // Generate the block descriptor. 6196a60fa24SAnders Carlsson const llvm::Type *UnsignedLongTy = Types.ConvertType(Context.UnsignedLongTy); 62092bbd6d4SMike Stump const llvm::IntegerType *IntTy = cast<llvm::IntegerType>( 62192bbd6d4SMike Stump getTypes().ConvertType(getContext().IntTy)); 6226a60fa24SAnders Carlsson 623fc83aa04SBlaine Garst llvm::Constant *DescriptorFields[4]; 6246a60fa24SAnders Carlsson 6256a60fa24SAnders Carlsson // Reserved 6260b75f23bSOwen Anderson DescriptorFields[0] = llvm::Constant::getNullValue(UnsignedLongTy); 6276a60fa24SAnders Carlsson 6286a60fa24SAnders Carlsson // Block literal size. For global blocks we just use the size of the generic 6296a60fa24SAnders Carlsson // block literal struct. 63098ca7943SKen Dyck CharUnits BlockLiteralSize = 63198ca7943SKen Dyck CGM.GetTargetTypeStoreSize(getGenericBlockLiteralType()); 632170229f6SOwen Anderson DescriptorFields[1] = 63340775003SKen Dyck llvm::ConstantInt::get(UnsignedLongTy,BlockLiteralSize.getQuantity()); 6346a60fa24SAnders Carlsson 635fc83aa04SBlaine Garst // signature. non-optional ObjC-style method descriptor @encode sequence 636fc83aa04SBlaine Garst std::string BlockTypeEncoding; 637fc83aa04SBlaine Garst CGM.getContext().getObjCEncodingForBlock(BE, BlockTypeEncoding); 638fc83aa04SBlaine Garst 639fc83aa04SBlaine Garst DescriptorFields[2] = llvm::ConstantExpr::getBitCast( 640fc83aa04SBlaine Garst CGM.GetAddrOfConstantCString(BlockTypeEncoding), PtrToInt8Ty); 641fc83aa04SBlaine Garst 642fc83aa04SBlaine Garst // layout 643fc83aa04SBlaine Garst DescriptorFields[3] = 644fc83aa04SBlaine Garst llvm::ConstantInt::get(UnsignedLongTy,0); 645fc83aa04SBlaine Garst 646fc83aa04SBlaine Garst // build the structure from the 4 elements 6476a60fa24SAnders Carlsson llvm::Constant *DescriptorStruct = 648fc83aa04SBlaine Garst llvm::ConstantStruct::get(VMContext, &DescriptorFields[0], 4, false); 6496a60fa24SAnders Carlsson 6506a60fa24SAnders Carlsson llvm::GlobalVariable *Descriptor = 651c10c8d3eSOwen Anderson new llvm::GlobalVariable(getModule(), DescriptorStruct->getType(), true, 6526a60fa24SAnders Carlsson llvm::GlobalVariable::InternalLinkage, 653c10c8d3eSOwen Anderson DescriptorStruct, "__block_descriptor_global"); 6546a60fa24SAnders Carlsson 655950a9518SDavid Chisnall int FieldCount = 5; 6566a60fa24SAnders Carlsson // Generate the constants for the block literal. 657950a9518SDavid Chisnall 658950a9518SDavid Chisnall std::vector<llvm::Constant*> LiteralFields(FieldCount); 6596a60fa24SAnders Carlsson 6609d42f0f1SJohn McCall CGBlockInfo Info(n); 661afa3c0a8SFariborz Jahanian llvm::Constant *BlockVarLayout; 6625469f29aSMike Stump llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap; 663cb2fbcb0SMike Stump llvm::Function *Fn 664d5010898SFariborz Jahanian = CodeGenFunction(CGM).GenerateBlockFunction(GlobalDecl(), BE, 665afa3c0a8SFariborz Jahanian Info, 0, BlockVarLayout, 666afa3c0a8SFariborz Jahanian LocalDeclMap); 6679d42f0f1SJohn McCall assert(Info.BlockSize == BlockLiteralSize 668cb2fbcb0SMike Stump && "no imports allowed for global block"); 6696a60fa24SAnders Carlsson 6706a60fa24SAnders Carlsson // isa 671900546d2SDaniel Dunbar LiteralFields[0] = CGM.getNSConcreteGlobalBlock(); 6726a60fa24SAnders Carlsson 673d5010898SFariborz Jahanian // __flags 674d5010898SFariborz Jahanian unsigned flags = computeBlockFlag(CGM, BE, 675d5010898SFariborz Jahanian (BLOCK_IS_GLOBAL | BLOCK_HAS_SIGNATURE)); 676fc83aa04SBlaine Garst LiteralFields[1] = 677d5010898SFariborz Jahanian llvm::ConstantInt::get(IntTy, flags); 6786a60fa24SAnders Carlsson 6796a60fa24SAnders Carlsson // Reserved 6800b75f23bSOwen Anderson LiteralFields[2] = llvm::Constant::getNullValue(IntTy); 6816a60fa24SAnders Carlsson 6826a60fa24SAnders Carlsson // Function 6836a60fa24SAnders Carlsson LiteralFields[3] = Fn; 6846a60fa24SAnders Carlsson 6856a60fa24SAnders Carlsson // Descriptor 6866a60fa24SAnders Carlsson LiteralFields[4] = Descriptor; 6876a60fa24SAnders Carlsson 6886a60fa24SAnders Carlsson llvm::Constant *BlockLiteralStruct = 689950a9518SDavid Chisnall llvm::ConstantStruct::get(VMContext, LiteralFields, false); 6906a60fa24SAnders Carlsson 6916a60fa24SAnders Carlsson llvm::GlobalVariable *BlockLiteral = 692c10c8d3eSOwen Anderson new llvm::GlobalVariable(getModule(), BlockLiteralStruct->getType(), true, 6936a60fa24SAnders Carlsson llvm::GlobalVariable::InternalLinkage, 694c10c8d3eSOwen Anderson BlockLiteralStruct, "__block_literal_global"); 6956a60fa24SAnders Carlsson 6966a60fa24SAnders Carlsson return BlockLiteral; 6976a60fa24SAnders Carlsson } 6986a60fa24SAnders Carlsson 699cb2fbcb0SMike Stump llvm::Value *CodeGenFunction::LoadBlockStruct() { 70038382028SMike Stump llvm::Value *V = Builder.CreateLoad(LocalDeclMap[getBlockStructDecl()], 70138382028SMike Stump "self"); 70238382028SMike Stump // For now, we codegen based upon byte offsets. 70338382028SMike Stump return Builder.CreateBitCast(V, PtrToInt8Ty); 704cb2fbcb0SMike Stump } 705cb2fbcb0SMike Stump 7064446dcf0SMike Stump llvm::Function * 7079b5528d2SFariborz Jahanian CodeGenFunction::GenerateBlockFunction(GlobalDecl GD, const BlockExpr *BExpr, 7089d42f0f1SJohn McCall CGBlockInfo &Info, 709692c6e37SMike Stump const Decl *OuterFuncDecl, 710afa3c0a8SFariborz Jahanian llvm::Constant *& BlockVarLayout, 7119d42f0f1SJohn McCall llvm::DenseMap<const Decl*, llvm::Value*> ldm) { 7129074ed8cSDevang Patel 7139074ed8cSDevang Patel // Check if we should generate debug info for this block. 7149074ed8cSDevang Patel if (CGM.getDebugInfo()) 7159074ed8cSDevang Patel DebugInfo = CGM.getDebugInfo(); 7169074ed8cSDevang Patel 7175469f29aSMike Stump // Arrange for local static and local extern declarations to appear 7185469f29aSMike Stump // to be local to this function as well, as they are directly referenced 7195469f29aSMike Stump // in a block. 7205469f29aSMike Stump for (llvm::DenseMap<const Decl *, llvm::Value*>::iterator i = ldm.begin(); 7215469f29aSMike Stump i != ldm.end(); 7225469f29aSMike Stump ++i) { 7235469f29aSMike Stump const VarDecl *VD = dyn_cast<VarDecl>(i->first); 7245469f29aSMike Stump 7250ca16601SDaniel Dunbar if (VD->getStorageClass() == VarDecl::Static || VD->hasExternalStorage()) 7265469f29aSMike Stump LocalDeclMap[VD] = i->second; 7275469f29aSMike Stump } 7285469f29aSMike Stump 72998ca7943SKen Dyck BlockOffset = 73098ca7943SKen Dyck CGM.GetTargetTypeStoreSize(CGM.getGenericBlockLiteralType()); 7315262b119SKen Dyck BlockAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy); 73209a9b6e3SEli Friedman 733aae4349dSFariborz Jahanian const FunctionType *BlockFunctionType = BExpr->getFunctionType(); 734aae4349dSFariborz Jahanian QualType ResultType; 735c50c27ccSRafael Espindola FunctionType::ExtInfo EInfo = getFunctionExtInfo(*BlockFunctionType); 736aae4349dSFariborz Jahanian bool IsVariadic; 737a4f6b6b1SFariborz Jahanian if (const FunctionProtoType *FTy = 738a4f6b6b1SFariborz Jahanian dyn_cast<FunctionProtoType>(BlockFunctionType)) { 739aae4349dSFariborz Jahanian ResultType = FTy->getResultType(); 740aae4349dSFariborz Jahanian IsVariadic = FTy->isVariadic(); 741658fe02dSMike Stump } else { 742aae4349dSFariborz Jahanian // K&R style block. 743aae4349dSFariborz Jahanian ResultType = BlockFunctionType->getResultType(); 744aae4349dSFariborz Jahanian IsVariadic = false; 745aae4349dSFariborz Jahanian } 7466a60fa24SAnders Carlsson 7476a60fa24SAnders Carlsson FunctionArgList Args; 7486a60fa24SAnders Carlsson 7497fe9cc1dSMike Stump CurFuncDecl = OuterFuncDecl; 7507fe9cc1dSMike Stump 7513385fe12SChris Lattner const BlockDecl *BD = BExpr->getBlockDecl(); 7526a60fa24SAnders Carlsson 7537fe9cc1dSMike Stump IdentifierInfo *II = &CGM.getContext().Idents.get(".block_descriptor"); 754d015328fSMike Stump 75587fe5d56SJohn McCall // Build the block struct now. 7569d42f0f1SJohn McCall AllocateAllBlockDeclRefs(*this, Info); 7577fe9cc1dSMike Stump 758afa3c0a8SFariborz Jahanian // Capture block layout info. here. 759afa3c0a8SFariborz Jahanian if (CGM.getContext().getLangOptions().ObjC1) 760afa3c0a8SFariborz Jahanian BlockVarLayout = CGM.getObjCRuntime().GCBlockLayout(*this, Info.DeclRefs); 761afa3c0a8SFariborz Jahanian else 762afa3c0a8SFariborz Jahanian BlockVarLayout = llvm::Constant::getNullValue(PtrToInt8Ty); 763afa3c0a8SFariborz Jahanian 764e1b19ba0SMike Stump QualType ParmTy = getContext().getBlockParmType(BlockHasCopyDispose, 76587fe5d56SJohn McCall BlockLayout); 76687fe5d56SJohn McCall 7676a60fa24SAnders Carlsson // FIXME: This leaks 7686a60fa24SAnders Carlsson ImplicitParamDecl *SelfDecl = 7694d4dcc8eSJohn McCall ImplicitParamDecl::Create(getContext(), const_cast<BlockDecl*>(BD), 770d015328fSMike Stump SourceLocation(), II, 771d015328fSMike Stump ParmTy); 7726a60fa24SAnders Carlsson 7736a60fa24SAnders Carlsson Args.push_back(std::make_pair(SelfDecl, SelfDecl->getType())); 774cb2fbcb0SMike Stump BlockStructDecl = SelfDecl; 7756a60fa24SAnders Carlsson 776c4b30e59SSteve Naroff for (BlockDecl::param_const_iterator i = BD->param_begin(), 7776a60fa24SAnders Carlsson e = BD->param_end(); i != e; ++i) 778eecd39f2SMike Stump Args.push_back(std::make_pair(*i, (*i)->getType())); 7796a60fa24SAnders Carlsson 7806a60fa24SAnders Carlsson const CGFunctionInfo &FI = 781c50c27ccSRafael Espindola CGM.getTypes().getFunctionInfo(ResultType, Args, EInfo); 7826a60fa24SAnders Carlsson 7836a60fa24SAnders Carlsson CodeGenTypes &Types = CGM.getTypes(); 784aae4349dSFariborz Jahanian const llvm::FunctionType *LTy = Types.GetFunctionType(FI, IsVariadic); 7856a60fa24SAnders Carlsson 7867e10f369SDouglas Gregor MangleBuffer Name; 7879b5528d2SFariborz Jahanian CGM.getMangledName(GD, Name, BD); 7886a60fa24SAnders Carlsson llvm::Function *Fn = 78902df9da2SDouglas Gregor llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 79002df9da2SDouglas Gregor Name.getString(), &CGM.getModule()); 7916a60fa24SAnders Carlsson 792c3e7cff6SDaniel Dunbar CGM.SetInternalFunctionAttributes(BD, Fn, FI); 793f7f020bbSFariborz Jahanian StartFunction(BD, ResultType, Fn, Args, 794f7f020bbSFariborz Jahanian BExpr->getBody()->getLocEnd()); 795f7f020bbSFariborz Jahanian 796f7f020bbSFariborz Jahanian CurFuncDecl = OuterFuncDecl; 797c3e7cff6SDaniel Dunbar 79836ad0e99SFariborz Jahanian QualType FnType(BlockFunctionType, 0); 799c42461e1SFariborz Jahanian bool HasPrototype = isa<FunctionProtoType>(BlockFunctionType); 80036ad0e99SFariborz Jahanian 80136ad0e99SFariborz Jahanian IdentifierInfo *ID = &getContext().Idents.get(Name.getString()); 80236ad0e99SFariborz Jahanian CurCodeDecl = FunctionDecl::Create(getContext(), 80336ad0e99SFariborz Jahanian getContext().getTranslationUnitDecl(), 80436ad0e99SFariborz Jahanian SourceLocation(), ID, FnType, 80536ad0e99SFariborz Jahanian 0, 80636ad0e99SFariborz Jahanian FunctionDecl::Static, 80736ad0e99SFariborz Jahanian FunctionDecl::None, 80836ad0e99SFariborz Jahanian false, HasPrototype); 809f7f020bbSFariborz Jahanian if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FnType)) { 810f7f020bbSFariborz Jahanian const FunctionDecl *CFD = dyn_cast<FunctionDecl>(CurCodeDecl); 811f7f020bbSFariborz Jahanian FunctionDecl *FD = const_cast<FunctionDecl *>(CFD); 812f7f020bbSFariborz Jahanian llvm::SmallVector<ParmVarDecl*, 16> Params; 813f7f020bbSFariborz Jahanian for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 814f7f020bbSFariborz Jahanian Params.push_back(ParmVarDecl::Create(getContext(), FD, 815f7f020bbSFariborz Jahanian SourceLocation(), 0, 816f7f020bbSFariborz Jahanian FT->getArgType(i), /*TInfo=*/0, 817f7f020bbSFariborz Jahanian VarDecl::None, VarDecl::None, 0)); 818f7f020bbSFariborz Jahanian FD->setParams(Params.data(), Params.size()); 819f7f020bbSFariborz Jahanian } 82036ad0e99SFariborz Jahanian 821017460abSMike Stump 82287fe5d56SJohn McCall // If we have a C++ 'this' reference, go ahead and force it into 82387fe5d56SJohn McCall // existence now. 82487fe5d56SJohn McCall if (Info.CXXThisRef) { 82587fe5d56SJohn McCall assert(!BlockCXXThisOffset.isZero() && 82687fe5d56SJohn McCall "haven't yet allocated 'this' reference"); 82787fe5d56SJohn McCall 82887fe5d56SJohn McCall // TODO: I have a dream that one day this will be typed. 82987fe5d56SJohn McCall llvm::Value *BlockLiteral = LoadBlockStruct(); 83087fe5d56SJohn McCall llvm::Value *ThisPtrRaw = 83187fe5d56SJohn McCall Builder.CreateConstInBoundsGEP1_64(BlockLiteral, 83287fe5d56SJohn McCall BlockCXXThisOffset.getQuantity(), 83387fe5d56SJohn McCall "this.ptr.raw"); 83487fe5d56SJohn McCall 83587fe5d56SJohn McCall const llvm::Type *Ty = 83687fe5d56SJohn McCall CGM.getTypes().ConvertType(Info.CXXThisRef->getType()); 83787fe5d56SJohn McCall Ty = llvm::PointerType::get(Ty, 0); 83887fe5d56SJohn McCall llvm::Value *ThisPtr = Builder.CreateBitCast(ThisPtrRaw, Ty, "this.ptr"); 83987fe5d56SJohn McCall 84087fe5d56SJohn McCall CXXThisValue = Builder.CreateLoad(ThisPtr, "this"); 84187fe5d56SJohn McCall } 84287fe5d56SJohn McCall 8439d42f0f1SJohn McCall // If we have an Objective C 'self' reference, go ahead and force it 8449d42f0f1SJohn McCall // into existence now. 8459d42f0f1SJohn McCall if (Info.NeedsObjCSelf) { 8469d42f0f1SJohn McCall ValueDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl(); 8479d42f0f1SJohn McCall LocalDeclMap[Self] = GetAddrOfBlockDecl(Self, false); 8489d42f0f1SJohn McCall } 8499d42f0f1SJohn McCall 850017460abSMike Stump // Save a spot to insert the debug information for all the BlockDeclRefDecls. 851017460abSMike Stump llvm::BasicBlock *entry = Builder.GetInsertBlock(); 852017460abSMike Stump llvm::BasicBlock::iterator entry_ptr = Builder.GetInsertPoint(); 853017460abSMike Stump --entry_ptr; 854017460abSMike Stump 8553385fe12SChris Lattner EmitStmt(BExpr->getBody()); 856017460abSMike Stump 8577d69911aSMike Stump // Remember where we were... 8587d69911aSMike Stump llvm::BasicBlock *resume = Builder.GetInsertBlock(); 859017460abSMike Stump 8607d69911aSMike Stump // Go back to the entry. 861017460abSMike Stump ++entry_ptr; 862017460abSMike Stump Builder.SetInsertPoint(entry, entry_ptr); 863017460abSMike Stump 8642e722b91SMike Stump if (CGDebugInfo *DI = getDebugInfo()) { 8652e722b91SMike Stump // Emit debug information for all the BlockDeclRefDecls. 86687fe5d56SJohn McCall // FIXME: also for 'this' 86787fe5d56SJohn McCall for (unsigned i = 0, e = BlockLayout.size(); i != e; ++i) { 868bf78478dSChris Lattner if (const BlockDeclRefExpr *BDRE = 86987fe5d56SJohn McCall dyn_cast<BlockDeclRefExpr>(BlockLayout[i])) { 8702e722b91SMike Stump const ValueDecl *D = BDRE->getDecl(); 8712e722b91SMike Stump DI->setLocation(D->getLocation()); 8722e722b91SMike Stump DI->EmitDeclareOfBlockDeclRefVariable(BDRE, 8732e722b91SMike Stump LocalDeclMap[getBlockStructDecl()], 8742e722b91SMike Stump Builder, this); 8752e722b91SMike Stump } 8762e722b91SMike Stump } 8772e722b91SMike Stump } 8787d69911aSMike Stump // And resume where we left off. 8797d69911aSMike Stump if (resume == 0) 8807d69911aSMike Stump Builder.ClearInsertionPoint(); 8817d69911aSMike Stump else 8827d69911aSMike Stump Builder.SetInsertPoint(resume); 8832e722b91SMike Stump 8843385fe12SChris Lattner FinishFunction(cast<CompoundStmt>(BExpr->getBody())->getRBracLoc()); 8856a60fa24SAnders Carlsson 886b750d928SMike Stump // The runtime needs a minimum alignment of a void *. 8875262b119SKen Dyck CharUnits MinAlign = getContext().getTypeAlignInChars(getContext().VoidPtrTy); 88840775003SKen Dyck BlockOffset = CharUnits::fromQuantity( 8895262b119SKen Dyck llvm::RoundUpToAlignment(BlockOffset.getQuantity(), 8905262b119SKen Dyck MinAlign.getQuantity())); 891b750d928SMike Stump 8929d42f0f1SJohn McCall Info.BlockSize = BlockOffset; 8939d42f0f1SJohn McCall Info.BlockAlign = BlockAlign; 8949d42f0f1SJohn McCall Info.BlockLayout = BlockLayout; 8959d42f0f1SJohn McCall Info.BlockHasCopyDispose = BlockHasCopyDispose; 8966a60fa24SAnders Carlsson return Fn; 8976a60fa24SAnders Carlsson } 8981db7d04bSMike Stump 89987fe5d56SJohn McCall CharUnits BlockFunction::getBlockOffset(CharUnits Size, CharUnits Align) { 9005262b119SKen Dyck assert((Align.isPositive()) && "alignment must be 1 byte or more"); 9011db7d04bSMike Stump 90240775003SKen Dyck CharUnits OldOffset = BlockOffset; 9031db7d04bSMike Stump 9041db7d04bSMike Stump // Ensure proper alignment, even if it means we have to have a gap 90540775003SKen Dyck BlockOffset = CharUnits::fromQuantity( 9065262b119SKen Dyck llvm::RoundUpToAlignment(BlockOffset.getQuantity(), Align.getQuantity())); 9071db7d04bSMike Stump BlockAlign = std::max(Align, BlockAlign); 9081db7d04bSMike Stump 90940775003SKen Dyck CharUnits Pad = BlockOffset - OldOffset; 91040775003SKen Dyck if (Pad.isPositive()) { 9111db7d04bSMike Stump QualType PadTy = getContext().getConstantArrayType(getContext().CharTy, 91240775003SKen Dyck llvm::APInt(32, 91340775003SKen Dyck Pad.getQuantity()), 9141db7d04bSMike Stump ArrayType::Normal, 0); 9156a047c97SDouglas Gregor ValueDecl *PadDecl = VarDecl::Create(getContext(), 9166a047c97SDouglas Gregor getContext().getTranslationUnitDecl(), 9176a047c97SDouglas Gregor SourceLocation(), 918c4df4076SDouglas Gregor 0, QualType(PadTy), 0, 919c4df4076SDouglas Gregor VarDecl::None, VarDecl::None); 92087fe5d56SJohn McCall Expr *E = new (getContext()) DeclRefExpr(PadDecl, PadDecl->getType(), 921ed6c7440SDouglas Gregor SourceLocation()); 92287fe5d56SJohn McCall BlockLayout.push_back(E); 9231db7d04bSMike Stump } 9241db7d04bSMike Stump 9251db7d04bSMike Stump BlockOffset += Size; 9261db7d04bSMike Stump return BlockOffset - Size; 9271db7d04bSMike Stump } 92897d01d50SMike Stump 929aeb0ffd5SMike Stump llvm::Constant *BlockFunction:: 930aeb0ffd5SMike Stump GenerateCopyHelperFunction(bool BlockHasCopyDispose, const llvm::StructType *T, 93167645930SMike Stump std::vector<HelperInfo> *NoteForHelperp) { 9320c743277SMike Stump QualType R = getContext().VoidTy; 9330c743277SMike Stump 9340c743277SMike Stump FunctionArgList Args; 9350c743277SMike Stump // FIXME: This leaks 936aeb0ffd5SMike Stump ImplicitParamDecl *Dst = 9377fe9cc1dSMike Stump ImplicitParamDecl::Create(getContext(), 0, 9387fe9cc1dSMike Stump SourceLocation(), 0, 939aeb0ffd5SMike Stump getContext().getPointerType(getContext().VoidTy)); 940aeb0ffd5SMike Stump Args.push_back(std::make_pair(Dst, Dst->getType())); 9410c743277SMike Stump ImplicitParamDecl *Src = 9427fe9cc1dSMike Stump ImplicitParamDecl::Create(getContext(), 0, 9437fe9cc1dSMike Stump SourceLocation(), 0, 9440c743277SMike Stump getContext().getPointerType(getContext().VoidTy)); 9450c743277SMike Stump Args.push_back(std::make_pair(Src, Src->getType())); 9460c743277SMike Stump 9470c743277SMike Stump const CGFunctionInfo &FI = 948c50c27ccSRafael Espindola CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo()); 9490c743277SMike Stump 950cbc2bcafSMike Stump // FIXME: We'd like to put these into a mergable by content, with 951cbc2bcafSMike Stump // internal linkage. 9520c743277SMike Stump CodeGenTypes &Types = CGM.getTypes(); 9530c743277SMike Stump const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false); 9540c743277SMike Stump 9550c743277SMike Stump llvm::Function *Fn = 9560c743277SMike Stump llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 957d6b28fc6SBenjamin Kramer "__copy_helper_block_", &CGM.getModule()); 9580c743277SMike Stump 9590c743277SMike Stump IdentifierInfo *II 9600c743277SMike Stump = &CGM.getContext().Idents.get("__copy_helper_block_"); 9610c743277SMike Stump 9620c743277SMike Stump FunctionDecl *FD = FunctionDecl::Create(getContext(), 9630c743277SMike Stump getContext().getTranslationUnitDecl(), 96460ed5604SArgyrios Kyrtzidis SourceLocation(), II, R, 0, 965c4df4076SDouglas Gregor FunctionDecl::Static, 966c4df4076SDouglas Gregor FunctionDecl::None, 967c4df4076SDouglas Gregor false, 9680c743277SMike Stump true); 9690c743277SMike Stump CGF.StartFunction(FD, R, Fn, Args, SourceLocation()); 970aeb0ffd5SMike Stump 971aeb0ffd5SMike Stump llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src); 972aeb0ffd5SMike Stump llvm::Type *PtrPtrT; 97367645930SMike Stump 97467645930SMike Stump if (NoteForHelperp) { 97567645930SMike Stump std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp; 97667645930SMike Stump 9779793f0e4SOwen Anderson PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0); 978aeb0ffd5SMike Stump SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT); 979aeb0ffd5SMike Stump SrcObj = Builder.CreateLoad(SrcObj); 980aeb0ffd5SMike Stump 981aeb0ffd5SMike Stump llvm::Value *DstObj = CGF.GetAddrOfLocalVar(Dst); 9823b65ac26SMike Stump llvm::Type *PtrPtrT; 9839793f0e4SOwen Anderson PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0); 9843b65ac26SMike Stump DstObj = Builder.CreateBitCast(DstObj, PtrPtrT); 9853b65ac26SMike Stump DstObj = Builder.CreateLoad(DstObj); 986aeb0ffd5SMike Stump 987aeb0ffd5SMike Stump for (unsigned i=0; i < NoteForHelper.size(); ++i) { 988aeb0ffd5SMike Stump int flag = NoteForHelper[i].flag; 989aeb0ffd5SMike Stump int index = NoteForHelper[i].index; 990aeb0ffd5SMike Stump 991aeb0ffd5SMike Stump if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF) 992aeb0ffd5SMike Stump || NoteForHelper[i].RequiresCopying) { 993aeb0ffd5SMike Stump llvm::Value *Srcv = SrcObj; 994aeb0ffd5SMike Stump Srcv = Builder.CreateStructGEP(Srcv, index); 995aeb0ffd5SMike Stump Srcv = Builder.CreateBitCast(Srcv, 9969793f0e4SOwen Anderson llvm::PointerType::get(PtrToInt8Ty, 0)); 997aeb0ffd5SMike Stump Srcv = Builder.CreateLoad(Srcv); 998aeb0ffd5SMike Stump 999aeb0ffd5SMike Stump llvm::Value *Dstv = Builder.CreateStructGEP(DstObj, index); 1000aeb0ffd5SMike Stump Dstv = Builder.CreateBitCast(Dstv, PtrToInt8Ty); 1001aeb0ffd5SMike Stump 10025e016ae9SChris Lattner llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag); 1003900546d2SDaniel Dunbar llvm::Value *F = CGM.getBlockObjectAssign(); 1004aeb0ffd5SMike Stump Builder.CreateCall3(F, Dstv, Srcv, N); 1005aeb0ffd5SMike Stump } 1006aeb0ffd5SMike Stump } 100767645930SMike Stump } 1008aeb0ffd5SMike Stump 10090c743277SMike Stump CGF.FinishFunction(); 10100c743277SMike Stump 1011ade90fd1SOwen Anderson return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty); 101297d01d50SMike Stump } 101397d01d50SMike Stump 1014d6ef62f0SMike Stump llvm::Constant *BlockFunction:: 1015aeb0ffd5SMike Stump GenerateDestroyHelperFunction(bool BlockHasCopyDispose, 1016aeb0ffd5SMike Stump const llvm::StructType* T, 101767645930SMike Stump std::vector<HelperInfo> *NoteForHelperp) { 10180c743277SMike Stump QualType R = getContext().VoidTy; 10190c743277SMike Stump 10200c743277SMike Stump FunctionArgList Args; 10210c743277SMike Stump // FIXME: This leaks 10220c743277SMike Stump ImplicitParamDecl *Src = 10237fe9cc1dSMike Stump ImplicitParamDecl::Create(getContext(), 0, 10247fe9cc1dSMike Stump SourceLocation(), 0, 10250c743277SMike Stump getContext().getPointerType(getContext().VoidTy)); 10260c743277SMike Stump 10270c743277SMike Stump Args.push_back(std::make_pair(Src, Src->getType())); 10280c743277SMike Stump 10290c743277SMike Stump const CGFunctionInfo &FI = 1030c50c27ccSRafael Espindola CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo()); 10310c743277SMike Stump 1032cbc2bcafSMike Stump // FIXME: We'd like to put these into a mergable by content, with 1033cbc2bcafSMike Stump // internal linkage. 10340c743277SMike Stump CodeGenTypes &Types = CGM.getTypes(); 10350c743277SMike Stump const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false); 10360c743277SMike Stump 10370c743277SMike Stump llvm::Function *Fn = 10380c743277SMike Stump llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1039d6b28fc6SBenjamin Kramer "__destroy_helper_block_", &CGM.getModule()); 10400c743277SMike Stump 10410c743277SMike Stump IdentifierInfo *II 10420c743277SMike Stump = &CGM.getContext().Idents.get("__destroy_helper_block_"); 10430c743277SMike Stump 10440c743277SMike Stump FunctionDecl *FD = FunctionDecl::Create(getContext(), 10450c743277SMike Stump getContext().getTranslationUnitDecl(), 104660ed5604SArgyrios Kyrtzidis SourceLocation(), II, R, 0, 1047c4df4076SDouglas Gregor FunctionDecl::Static, 1048c4df4076SDouglas Gregor FunctionDecl::None, 1049c4df4076SDouglas Gregor false, true); 10500c743277SMike Stump CGF.StartFunction(FD, R, Fn, Args, SourceLocation()); 10516f7d9f87SMike Stump 105267645930SMike Stump if (NoteForHelperp) { 105367645930SMike Stump std::vector<HelperInfo> &NoteForHelper = *NoteForHelperp; 105467645930SMike Stump 10556f7d9f87SMike Stump llvm::Value *SrcObj = CGF.GetAddrOfLocalVar(Src); 10566f7d9f87SMike Stump llvm::Type *PtrPtrT; 10579793f0e4SOwen Anderson PtrPtrT = llvm::PointerType::get(llvm::PointerType::get(T, 0), 0); 10586f7d9f87SMike Stump SrcObj = Builder.CreateBitCast(SrcObj, PtrPtrT); 10596f7d9f87SMike Stump SrcObj = Builder.CreateLoad(SrcObj); 10606f7d9f87SMike Stump 10616f7d9f87SMike Stump for (unsigned i=0; i < NoteForHelper.size(); ++i) { 10626f7d9f87SMike Stump int flag = NoteForHelper[i].flag; 10636f7d9f87SMike Stump int index = NoteForHelper[i].index; 10646f7d9f87SMike Stump 10656f7d9f87SMike Stump if ((NoteForHelper[i].flag & BLOCK_FIELD_IS_BYREF) 10666f7d9f87SMike Stump || NoteForHelper[i].RequiresCopying) { 10676f7d9f87SMike Stump llvm::Value *Srcv = SrcObj; 10686f7d9f87SMike Stump Srcv = Builder.CreateStructGEP(Srcv, index); 10696f7d9f87SMike Stump Srcv = Builder.CreateBitCast(Srcv, 10709793f0e4SOwen Anderson llvm::PointerType::get(PtrToInt8Ty, 0)); 10716f7d9f87SMike Stump Srcv = Builder.CreateLoad(Srcv); 10726f7d9f87SMike Stump 10736f7d9f87SMike Stump BuildBlockRelease(Srcv, flag); 10746f7d9f87SMike Stump } 10756f7d9f87SMike Stump } 107667645930SMike Stump } 10776f7d9f87SMike Stump 10780c743277SMike Stump CGF.FinishFunction(); 10790c743277SMike Stump 1080ade90fd1SOwen Anderson return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty); 10810c743277SMike Stump } 10820c743277SMike Stump 1083aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildCopyHelper(const llvm::StructType *T, 108467645930SMike Stump std::vector<HelperInfo> *NoteForHelper) { 1085aeb0ffd5SMike Stump return CodeGenFunction(CGM).GenerateCopyHelperFunction(BlockHasCopyDispose, 1086aeb0ffd5SMike Stump T, NoteForHelper); 10870c743277SMike Stump } 10880c743277SMike Stump 1089aeb0ffd5SMike Stump llvm::Constant *BlockFunction::BuildDestroyHelper(const llvm::StructType *T, 109067645930SMike Stump std::vector<HelperInfo> *NoteForHelperp) { 1091aeb0ffd5SMike Stump return CodeGenFunction(CGM).GenerateDestroyHelperFunction(BlockHasCopyDispose, 109267645930SMike Stump T, NoteForHelperp); 109397d01d50SMike Stump } 1094626aecc4SMike Stump 1095f89230d9SMike Stump llvm::Constant *BlockFunction:: 1096f89230d9SMike Stump GeneratebyrefCopyHelperFunction(const llvm::Type *T, int flag) { 1097ee2a5ee5SMike Stump QualType R = getContext().VoidTy; 1098ee2a5ee5SMike Stump 1099ee2a5ee5SMike Stump FunctionArgList Args; 1100ee2a5ee5SMike Stump // FIXME: This leaks 1101f89230d9SMike Stump ImplicitParamDecl *Dst = 11027fe9cc1dSMike Stump ImplicitParamDecl::Create(getContext(), 0, 11037fe9cc1dSMike Stump SourceLocation(), 0, 1104f89230d9SMike Stump getContext().getPointerType(getContext().VoidTy)); 1105f89230d9SMike Stump Args.push_back(std::make_pair(Dst, Dst->getType())); 1106f89230d9SMike Stump 1107f89230d9SMike Stump // FIXME: This leaks 1108ee2a5ee5SMike Stump ImplicitParamDecl *Src = 11097fe9cc1dSMike Stump ImplicitParamDecl::Create(getContext(), 0, 11107fe9cc1dSMike Stump SourceLocation(), 0, 1111ee2a5ee5SMike Stump getContext().getPointerType(getContext().VoidTy)); 1112ee2a5ee5SMike Stump Args.push_back(std::make_pair(Src, Src->getType())); 1113ee2a5ee5SMike Stump 1114ee2a5ee5SMike Stump const CGFunctionInfo &FI = 1115c50c27ccSRafael Espindola CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo()); 1116ee2a5ee5SMike Stump 1117ee2a5ee5SMike Stump CodeGenTypes &Types = CGM.getTypes(); 1118ee2a5ee5SMike Stump const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false); 1119ee2a5ee5SMike Stump 1120cbc2bcafSMike Stump // FIXME: We'd like to put these into a mergable by content, with 1121cbc2bcafSMike Stump // internal linkage. 1122ee2a5ee5SMike Stump llvm::Function *Fn = 1123ee2a5ee5SMike Stump llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1124d6b28fc6SBenjamin Kramer "__Block_byref_id_object_copy_", &CGM.getModule()); 1125ee2a5ee5SMike Stump 1126ee2a5ee5SMike Stump IdentifierInfo *II 1127ee2a5ee5SMike Stump = &CGM.getContext().Idents.get("__Block_byref_id_object_copy_"); 1128ee2a5ee5SMike Stump 1129ee2a5ee5SMike Stump FunctionDecl *FD = FunctionDecl::Create(getContext(), 1130ee2a5ee5SMike Stump getContext().getTranslationUnitDecl(), 113160ed5604SArgyrios Kyrtzidis SourceLocation(), II, R, 0, 1132c4df4076SDouglas Gregor FunctionDecl::Static, 1133c4df4076SDouglas Gregor FunctionDecl::None, 1134c4df4076SDouglas Gregor false, true); 1135ee2a5ee5SMike Stump CGF.StartFunction(FD, R, Fn, Args, SourceLocation()); 1136f89230d9SMike Stump 1137f89230d9SMike Stump // dst->x 1138f89230d9SMike Stump llvm::Value *V = CGF.GetAddrOfLocalVar(Dst); 11399793f0e4SOwen Anderson V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0)); 11403b65ac26SMike Stump V = Builder.CreateLoad(V); 1141f89230d9SMike Stump V = Builder.CreateStructGEP(V, 6, "x"); 1142f89230d9SMike Stump llvm::Value *DstObj = Builder.CreateBitCast(V, PtrToInt8Ty); 1143f89230d9SMike Stump 1144f89230d9SMike Stump // src->x 1145f89230d9SMike Stump V = CGF.GetAddrOfLocalVar(Src); 1146f89230d9SMike Stump V = Builder.CreateLoad(V); 1147f89230d9SMike Stump V = Builder.CreateBitCast(V, T); 1148f89230d9SMike Stump V = Builder.CreateStructGEP(V, 6, "x"); 11499793f0e4SOwen Anderson V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0)); 1150f89230d9SMike Stump llvm::Value *SrcObj = Builder.CreateLoad(V); 1151f89230d9SMike Stump 1152f89230d9SMike Stump flag |= BLOCK_BYREF_CALLER; 1153f89230d9SMike Stump 11545e016ae9SChris Lattner llvm::Value *N = llvm::ConstantInt::get(CGF.Int32Ty, flag); 1155900546d2SDaniel Dunbar llvm::Value *F = CGM.getBlockObjectAssign(); 1156f89230d9SMike Stump Builder.CreateCall3(F, DstObj, SrcObj, N); 1157f89230d9SMike Stump 1158ee2a5ee5SMike Stump CGF.FinishFunction(); 1159ee2a5ee5SMike Stump 1160ade90fd1SOwen Anderson return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty); 1161ee2a5ee5SMike Stump } 1162ee2a5ee5SMike Stump 1163fbe25dd1SMike Stump llvm::Constant * 1164fbe25dd1SMike Stump BlockFunction::GeneratebyrefDestroyHelperFunction(const llvm::Type *T, 1165fbe25dd1SMike Stump int flag) { 1166ee2a5ee5SMike Stump QualType R = getContext().VoidTy; 1167ee2a5ee5SMike Stump 1168ee2a5ee5SMike Stump FunctionArgList Args; 1169ee2a5ee5SMike Stump // FIXME: This leaks 1170ee2a5ee5SMike Stump ImplicitParamDecl *Src = 11717fe9cc1dSMike Stump ImplicitParamDecl::Create(getContext(), 0, 11727fe9cc1dSMike Stump SourceLocation(), 0, 1173ee2a5ee5SMike Stump getContext().getPointerType(getContext().VoidTy)); 1174ee2a5ee5SMike Stump 1175ee2a5ee5SMike Stump Args.push_back(std::make_pair(Src, Src->getType())); 1176ee2a5ee5SMike Stump 1177ee2a5ee5SMike Stump const CGFunctionInfo &FI = 1178c50c27ccSRafael Espindola CGM.getTypes().getFunctionInfo(R, Args, FunctionType::ExtInfo()); 1179ee2a5ee5SMike Stump 1180ee2a5ee5SMike Stump CodeGenTypes &Types = CGM.getTypes(); 1181ee2a5ee5SMike Stump const llvm::FunctionType *LTy = Types.GetFunctionType(FI, false); 1182ee2a5ee5SMike Stump 1183cbc2bcafSMike Stump // FIXME: We'd like to put these into a mergable by content, with 1184cbc2bcafSMike Stump // internal linkage. 1185ee2a5ee5SMike Stump llvm::Function *Fn = 1186ee2a5ee5SMike Stump llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage, 1187d6b28fc6SBenjamin Kramer "__Block_byref_id_object_dispose_", 1188ee2a5ee5SMike Stump &CGM.getModule()); 1189ee2a5ee5SMike Stump 1190ee2a5ee5SMike Stump IdentifierInfo *II 1191ee2a5ee5SMike Stump = &CGM.getContext().Idents.get("__Block_byref_id_object_dispose_"); 1192ee2a5ee5SMike Stump 1193ee2a5ee5SMike Stump FunctionDecl *FD = FunctionDecl::Create(getContext(), 1194ee2a5ee5SMike Stump getContext().getTranslationUnitDecl(), 119560ed5604SArgyrios Kyrtzidis SourceLocation(), II, R, 0, 1196c4df4076SDouglas Gregor FunctionDecl::Static, 1197c4df4076SDouglas Gregor FunctionDecl::None, 1198c4df4076SDouglas Gregor false, true); 1199ee2a5ee5SMike Stump CGF.StartFunction(FD, R, Fn, Args, SourceLocation()); 1200fbe25dd1SMike Stump 1201fbe25dd1SMike Stump llvm::Value *V = CGF.GetAddrOfLocalVar(Src); 12029793f0e4SOwen Anderson V = Builder.CreateBitCast(V, llvm::PointerType::get(T, 0)); 12033b65ac26SMike Stump V = Builder.CreateLoad(V); 1204fbe25dd1SMike Stump V = Builder.CreateStructGEP(V, 6, "x"); 12059793f0e4SOwen Anderson V = Builder.CreateBitCast(V, llvm::PointerType::get(PtrToInt8Ty, 0)); 12063b65ac26SMike Stump V = Builder.CreateLoad(V); 1207fbe25dd1SMike Stump 1208fbe25dd1SMike Stump flag |= BLOCK_BYREF_CALLER; 1209fbe25dd1SMike Stump BuildBlockRelease(V, flag); 1210ee2a5ee5SMike Stump CGF.FinishFunction(); 1211ee2a5ee5SMike Stump 1212ade90fd1SOwen Anderson return llvm::ConstantExpr::getBitCast(Fn, PtrToInt8Ty); 1213ee2a5ee5SMike Stump } 1214ee2a5ee5SMike Stump 1215f89230d9SMike Stump llvm::Constant *BlockFunction::BuildbyrefCopyHelper(const llvm::Type *T, 1216e08ea787SChris Lattner int Flag, unsigned Align) { 1217e08ea787SChris Lattner // All alignments below that of pointer alignment collapse down to just 1218cbc2bcafSMike Stump // pointer alignment, as we always have at least that much alignment to begin 1219cbc2bcafSMike Stump // with. 1220cbc2bcafSMike Stump Align /= unsigned(CGF.Target.getPointerAlign(0)/8); 1221e08ea787SChris Lattner 1222cbc2bcafSMike Stump // As an optimization, we only generate a single function of each kind we 1223cbc2bcafSMike Stump // might need. We need a different one for each alignment and for each 1224cbc2bcafSMike Stump // setting of flags. We mix Align and flag to get the kind. 1225e08ea787SChris Lattner uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag; 1226e08ea787SChris Lattner llvm::Constant *&Entry = CGM.AssignCache[Kind]; 1227cbc2bcafSMike Stump if (Entry) 1228cbc2bcafSMike Stump return Entry; 1229e08ea787SChris Lattner return Entry = CodeGenFunction(CGM).GeneratebyrefCopyHelperFunction(T, Flag); 1230ee2a5ee5SMike Stump } 1231ee2a5ee5SMike Stump 1232fbe25dd1SMike Stump llvm::Constant *BlockFunction::BuildbyrefDestroyHelper(const llvm::Type *T, 1233e08ea787SChris Lattner int Flag, 1234cbc2bcafSMike Stump unsigned Align) { 1235cbc2bcafSMike Stump // All alignments below that of pointer alignment collpase down to just 1236cbc2bcafSMike Stump // pointer alignment, as we always have at least that much alignment to begin 1237cbc2bcafSMike Stump // with. 1238cbc2bcafSMike Stump Align /= unsigned(CGF.Target.getPointerAlign(0)/8); 1239e08ea787SChris Lattner 1240cbc2bcafSMike Stump // As an optimization, we only generate a single function of each kind we 1241cbc2bcafSMike Stump // might need. We need a different one for each alignment and for each 1242cbc2bcafSMike Stump // setting of flags. We mix Align and flag to get the kind. 1243e08ea787SChris Lattner uint64_t Kind = (uint64_t)Align*BLOCK_BYREF_CURRENT_MAX + Flag; 1244e08ea787SChris Lattner llvm::Constant *&Entry = CGM.DestroyCache[Kind]; 1245cbc2bcafSMike Stump if (Entry) 1246cbc2bcafSMike Stump return Entry; 1247e08ea787SChris Lattner return Entry=CodeGenFunction(CGM).GeneratebyrefDestroyHelperFunction(T, Flag); 1248ee2a5ee5SMike Stump } 1249ee2a5ee5SMike Stump 1250fbe25dd1SMike Stump void BlockFunction::BuildBlockRelease(llvm::Value *V, int flag) { 1251900546d2SDaniel Dunbar llvm::Value *F = CGM.getBlockObjectDispose(); 1252fbe25dd1SMike Stump llvm::Value *N; 1253626aecc4SMike Stump V = Builder.CreateBitCast(V, PtrToInt8Ty); 12545e016ae9SChris Lattner N = llvm::ConstantInt::get(CGF.Int32Ty, flag); 1255626aecc4SMike Stump Builder.CreateCall2(F, V, N); 1256626aecc4SMike Stump } 12574446dcf0SMike Stump 12584446dcf0SMike Stump ASTContext &BlockFunction::getContext() const { return CGM.getContext(); } 1259aeb0ffd5SMike Stump 1260aeb0ffd5SMike Stump BlockFunction::BlockFunction(CodeGenModule &cgm, CodeGenFunction &cgf, 1261aeb0ffd5SMike Stump CGBuilderTy &B) 12625e016ae9SChris Lattner : CGM(cgm), VMContext(cgm.getLLVMContext()), CGF(cgf), Builder(B) { 126341a75027SOwen Anderson PtrToInt8Ty = llvm::PointerType::getUnqual( 126441a75027SOwen Anderson llvm::Type::getInt8Ty(VMContext)); 1265aeb0ffd5SMike Stump 1266aeb0ffd5SMike Stump BlockHasCopyDispose = false; 1267aeb0ffd5SMike Stump } 1268