Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 1 | //===--- RewriteBlocks.cpp ----------------------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // Hacks and fun related to the closure rewriter. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "ASTConsumers.h" |
| 15 | #include "clang/Rewrite/Rewriter.h" |
| 16 | #include "clang/AST/AST.h" |
| 17 | #include "clang/AST/ASTConsumer.h" |
| 18 | #include "clang/Basic/SourceManager.h" |
| 19 | #include "clang/Basic/IdentifierTable.h" |
| 20 | #include "clang/Basic/Diagnostic.h" |
| 21 | #include "clang/Basic/LangOptions.h" |
| 22 | #include "llvm/Support/MemoryBuffer.h" |
| 23 | #include "llvm/ADT/StringExtras.h" |
| 24 | #include "llvm/ADT/SmallPtrSet.h" |
| 25 | #include <sstream> |
| 26 | |
| 27 | using namespace clang; |
| 28 | using llvm::utostr; |
| 29 | |
| 30 | namespace { |
| 31 | |
| 32 | class RewriteBlocks : public ASTConsumer { |
| 33 | Rewriter Rewrite; |
| 34 | Diagnostic &Diags; |
| 35 | const LangOptions &LangOpts; |
| 36 | unsigned RewriteFailedDiag; |
| 37 | unsigned NoNestedBlockCalls; |
| 38 | |
| 39 | ASTContext *Context; |
| 40 | SourceManager *SM; |
| 41 | unsigned MainFileID; |
| 42 | const char *MainFileStart, *MainFileEnd; |
| 43 | |
| 44 | // Block expressions. |
| 45 | llvm::SmallVector<BlockExpr *, 32> Blocks; |
| 46 | llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs; |
| 47 | llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs; |
| 48 | |
| 49 | // Block related declarations. |
| 50 | llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls; |
| 51 | llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 52 | llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls; |
Steve Naroff | 70f9550 | 2008-10-04 17:06:23 +0000 | [diff] [blame] | 53 | |
| 54 | llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 55 | |
| 56 | // The function/method we are rewriting. |
| 57 | FunctionDecl *CurFunctionDef; |
| 58 | ObjCMethodDecl *CurMethodDef; |
| 59 | |
| 60 | bool IsHeader; |
Steve Naroff | 1318895 | 2008-09-18 14:10:13 +0000 | [diff] [blame] | 61 | std::string InFileName; |
| 62 | std::string OutFileName; |
Steve Naroff | a0b75cf | 2008-10-02 23:30:43 +0000 | [diff] [blame] | 63 | |
| 64 | std::string Preamble; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 65 | public: |
Steve Naroff | 1318895 | 2008-09-18 14:10:13 +0000 | [diff] [blame] | 66 | RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D, |
| 67 | const LangOptions &LOpts); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 68 | ~RewriteBlocks() { |
| 69 | // Get the buffer corresponding to MainFileID. |
| 70 | // If we haven't changed it, then we are done. |
| 71 | if (const RewriteBuffer *RewriteBuf = |
| 72 | Rewrite.getRewriteBufferFor(MainFileID)) { |
| 73 | std::string S(RewriteBuf->begin(), RewriteBuf->end()); |
| 74 | printf("%s\n", S.c_str()); |
| 75 | } else { |
| 76 | printf("No changes\n"); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | void Initialize(ASTContext &context); |
| 81 | |
| 82 | void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen); |
| 83 | void ReplaceText(SourceLocation Start, unsigned OrigLength, |
| 84 | const char *NewStr, unsigned NewLength); |
| 85 | |
| 86 | // Top Level Driver code. |
| 87 | virtual void HandleTopLevelDecl(Decl *D); |
| 88 | void HandleDeclInMainFile(Decl *D); |
| 89 | |
| 90 | // Top level |
| 91 | Stmt *RewriteFunctionBody(Stmt *S); |
| 92 | void InsertBlockLiteralsWithinFunction(FunctionDecl *FD); |
| 93 | void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD); |
| 94 | |
| 95 | // Block specific rewrite rules. |
Steve Naroff | 70f9550 | 2008-10-04 17:06:23 +0000 | [diff] [blame] | 96 | std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 97 | |
| 98 | void RewriteBlockCall(CallExpr *Exp); |
| 99 | void RewriteBlockPointerDecl(NamedDecl *VD); |
| 100 | void RewriteBlockPointerFunctionArgs(FunctionDecl *FD); |
| 101 | |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 102 | std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, |
| 103 | const char *funcName, std::string Tag); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 104 | std::string SynthesizeBlockFunc(BlockExpr *CE, int i, |
| 105 | const char *funcName, std::string Tag); |
| 106 | std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag); |
| 107 | std::string SynthesizeBlockCall(CallExpr *Exp); |
| 108 | void SynthesizeBlockLiterals(SourceLocation FunLocStart, |
| 109 | const char *FunName); |
| 110 | |
| 111 | void GetBlockDeclRefExprs(Stmt *S); |
| 112 | void GetBlockCallExprs(Stmt *S); |
| 113 | |
| 114 | // We avoid calling Type::isBlockPointerType(), since it operates on the |
| 115 | // canonical type. We only care if the top-level type is a closure pointer. |
| 116 | bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); } |
| 117 | |
| 118 | // FIXME: This predicate seems like it would be useful to add to ASTContext. |
| 119 | bool isObjCType(QualType T) { |
| 120 | if (!LangOpts.ObjC1 && !LangOpts.ObjC2) |
| 121 | return false; |
| 122 | |
| 123 | QualType OCT = Context->getCanonicalType(T).getUnqualifiedType(); |
| 124 | |
| 125 | if (OCT == Context->getCanonicalType(Context->getObjCIdType()) || |
| 126 | OCT == Context->getCanonicalType(Context->getObjCClassType())) |
| 127 | return true; |
| 128 | |
| 129 | if (const PointerType *PT = OCT->getAsPointerType()) { |
| 130 | if (isa<ObjCInterfaceType>(PT->getPointeeType()) || |
| 131 | isa<ObjCQualifiedIdType>(PT->getPointeeType())) |
| 132 | return true; |
| 133 | } |
| 134 | return false; |
| 135 | } |
| 136 | // ObjC rewrite methods. |
| 137 | void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl); |
| 138 | void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl); |
| 139 | void RewriteProtocolDecl(ObjCProtocolDecl *PDecl); |
| 140 | void RewriteMethodDecl(ObjCMethodDecl *MDecl); |
Steve Naroff | eab5f63 | 2008-09-23 19:24:41 +0000 | [diff] [blame] | 141 | |
| 142 | bool BlockPointerTypeTakesAnyBlockArguments(QualType QT); |
Steve Naroff | 1f6c3ae | 2008-09-24 17:22:34 +0000 | [diff] [blame] | 143 | void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 144 | }; |
| 145 | |
| 146 | } |
| 147 | |
| 148 | static bool IsHeaderFile(const std::string &Filename) { |
| 149 | std::string::size_type DotPos = Filename.rfind('.'); |
| 150 | |
| 151 | if (DotPos == std::string::npos) { |
| 152 | // no file extension |
| 153 | return false; |
| 154 | } |
| 155 | |
| 156 | std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end()); |
| 157 | // C header: .h |
| 158 | // C++ header: .hh or .H; |
| 159 | return Ext == "h" || Ext == "hh" || Ext == "H"; |
| 160 | } |
| 161 | |
Steve Naroff | 1318895 | 2008-09-18 14:10:13 +0000 | [diff] [blame] | 162 | RewriteBlocks::RewriteBlocks(std::string inFile, std::string outFile, |
| 163 | Diagnostic &D, const LangOptions &LOpts) : |
| 164 | Diags(D), LangOpts(LOpts) { |
| 165 | IsHeader = IsHeaderFile(inFile); |
| 166 | InFileName = inFile; |
| 167 | OutFileName = outFile; |
| 168 | CurFunctionDef = 0; |
| 169 | CurMethodDef = 0; |
| 170 | RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning, |
| 171 | "rewriting failed"); |
| 172 | NoNestedBlockCalls = Diags.getCustomDiagID(Diagnostic::Warning, |
| 173 | "Rewrite support for closure calls nested within closure blocks is incomplete"); |
| 174 | } |
| 175 | |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 176 | ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile, |
Steve Naroff | 1318895 | 2008-09-18 14:10:13 +0000 | [diff] [blame] | 177 | const std::string& OutFile, |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 178 | Diagnostic &Diags, |
| 179 | const LangOptions &LangOpts) { |
Steve Naroff | 1318895 | 2008-09-18 14:10:13 +0000 | [diff] [blame] | 180 | return new RewriteBlocks(InFile, OutFile, Diags, LangOpts); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 181 | } |
| 182 | |
| 183 | void RewriteBlocks::Initialize(ASTContext &context) { |
| 184 | Context = &context; |
| 185 | SM = &Context->getSourceManager(); |
| 186 | |
| 187 | // Get the ID and start/end of the main file. |
| 188 | MainFileID = SM->getMainFileID(); |
| 189 | const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID); |
| 190 | MainFileStart = MainBuf->getBufferStart(); |
| 191 | MainFileEnd = MainBuf->getBufferEnd(); |
| 192 | |
| 193 | Rewrite.setSourceMgr(Context->getSourceManager()); |
| 194 | |
Steve Naroff | a0b75cf | 2008-10-02 23:30:43 +0000 | [diff] [blame] | 195 | if (IsHeader) |
| 196 | Preamble = "#pragma once\n"; |
| 197 | Preamble += "#ifndef BLOCK_IMPL\n"; |
| 198 | Preamble += "#define BLOCK_IMPL\n"; |
| 199 | Preamble += "struct __block_impl {\n"; |
| 200 | Preamble += " void *isa;\n"; |
| 201 | Preamble += " int Flags;\n"; |
| 202 | Preamble += " int Size;\n"; |
| 203 | Preamble += " void *FuncPtr;\n"; |
| 204 | Preamble += "};\n"; |
| 205 | Preamble += "enum {\n"; |
| 206 | Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n"; |
| 207 | Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n"; |
| 208 | Preamble += "};\n"; |
| 209 | if (LangOpts.Microsoft) |
| 210 | Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n"; |
| 211 | else |
| 212 | Preamble += "#define __OBJC_RW_EXTERN extern\n"; |
| 213 | Preamble += "// Runtime copy/destroy helper functions\n"; |
| 214 | Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n"; |
| 215 | Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n"; |
| 216 | Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n"; |
| 217 | Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n"; |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 218 | Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n"; |
| 219 | Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n"; |
Steve Naroff | a0b75cf | 2008-10-02 23:30:43 +0000 | [diff] [blame] | 220 | Preamble += "#endif\n"; |
| 221 | |
| 222 | InsertText(SourceLocation::getFileLoc(MainFileID, 0), |
| 223 | Preamble.c_str(), Preamble.size()); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 224 | } |
| 225 | |
| 226 | void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData, |
| 227 | unsigned StrLen) |
| 228 | { |
| 229 | if (!Rewrite.InsertText(Loc, StrData, StrLen)) |
| 230 | return; |
| 231 | Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag); |
| 232 | } |
| 233 | |
| 234 | void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength, |
| 235 | const char *NewStr, unsigned NewLength) { |
| 236 | if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength)) |
| 237 | return; |
| 238 | Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag); |
| 239 | } |
| 240 | |
| 241 | void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) { |
| 242 | bool haveBlockPtrs = false; |
| 243 | for (ObjCMethodDecl::param_iterator I = Method->param_begin(), |
| 244 | E = Method->param_end(); I != E; ++I) |
| 245 | if (isBlockPointerType((*I)->getType())) |
| 246 | haveBlockPtrs = true; |
| 247 | |
| 248 | if (!haveBlockPtrs) |
| 249 | return; |
| 250 | |
| 251 | // Do a fuzzy rewrite. |
| 252 | // We have 1 or more arguments that have closure pointers. |
| 253 | SourceLocation Loc = Method->getLocStart(); |
| 254 | SourceLocation LocEnd = Method->getLocEnd(); |
| 255 | const char *startBuf = SM->getCharacterData(Loc); |
| 256 | const char *endBuf = SM->getCharacterData(LocEnd); |
| 257 | |
| 258 | const char *methodPtr = startBuf; |
Steve Naroff | 8af6a45 | 2008-10-02 17:12:56 +0000 | [diff] [blame] | 259 | std::string Tag = "struct __block_impl *"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 260 | |
| 261 | while (*methodPtr++ && (methodPtr != endBuf)) { |
| 262 | switch (*methodPtr) { |
| 263 | case ':': |
| 264 | methodPtr++; |
| 265 | if (*methodPtr == '(') { |
| 266 | const char *scanType = ++methodPtr; |
| 267 | bool foundBlockPointer = false; |
| 268 | unsigned parenCount = 1; |
| 269 | |
| 270 | while (parenCount) { |
| 271 | switch (*scanType) { |
| 272 | case '(': |
| 273 | parenCount++; |
| 274 | break; |
| 275 | case ')': |
| 276 | parenCount--; |
| 277 | break; |
| 278 | case '^': |
| 279 | foundBlockPointer = true; |
| 280 | break; |
| 281 | } |
| 282 | scanType++; |
| 283 | } |
| 284 | if (foundBlockPointer) { |
| 285 | // advance the location to startArgList. |
| 286 | Loc = Loc.getFileLocWithOffset(methodPtr-startBuf); |
| 287 | assert((Loc.isValid()) && "Invalid Loc"); |
| 288 | ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size()); |
| 289 | |
| 290 | // Advance startBuf. Since the underlying buffer has changed, |
| 291 | // it's very important to advance startBuf (so we can correctly |
| 292 | // compute a relative Loc the next time around). |
| 293 | startBuf = methodPtr; |
| 294 | } |
| 295 | // Advance the method ptr to the end of the type. |
| 296 | methodPtr = scanType; |
| 297 | } |
| 298 | break; |
| 299 | } |
| 300 | } |
| 301 | return; |
| 302 | } |
| 303 | |
| 304 | void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) { |
| 305 | for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(), |
| 306 | E = ClassDecl->instmeth_end(); I != E; ++I) |
| 307 | RewriteMethodDecl(*I); |
| 308 | for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(), |
| 309 | E = ClassDecl->classmeth_end(); I != E; ++I) |
| 310 | RewriteMethodDecl(*I); |
| 311 | } |
| 312 | |
| 313 | void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) { |
| 314 | for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(), |
| 315 | E = CatDecl->instmeth_end(); I != E; ++I) |
| 316 | RewriteMethodDecl(*I); |
| 317 | for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(), |
| 318 | E = CatDecl->classmeth_end(); I != E; ++I) |
| 319 | RewriteMethodDecl(*I); |
| 320 | } |
| 321 | |
| 322 | void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) { |
| 323 | for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(), |
| 324 | E = PDecl->instmeth_end(); I != E; ++I) |
| 325 | RewriteMethodDecl(*I); |
| 326 | for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(), |
| 327 | E = PDecl->classmeth_end(); I != E; ++I) |
| 328 | RewriteMethodDecl(*I); |
| 329 | } |
| 330 | |
| 331 | //===----------------------------------------------------------------------===// |
| 332 | // Top Level Driver Code |
| 333 | //===----------------------------------------------------------------------===// |
| 334 | |
| 335 | void RewriteBlocks::HandleTopLevelDecl(Decl *D) { |
| 336 | // Two cases: either the decl could be in the main file, or it could be in a |
| 337 | // #included file. If the former, rewrite it now. If the later, check to see |
| 338 | // if we rewrote the #include/#import. |
| 339 | SourceLocation Loc = D->getLocation(); |
| 340 | Loc = SM->getLogicalLoc(Loc); |
| 341 | |
| 342 | // If this is for a builtin, ignore it. |
| 343 | if (Loc.isInvalid()) return; |
| 344 | |
| 345 | if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) |
| 346 | RewriteInterfaceDecl(MD); |
| 347 | else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) |
| 348 | RewriteCategoryDecl(CD); |
| 349 | else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) |
| 350 | RewriteProtocolDecl(PD); |
| 351 | |
| 352 | // If we have a decl in the main file, see if we should rewrite it. |
| 353 | if (SM->getDecomposedFileLoc(Loc).first == MainFileID) |
| 354 | HandleDeclInMainFile(D); |
| 355 | return; |
| 356 | } |
| 357 | |
| 358 | std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i, |
| 359 | const char *funcName, |
| 360 | std::string Tag) { |
| 361 | const FunctionType *AFT = CE->getFunctionType(); |
| 362 | QualType RT = AFT->getResultType(); |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 363 | std::string StructRef = "struct " + Tag; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 364 | std::string S = "static " + RT.getAsString() + " __" + |
Steve Naroff | a0b75cf | 2008-10-02 23:30:43 +0000 | [diff] [blame] | 365 | funcName + "_" + "block_func_" + utostr(i); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 366 | |
| 367 | if (isa<FunctionTypeNoProto>(AFT)) { |
| 368 | S += "()"; |
| 369 | } else if (CE->arg_empty()) { |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 370 | S += "(" + StructRef + " *__cself)"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 371 | } else { |
| 372 | const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT); |
| 373 | assert(FT && "SynthesizeBlockFunc: No function proto"); |
| 374 | S += '('; |
| 375 | // first add the implicit argument. |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 376 | S += StructRef + " *__cself, "; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 377 | std::string ParamStr; |
Steve Naroff | 9c3c902 | 2008-09-17 18:37:59 +0000 | [diff] [blame] | 378 | for (BlockExpr::arg_iterator AI = CE->arg_begin(), |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 379 | E = CE->arg_end(); AI != E; ++AI) { |
| 380 | if (AI != CE->arg_begin()) S += ", "; |
| 381 | ParamStr = (*AI)->getName(); |
| 382 | (*AI)->getType().getAsStringInternal(ParamStr); |
| 383 | S += ParamStr; |
| 384 | } |
| 385 | if (FT->isVariadic()) { |
| 386 | if (!CE->arg_empty()) S += ", "; |
| 387 | S += "..."; |
| 388 | } |
| 389 | S += ')'; |
| 390 | } |
| 391 | S += " {\n"; |
| 392 | |
| 393 | bool haveByRefDecls = false; |
| 394 | |
| 395 | // Create local declarations to avoid rewriting all closure decl ref exprs. |
| 396 | // First, emit a declaration for all "by ref" decls. |
| 397 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 398 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 399 | // Note: It is not possible to have "by ref" closure pointer decls. |
| 400 | haveByRefDecls = true; |
| 401 | S += " "; |
| 402 | std::string Name = (*I)->getName(); |
| 403 | Context->getPointerType((*I)->getType()).getAsStringInternal(Name); |
| 404 | S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n"; |
| 405 | } |
| 406 | // Next, emit a declaration for all "by copy" declarations. |
| 407 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 408 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 409 | S += " "; |
| 410 | std::string Name = (*I)->getName(); |
| 411 | // Handle nested closure invocation. For example: |
| 412 | // |
| 413 | // void (^myImportedClosure)(void); |
| 414 | // myImportedClosure = ^(void) { setGlobalInt(x + y); }; |
| 415 | // |
| 416 | // void (^anotherClosure)(void); |
| 417 | // anotherClosure = ^(void) { |
| 418 | // myImportedClosure(); // import and invoke the closure |
| 419 | // }; |
| 420 | // |
| 421 | if (isBlockPointerType((*I)->getType())) |
Steve Naroff | 8af6a45 | 2008-10-02 17:12:56 +0000 | [diff] [blame] | 422 | S += "struct __block_impl *"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 423 | else |
| 424 | (*I)->getType().getAsStringInternal(Name); |
| 425 | S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 426 | } |
Steve Naroff | 70f9550 | 2008-10-04 17:06:23 +0000 | [diff] [blame] | 427 | std::string RewrittenStr = RewrittenBlockExprs[CE]; |
| 428 | const char *cstr = RewrittenStr.c_str(); |
| 429 | while (*cstr++ != '{') ; |
| 430 | S += cstr; |
| 431 | S += "\n"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 432 | return S; |
| 433 | } |
| 434 | |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 435 | std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i, |
| 436 | const char *funcName, |
| 437 | std::string Tag) { |
| 438 | std::string StructRef = "struct " + Tag; |
| 439 | std::string S = "static void __"; |
| 440 | |
| 441 | S += funcName; |
| 442 | S += "_block_copy_" + utostr(i); |
| 443 | S += "(" + StructRef; |
| 444 | S += "*dst, " + StructRef; |
| 445 | S += "*src) {"; |
| 446 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(), |
| 447 | E = ImportedBlockDecls.end(); I != E; ++I) { |
| 448 | S += "_Block_copy_assign(&dst->"; |
| 449 | S += (*I)->getName(); |
| 450 | S += ", src->"; |
| 451 | S += (*I)->getName(); |
| 452 | S += ");}"; |
| 453 | } |
| 454 | S += "\nstatic void __"; |
| 455 | S += funcName; |
| 456 | S += "_block_dispose_" + utostr(i); |
| 457 | S += "(" + StructRef; |
| 458 | S += "*src) {"; |
| 459 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(), |
| 460 | E = ImportedBlockDecls.end(); I != E; ++I) { |
| 461 | S += "_Block_destroy(src->"; |
| 462 | S += (*I)->getName(); |
| 463 | S += ");"; |
| 464 | } |
| 465 | S += "}\n"; |
| 466 | return S; |
| 467 | } |
| 468 | |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 469 | std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag) { |
| 470 | std::string S = "struct " + Tag; |
| 471 | std::string Constructor = " " + Tag; |
| 472 | |
| 473 | S += " {\n struct __block_impl impl;\n"; |
| 474 | Constructor += "(void *fp"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 475 | |
| 476 | GetBlockDeclRefExprs(CE); |
| 477 | if (BlockDeclRefs.size()) { |
| 478 | // Unique all "by copy" declarations. |
| 479 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
| 480 | if (!BlockDeclRefs[i]->isByRef()) |
| 481 | BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl()); |
| 482 | // Unique all "by ref" declarations. |
| 483 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
| 484 | if (BlockDeclRefs[i]->isByRef()) |
| 485 | BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl()); |
| 486 | |
| 487 | // Output all "by copy" declarations. |
| 488 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 489 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 490 | S += " "; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 491 | std::string FieldName = (*I)->getName(); |
| 492 | std::string ArgName = "_" + FieldName; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 493 | // Handle nested closure invocation. For example: |
| 494 | // |
| 495 | // void (^myImportedBlock)(void); |
| 496 | // myImportedBlock = ^(void) { setGlobalInt(x + y); }; |
| 497 | // |
| 498 | // void (^anotherBlock)(void); |
| 499 | // anotherBlock = ^(void) { |
| 500 | // myImportedBlock(); // import and invoke the closure |
| 501 | // }; |
| 502 | // |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 503 | if (isBlockPointerType((*I)->getType())) { |
Steve Naroff | 8af6a45 | 2008-10-02 17:12:56 +0000 | [diff] [blame] | 504 | S += "struct __block_impl *"; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 505 | Constructor += ", void *" + ArgName; |
| 506 | } else { |
| 507 | (*I)->getType().getAsStringInternal(FieldName); |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 508 | (*I)->getType().getAsStringInternal(ArgName); |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 509 | Constructor += ", " + ArgName; |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 510 | } |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 511 | S += FieldName + ";\n"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 512 | } |
| 513 | // Output all "by ref" declarations. |
| 514 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 515 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 516 | S += " "; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 517 | std::string FieldName = (*I)->getName(); |
| 518 | std::string ArgName = "_" + FieldName; |
| 519 | // Handle nested closure invocation. For example: |
| 520 | // |
| 521 | // void (^myImportedBlock)(void); |
| 522 | // myImportedBlock = ^(void) { setGlobalInt(x + y); }; |
| 523 | // |
| 524 | // void (^anotherBlock)(void); |
| 525 | // anotherBlock = ^(void) { |
| 526 | // myImportedBlock(); // import and invoke the closure |
| 527 | // }; |
| 528 | // |
| 529 | if (isBlockPointerType((*I)->getType())) { |
Steve Naroff | 8af6a45 | 2008-10-02 17:12:56 +0000 | [diff] [blame] | 530 | S += "struct __block_impl *"; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 531 | Constructor += ", void *" + ArgName; |
| 532 | } else { |
| 533 | Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName); |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 534 | Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName); |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 535 | Constructor += ", " + ArgName; |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 536 | } |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 537 | S += FieldName + "; // by ref\n"; |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 538 | } |
| 539 | // Finish writing the constructor. |
| 540 | // FIXME: handle NSConcreteGlobalBlock. |
| 541 | Constructor += ", int flags=0) {\n"; |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 542 | Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof("; |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 543 | Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n"; |
| 544 | |
| 545 | // Initialize all "by copy" arguments. |
| 546 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 547 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 548 | std::string Name = (*I)->getName(); |
| 549 | Constructor += " "; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 550 | if (isBlockPointerType((*I)->getType())) |
| 551 | Constructor += Name + " = (struct __block_impl *)_"; |
| 552 | else |
| 553 | Constructor += Name + " = _"; |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 554 | Constructor += Name + ";\n"; |
| 555 | } |
| 556 | // Initialize all "by ref" arguments. |
| 557 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 558 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 559 | std::string Name = (*I)->getName(); |
| 560 | Constructor += " "; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 561 | if (isBlockPointerType((*I)->getType())) |
| 562 | Constructor += Name + " = (struct __block_impl *)_"; |
| 563 | else |
| 564 | Constructor += Name + " = _"; |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 565 | Constructor += Name + ";\n"; |
| 566 | } |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 567 | } else { |
| 568 | // Finish writing the constructor. |
| 569 | // FIXME: handle NSConcreteGlobalBlock. |
| 570 | Constructor += ", int flags=0) {\n"; |
| 571 | Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof("; |
| 572 | Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 573 | } |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 574 | Constructor += " "; |
| 575 | Constructor += "}\n"; |
| 576 | S += Constructor; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 577 | S += "};\n"; |
| 578 | return S; |
| 579 | } |
| 580 | |
| 581 | void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart, |
| 582 | const char *FunName) { |
| 583 | // Insert closures that were part of the function. |
| 584 | for (unsigned i = 0; i < Blocks.size(); i++) { |
| 585 | |
Steve Naroff | 48a8c61 | 2008-10-03 12:09:49 +0000 | [diff] [blame] | 586 | std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 587 | |
| 588 | std::string CI = SynthesizeBlockImpl(Blocks[i], Tag); |
| 589 | |
| 590 | InsertText(FunLocStart, CI.c_str(), CI.size()); |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 591 | |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 592 | std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag); |
| 593 | |
| 594 | InsertText(FunLocStart, CF.c_str(), CF.size()); |
| 595 | |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 596 | if (ImportedBlockDecls.size()) { |
| 597 | std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag); |
| 598 | InsertText(FunLocStart, HF.c_str(), HF.size()); |
| 599 | } |
| 600 | |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 601 | BlockDeclRefs.clear(); |
| 602 | BlockByRefDecls.clear(); |
| 603 | BlockByCopyDecls.clear(); |
| 604 | BlockCallExprs.clear(); |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 605 | ImportedBlockDecls.clear(); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 606 | } |
| 607 | Blocks.clear(); |
Steve Naroff | 8e9216d | 2008-10-04 17:10:02 +0000 | [diff] [blame] | 608 | RewrittenBlockExprs.clear(); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 609 | } |
| 610 | |
| 611 | void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) { |
Steve Naroff | 3ad29e2 | 2008-10-03 00:12:09 +0000 | [diff] [blame] | 612 | SourceLocation FunLocStart = FD->getTypeSpecStartLoc(); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 613 | const char *FuncName = FD->getName(); |
| 614 | |
| 615 | SynthesizeBlockLiterals(FunLocStart, FuncName); |
| 616 | } |
| 617 | |
| 618 | void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) { |
| 619 | SourceLocation FunLocStart = MD->getLocStart(); |
| 620 | std::string FuncName = std::string(MD->getSelector().getName()); |
| 621 | // Convert colons to underscores. |
| 622 | std::string::size_type loc = 0; |
| 623 | while ((loc = FuncName.find(":", loc)) != std::string::npos) |
| 624 | FuncName.replace(loc, 1, "_"); |
| 625 | |
| 626 | SynthesizeBlockLiterals(FunLocStart, FuncName.c_str()); |
| 627 | } |
| 628 | |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 629 | |
| 630 | void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) { |
| 631 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 632 | CI != E; ++CI) |
| 633 | if (*CI) |
| 634 | GetBlockDeclRefExprs(*CI); |
| 635 | |
| 636 | // Handle specific things. |
| 637 | if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) |
| 638 | // FIXME: Handle enums. |
| 639 | if (!isa<FunctionDecl>(CDRE->getDecl())) |
| 640 | BlockDeclRefs.push_back(CDRE); |
| 641 | return; |
| 642 | } |
| 643 | |
| 644 | void RewriteBlocks::GetBlockCallExprs(Stmt *S) { |
| 645 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 646 | CI != E; ++CI) |
| 647 | if (*CI) |
| 648 | GetBlockCallExprs(*CI); |
| 649 | |
| 650 | if (CallExpr *CE = dyn_cast<CallExpr>(S)) { |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 651 | if (CE->getCallee()->getType()->isBlockPointerType()) { |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 652 | BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 653 | } |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 654 | } |
| 655 | return; |
| 656 | } |
| 657 | |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 658 | std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) { |
| 659 | // Navigate to relevant type information. |
Steve Naroff | cc2ece2 | 2008-09-24 22:46:45 +0000 | [diff] [blame] | 660 | const char *closureName = 0; |
| 661 | const BlockPointerType *CPT = 0; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 662 | |
| 663 | if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) { |
| 664 | closureName = DRE->getDecl()->getName(); |
| 665 | CPT = DRE->getType()->getAsBlockPointerType(); |
| 666 | } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) { |
| 667 | closureName = CDRE->getDecl()->getName(); |
| 668 | CPT = CDRE->getType()->getAsBlockPointerType(); |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 669 | } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) { |
| 670 | closureName = MExpr->getMemberDecl()->getName(); |
| 671 | CPT = MExpr->getType()->getAsBlockPointerType(); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 672 | } else { |
| 673 | assert(1 && "RewriteBlockClass: Bad type"); |
| 674 | } |
| 675 | assert(CPT && "RewriteBlockClass: Bad type"); |
| 676 | const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType(); |
| 677 | assert(FT && "RewriteBlockClass: Bad type"); |
| 678 | const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT); |
| 679 | // FTP will be null for closures that don't take arguments. |
| 680 | |
| 681 | // Build a closure call - start with a paren expr to enforce precedence. |
| 682 | std::string BlockCall = "("; |
| 683 | |
| 684 | // Synthesize the cast. |
| 685 | BlockCall += "(" + Exp->getType().getAsString() + "(*)"; |
Steve Naroff | 8af6a45 | 2008-10-02 17:12:56 +0000 | [diff] [blame] | 686 | BlockCall += "(struct __block_impl *"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 687 | if (FTP) { |
| 688 | for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(), |
| 689 | E = FTP->arg_type_end(); I && (I != E); ++I) |
| 690 | BlockCall += ", " + (*I).getAsString(); |
| 691 | } |
| 692 | BlockCall += "))"; // close the argument list and paren expression. |
| 693 | |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 694 | // Invoke the closure. We need to cast it since the declaration type is |
| 695 | // bogus (it's a function pointer type) |
| 696 | BlockCall += "((struct __block_impl *)"; |
| 697 | std::string closureExprBufStr; |
| 698 | llvm::raw_string_ostream closureExprBuf(closureExprBufStr); |
| 699 | Exp->getCallee()->printPretty(closureExprBuf); |
| 700 | BlockCall += closureExprBuf.str(); |
| 701 | BlockCall += ")->FuncPtr)"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 702 | |
| 703 | // Add the arguments. |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 704 | BlockCall += "((struct __block_impl *)"; |
Steve Naroff | b65a4f1 | 2008-10-04 17:45:51 +0000 | [diff] [blame] | 705 | BlockCall += closureExprBuf.str(); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 706 | for (CallExpr::arg_iterator I = Exp->arg_begin(), |
| 707 | E = Exp->arg_end(); I != E; ++I) { |
| 708 | std::string syncExprBufS; |
| 709 | llvm::raw_string_ostream Buf(syncExprBufS); |
| 710 | (*I)->printPretty(Buf); |
| 711 | BlockCall += ", " + Buf.str(); |
| 712 | } |
| 713 | return BlockCall; |
| 714 | } |
| 715 | |
| 716 | void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) { |
| 717 | std::string BlockCall = SynthesizeBlockCall(Exp); |
| 718 | |
| 719 | const char *startBuf = SM->getCharacterData(Exp->getLocStart()); |
| 720 | const char *endBuf = SM->getCharacterData(Exp->getLocEnd()); |
| 721 | |
| 722 | ReplaceText(Exp->getLocStart(), endBuf-startBuf, |
| 723 | BlockCall.c_str(), BlockCall.size()); |
| 724 | } |
| 725 | |
| 726 | void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) { |
| 727 | SourceLocation DeclLoc = FD->getLocation(); |
| 728 | unsigned parenCount = 0, nArgs = 0; |
| 729 | |
| 730 | // We have 1 or more arguments that have closure pointers. |
| 731 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 732 | const char *startArgList = strchr(startBuf, '('); |
| 733 | |
| 734 | assert((*startArgList == '(') && "Rewriter fuzzy parser confused"); |
| 735 | |
| 736 | parenCount++; |
| 737 | // advance the location to startArgList. |
| 738 | DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf+1); |
| 739 | assert((DeclLoc.isValid()) && "Invalid DeclLoc"); |
| 740 | |
| 741 | const char *topLevelCommaCursor = 0; |
| 742 | const char *argPtr = startArgList; |
| 743 | bool scannedBlockDecl = false; |
Steve Naroff | 8af6a45 | 2008-10-02 17:12:56 +0000 | [diff] [blame] | 744 | std::string Tag = "struct __block_impl *"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 745 | |
| 746 | while (*argPtr++ && parenCount) { |
| 747 | switch (*argPtr) { |
| 748 | case '^': |
| 749 | scannedBlockDecl = true; |
| 750 | break; |
| 751 | case '(': |
| 752 | parenCount++; |
| 753 | break; |
| 754 | case ')': |
| 755 | parenCount--; |
| 756 | if (parenCount == 0) { |
| 757 | if (scannedBlockDecl) { |
| 758 | // If we are rewriting a definition, don't forget the arg name. |
| 759 | if (FD->getBody()) |
| 760 | Tag += FD->getParamDecl(nArgs)->getName(); |
| 761 | // The last argument is a closure pointer decl, rewrite it! |
| 762 | if (topLevelCommaCursor) |
| 763 | ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-2, Tag.c_str(), Tag.size()); |
| 764 | else |
| 765 | ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size()); |
| 766 | scannedBlockDecl = false; // reset. |
| 767 | } |
| 768 | nArgs++; |
| 769 | } |
| 770 | break; |
| 771 | case ',': |
| 772 | if (parenCount == 1) { |
| 773 | // Make sure the function takes more than one argument. |
| 774 | assert((FD->getNumParams() > 1) && "Rewriter fuzzy parser confused"); |
| 775 | if (scannedBlockDecl) { |
| 776 | // If we are rewriting a definition, don't forget the arg name. |
| 777 | if (FD->getBody()) |
| 778 | Tag += FD->getParamDecl(nArgs)->getName(); |
| 779 | // The current argument is a closure pointer decl, rewrite it! |
| 780 | if (topLevelCommaCursor) |
| 781 | ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-1, Tag.c_str(), Tag.size()); |
| 782 | else |
| 783 | ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size()); |
| 784 | scannedBlockDecl = false; |
| 785 | } |
| 786 | nArgs++; |
| 787 | // advance the location to topLevelCommaCursor. |
| 788 | if (topLevelCommaCursor) |
| 789 | DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-topLevelCommaCursor); |
| 790 | else |
| 791 | DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList+1); |
| 792 | topLevelCommaCursor = argPtr; |
| 793 | assert((DeclLoc.isValid()) && "Invalid DeclLoc"); |
| 794 | } |
| 795 | break; |
| 796 | } |
| 797 | } |
| 798 | return; |
| 799 | } |
| 800 | |
Steve Naroff | eab5f63 | 2008-09-23 19:24:41 +0000 | [diff] [blame] | 801 | bool RewriteBlocks::BlockPointerTypeTakesAnyBlockArguments(QualType QT) { |
| 802 | const BlockPointerType *BPT = QT->getAsBlockPointerType(); |
| 803 | assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type"); |
| 804 | const FunctionTypeProto *FTP = BPT->getPointeeType()->getAsFunctionTypeProto(); |
| 805 | if (FTP) { |
| 806 | for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(), |
| 807 | E = FTP->arg_type_end(); I != E; ++I) |
| 808 | if (isBlockPointerType(*I)) |
| 809 | return true; |
| 810 | } |
| 811 | return false; |
| 812 | } |
| 813 | |
| 814 | void RewriteBlocks::GetExtentOfArgList(const char *Name, |
Steve Naroff | 1f6c3ae | 2008-09-24 17:22:34 +0000 | [diff] [blame] | 815 | const char *&LParen, const char *&RParen) { |
| 816 | const char *argPtr = strchr(Name, '('); |
Steve Naroff | eab5f63 | 2008-09-23 19:24:41 +0000 | [diff] [blame] | 817 | assert((*argPtr == '(') && "Rewriter fuzzy parser confused"); |
| 818 | |
| 819 | LParen = argPtr; // output the start. |
| 820 | argPtr++; // skip past the left paren. |
| 821 | unsigned parenCount = 1; |
| 822 | |
| 823 | while (*argPtr && parenCount) { |
| 824 | switch (*argPtr) { |
| 825 | case '(': parenCount++; break; |
| 826 | case ')': parenCount--; break; |
| 827 | default: break; |
| 828 | } |
| 829 | if (parenCount) argPtr++; |
| 830 | } |
| 831 | assert((*argPtr == ')') && "Rewriter fuzzy parser confused"); |
| 832 | RParen = argPtr; // output the end |
| 833 | } |
| 834 | |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 835 | void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) { |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 836 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { |
| 837 | RewriteBlockPointerFunctionArgs(FD); |
| 838 | return; |
Steve Naroff | ca3bb4f | 2008-09-23 21:15:53 +0000 | [diff] [blame] | 839 | } |
| 840 | // Handle Variables and Typedefs. |
| 841 | SourceLocation DeclLoc = ND->getLocation(); |
| 842 | QualType DeclT; |
| 843 | if (VarDecl *VD = dyn_cast<VarDecl>(ND)) |
| 844 | DeclT = VD->getType(); |
| 845 | else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND)) |
| 846 | DeclT = TDD->getUnderlyingType(); |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 847 | else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND)) |
| 848 | DeclT = FD->getType(); |
Steve Naroff | ca3bb4f | 2008-09-23 21:15:53 +0000 | [diff] [blame] | 849 | else |
| 850 | assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled"); |
Steve Naroff | eab5f63 | 2008-09-23 19:24:41 +0000 | [diff] [blame] | 851 | |
Steve Naroff | ca3bb4f | 2008-09-23 21:15:53 +0000 | [diff] [blame] | 852 | const char *startBuf = SM->getCharacterData(DeclLoc); |
| 853 | const char *endBuf = startBuf; |
| 854 | // scan backward (from the decl location) for the end of the previous decl. |
| 855 | while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart) |
| 856 | startBuf--; |
| 857 | assert((*startBuf == '^') && |
| 858 | "RewriteBlockPointerDecl() scan error: no caret"); |
| 859 | // Replace the '^' with '*', computing a negative offset. |
| 860 | DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf); |
| 861 | ReplaceText(DeclLoc, 1, "*", 1); |
| 862 | |
| 863 | if (BlockPointerTypeTakesAnyBlockArguments(DeclT)) { |
| 864 | // Replace the '^' with '*' for arguments. |
| 865 | DeclLoc = ND->getLocation(); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 866 | startBuf = SM->getCharacterData(DeclLoc); |
Steve Naroff | 1f6c3ae | 2008-09-24 17:22:34 +0000 | [diff] [blame] | 867 | const char *argListBegin, *argListEnd; |
Steve Naroff | ca3bb4f | 2008-09-23 21:15:53 +0000 | [diff] [blame] | 868 | GetExtentOfArgList(startBuf, argListBegin, argListEnd); |
| 869 | while (argListBegin < argListEnd) { |
| 870 | if (*argListBegin == '^') { |
| 871 | SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf); |
| 872 | ReplaceText(CaretLoc, 1, "*", 1); |
| 873 | } |
| 874 | argListBegin++; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 875 | } |
Steve Naroff | eab5f63 | 2008-09-23 19:24:41 +0000 | [diff] [blame] | 876 | } |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 877 | return; |
| 878 | } |
| 879 | |
Steve Naroff | 70f9550 | 2008-10-04 17:06:23 +0000 | [diff] [blame] | 880 | std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) { |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 881 | Blocks.push_back(Exp); |
| 882 | bool haveByRefDecls = false; |
| 883 | |
| 884 | // Add initializers for any closure decl refs. |
| 885 | GetBlockDeclRefExprs(Exp); |
| 886 | if (BlockDeclRefs.size()) { |
| 887 | // Unique all "by copy" declarations. |
| 888 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
| 889 | if (!BlockDeclRefs[i]->isByRef()) |
| 890 | BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl()); |
| 891 | // Unique all "by ref" declarations. |
| 892 | for (unsigned i = 0; i < BlockDeclRefs.size(); i++) |
| 893 | if (BlockDeclRefs[i]->isByRef()) { |
| 894 | haveByRefDecls = true; |
| 895 | BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl()); |
| 896 | } |
| 897 | } |
| 898 | std::string FuncName; |
| 899 | |
| 900 | if (CurFunctionDef) |
| 901 | FuncName = std::string(CurFunctionDef->getName()); |
| 902 | else if (CurMethodDef) { |
| 903 | FuncName = std::string(CurMethodDef->getSelector().getName()); |
| 904 | // Convert colons to underscores. |
| 905 | std::string::size_type loc = 0; |
| 906 | while ((loc = FuncName.find(":", loc)) != std::string::npos) |
| 907 | FuncName.replace(loc, 1, "_"); |
Steve Naroff | 39622b9 | 2008-10-03 15:38:09 +0000 | [diff] [blame] | 908 | } else if (VD) |
| 909 | FuncName = std::string(VD->getName()); |
| 910 | |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 911 | std::string BlockNumber = utostr(Blocks.size()-1); |
| 912 | |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 913 | std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber; |
Steve Naroff | a0b75cf | 2008-10-02 23:30:43 +0000 | [diff] [blame] | 914 | std::string Func = "__" + FuncName + "_block_func_" + BlockNumber; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 915 | |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 916 | std::string FunkTypeStr; |
| 917 | |
| 918 | // Get a pointer to the function type so we can cast appropriately. |
| 919 | Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr); |
| 920 | |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 921 | // Rewrite the closure block with a compound literal. The first cast is |
| 922 | // to prevent warnings from the C compiler. |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 923 | std::string Init = "(" + FunkTypeStr; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 924 | |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 925 | Init += ")&" + Tag; |
| 926 | |
| 927 | // Initialize the block function. |
| 928 | Init += "((void*)" + Func; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 929 | |
| 930 | // Add initializers for any closure decl refs. |
| 931 | if (BlockDeclRefs.size()) { |
| 932 | // Output all "by copy" declarations. |
| 933 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(), |
| 934 | E = BlockByCopyDecls.end(); I != E; ++I) { |
| 935 | Init += ","; |
| 936 | if (isObjCType((*I)->getType())) { |
| 937 | Init += "[["; |
| 938 | Init += (*I)->getName(); |
| 939 | Init += " retain] autorelease]"; |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 940 | } else if (isBlockPointerType((*I)->getType())) { |
| 941 | Init += "(void *)"; |
| 942 | Init += (*I)->getName(); |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 943 | } else { |
| 944 | Init += (*I)->getName(); |
| 945 | } |
| 946 | } |
| 947 | // Output all "by ref" declarations. |
| 948 | for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(), |
| 949 | E = BlockByRefDecls.end(); I != E; ++I) { |
| 950 | Init += ",&"; |
| 951 | Init += (*I)->getName(); |
| 952 | } |
| 953 | } |
Steve Naroff | 83ba14e | 2008-10-03 15:04:50 +0000 | [diff] [blame] | 954 | Init += ")"; |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 955 | BlockDeclRefs.clear(); |
| 956 | BlockByRefDecls.clear(); |
| 957 | BlockByCopyDecls.clear(); |
Steve Naroff | 4e13b76 | 2008-10-03 20:28:15 +0000 | [diff] [blame] | 958 | ImportedBlockDecls.clear(); |
| 959 | |
Steve Naroff | 70f9550 | 2008-10-04 17:06:23 +0000 | [diff] [blame] | 960 | return Init; |
| 961 | } |
| 962 | |
| 963 | //===----------------------------------------------------------------------===// |
| 964 | // Function Body / Expression rewriting |
| 965 | //===----------------------------------------------------------------------===// |
| 966 | |
| 967 | Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) { |
| 968 | // Start by rewriting all children. |
| 969 | for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); |
| 970 | CI != E; ++CI) |
| 971 | if (*CI) { |
| 972 | if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) { |
| 973 | Stmt *newStmt = RewriteFunctionBody(*CI); |
| 974 | if (newStmt) |
| 975 | *CI = newStmt; |
| 976 | |
| 977 | // We've just rewritten the block body in place. |
| 978 | // Now we snarf the rewritten text and stash it away for later use. |
| 979 | std::string S = Rewrite.getRewritenText(CBE->getSourceRange()); |
| 980 | RewrittenBlockExprs[CBE] = S; |
| 981 | std::string Init = SynthesizeBlockInitExpr(CBE); |
| 982 | // Do the rewrite, using S.size() which contains the rewritten size. |
| 983 | ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size()); |
| 984 | } else { |
| 985 | Stmt *newStmt = RewriteFunctionBody(*CI); |
| 986 | if (newStmt) |
| 987 | *CI = newStmt; |
| 988 | } |
| 989 | } |
| 990 | // Handle specific things. |
| 991 | if (CallExpr *CE = dyn_cast<CallExpr>(S)) { |
| 992 | if (CE->getCallee()->getType()->isBlockPointerType()) |
| 993 | RewriteBlockCall(CE); |
| 994 | } |
| 995 | if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) { |
| 996 | ScopedDecl *SD = DS->getDecl(); |
| 997 | if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) { |
| 998 | if (isBlockPointerType(ND->getType())) |
| 999 | RewriteBlockPointerDecl(ND); |
| 1000 | } |
| 1001 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) { |
| 1002 | if (isBlockPointerType(TD->getUnderlyingType())) |
| 1003 | RewriteBlockPointerDecl(TD); |
| 1004 | } |
| 1005 | } |
| 1006 | // Return this stmt unmodified. |
| 1007 | return S; |
| 1008 | } |
| 1009 | |
| 1010 | /// HandleDeclInMainFile - This is called for each top-level decl defined in the |
| 1011 | /// main file of the input. |
| 1012 | void RewriteBlocks::HandleDeclInMainFile(Decl *D) { |
| 1013 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
| 1014 | |
| 1015 | // Since function prototypes don't have ParmDecl's, we check the function |
| 1016 | // prototype. This enables us to rewrite function declarations and |
| 1017 | // definitions using the same code. |
| 1018 | QualType funcType = FD->getType(); |
| 1019 | |
| 1020 | if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) { |
| 1021 | for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(), |
| 1022 | E = fproto->arg_type_end(); I && (I != E); ++I) |
| 1023 | if (isBlockPointerType(*I)) { |
| 1024 | // All the args are checked/rewritten. Don't call twice! |
| 1025 | RewriteBlockPointerDecl(FD); |
| 1026 | break; |
| 1027 | } |
| 1028 | } |
| 1029 | if (Stmt *Body = FD->getBody()) { |
| 1030 | CurFunctionDef = FD; |
| 1031 | FD->setBody(RewriteFunctionBody(Body)); |
| 1032 | // This synthesizes and inserts the block "impl" struct, invoke function, |
| 1033 | // and any copy/dispose helper functions. |
| 1034 | InsertBlockLiteralsWithinFunction(FD); |
| 1035 | CurFunctionDef = 0; |
| 1036 | } |
| 1037 | return; |
| 1038 | } |
| 1039 | if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { |
| 1040 | RewriteMethodDecl(MD); |
| 1041 | if (Stmt *Body = MD->getBody()) { |
| 1042 | CurMethodDef = MD; |
| 1043 | RewriteFunctionBody(Body); |
| 1044 | InsertBlockLiteralsWithinMethod(MD); |
| 1045 | CurMethodDef = 0; |
| 1046 | } |
| 1047 | } |
| 1048 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { |
| 1049 | if (isBlockPointerType(VD->getType())) { |
| 1050 | RewriteBlockPointerDecl(VD); |
| 1051 | if (VD->getInit()) { |
| 1052 | if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) { |
| 1053 | RewriteFunctionBody(VD->getInit()); |
| 1054 | |
| 1055 | // We've just rewritten the block body in place. |
| 1056 | // Now we snarf the rewritten text and stash it away for later use. |
| 1057 | std::string S = Rewrite.getRewritenText(CBE->getSourceRange()); |
| 1058 | RewrittenBlockExprs[CBE] = S; |
| 1059 | std::string Init = SynthesizeBlockInitExpr(CBE, VD); |
| 1060 | // Do the rewrite, using S.size() which contains the rewritten size. |
| 1061 | ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size()); |
| 1062 | SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName()); |
| 1063 | } |
| 1064 | } |
| 1065 | } |
| 1066 | return; |
| 1067 | } |
| 1068 | if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) { |
| 1069 | if (isBlockPointerType(TD->getUnderlyingType())) |
| 1070 | RewriteBlockPointerDecl(TD); |
| 1071 | return; |
| 1072 | } |
| 1073 | if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) { |
| 1074 | if (RD->isDefinition()) { |
| 1075 | for (RecordDecl::field_const_iterator i = RD->field_begin(), |
| 1076 | e = RD->field_end(); i != e; ++i) { |
| 1077 | FieldDecl *FD = *i; |
| 1078 | if (isBlockPointerType(FD->getType())) |
| 1079 | RewriteBlockPointerDecl(FD); |
| 1080 | } |
| 1081 | } |
| 1082 | return; |
| 1083 | } |
Steve Naroff | 1c9f81b | 2008-09-17 00:13:27 +0000 | [diff] [blame] | 1084 | } |