blob: 89b1466846b8d8aa5fde7668a87bcf4bee8f5415 [file] [log] [blame]
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001//===--- 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
27using namespace clang;
28using llvm::utostr;
29
30namespace {
31
32class 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;
52
53 // The function/method we are rewriting.
54 FunctionDecl *CurFunctionDef;
55 ObjCMethodDecl *CurMethodDef;
56
57 bool IsHeader;
Steve Naroff13188952008-09-18 14:10:13 +000058 std::string InFileName;
59 std::string OutFileName;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000060
61 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000062public:
Steve Naroff13188952008-09-18 14:10:13 +000063 RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D,
64 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000065 ~RewriteBlocks() {
66 // Get the buffer corresponding to MainFileID.
67 // If we haven't changed it, then we are done.
68 if (const RewriteBuffer *RewriteBuf =
69 Rewrite.getRewriteBufferFor(MainFileID)) {
70 std::string S(RewriteBuf->begin(), RewriteBuf->end());
71 printf("%s\n", S.c_str());
72 } else {
73 printf("No changes\n");
74 }
75 }
76
77 void Initialize(ASTContext &context);
78
79 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen);
80 void ReplaceText(SourceLocation Start, unsigned OrigLength,
81 const char *NewStr, unsigned NewLength);
82
83 // Top Level Driver code.
84 virtual void HandleTopLevelDecl(Decl *D);
85 void HandleDeclInMainFile(Decl *D);
86
87 // Top level
88 Stmt *RewriteFunctionBody(Stmt *S);
89 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
90 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
91
92 // Block specific rewrite rules.
Steve Naroff9c3c9022008-09-17 18:37:59 +000093 void RewriteBlockExpr(BlockExpr *Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000094
95 void RewriteBlockCall(CallExpr *Exp);
96 void RewriteBlockPointerDecl(NamedDecl *VD);
97 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
98
99 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
100 const char *funcName, std::string Tag);
101 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag);
102 std::string SynthesizeBlockCall(CallExpr *Exp);
103 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
104 const char *FunName);
105
106 void GetBlockDeclRefExprs(Stmt *S);
107 void GetBlockCallExprs(Stmt *S);
108
109 // We avoid calling Type::isBlockPointerType(), since it operates on the
110 // canonical type. We only care if the top-level type is a closure pointer.
111 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
112
113 // FIXME: This predicate seems like it would be useful to add to ASTContext.
114 bool isObjCType(QualType T) {
115 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
116 return false;
117
118 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
119
120 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
121 OCT == Context->getCanonicalType(Context->getObjCClassType()))
122 return true;
123
124 if (const PointerType *PT = OCT->getAsPointerType()) {
125 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
126 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
127 return true;
128 }
129 return false;
130 }
131 // ObjC rewrite methods.
132 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
133 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
134 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
135 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffeab5f632008-09-23 19:24:41 +0000136
137 bool BlockPointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000138 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000139};
140
141}
142
143static bool IsHeaderFile(const std::string &Filename) {
144 std::string::size_type DotPos = Filename.rfind('.');
145
146 if (DotPos == std::string::npos) {
147 // no file extension
148 return false;
149 }
150
151 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
152 // C header: .h
153 // C++ header: .hh or .H;
154 return Ext == "h" || Ext == "hh" || Ext == "H";
155}
156
Steve Naroff13188952008-09-18 14:10:13 +0000157RewriteBlocks::RewriteBlocks(std::string inFile, std::string outFile,
158 Diagnostic &D, const LangOptions &LOpts) :
159 Diags(D), LangOpts(LOpts) {
160 IsHeader = IsHeaderFile(inFile);
161 InFileName = inFile;
162 OutFileName = outFile;
163 CurFunctionDef = 0;
164 CurMethodDef = 0;
165 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
166 "rewriting failed");
167 NoNestedBlockCalls = Diags.getCustomDiagID(Diagnostic::Warning,
168 "Rewrite support for closure calls nested within closure blocks is incomplete");
169}
170
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000171ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
Steve Naroff13188952008-09-18 14:10:13 +0000172 const std::string& OutFile,
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000173 Diagnostic &Diags,
174 const LangOptions &LangOpts) {
Steve Naroff13188952008-09-18 14:10:13 +0000175 return new RewriteBlocks(InFile, OutFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000176}
177
178void RewriteBlocks::Initialize(ASTContext &context) {
179 Context = &context;
180 SM = &Context->getSourceManager();
181
182 // Get the ID and start/end of the main file.
183 MainFileID = SM->getMainFileID();
184 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
185 MainFileStart = MainBuf->getBufferStart();
186 MainFileEnd = MainBuf->getBufferEnd();
187
188 Rewrite.setSourceMgr(Context->getSourceManager());
189
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000190 if (IsHeader)
191 Preamble = "#pragma once\n";
192 Preamble += "#ifndef BLOCK_IMPL\n";
193 Preamble += "#define BLOCK_IMPL\n";
194 Preamble += "struct __block_impl {\n";
195 Preamble += " void *isa;\n";
196 Preamble += " int Flags;\n";
197 Preamble += " int Size;\n";
198 Preamble += " void *FuncPtr;\n";
199 Preamble += "};\n";
200 Preamble += "enum {\n";
201 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
202 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
203 Preamble += "};\n";
204 if (LangOpts.Microsoft)
205 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
206 else
207 Preamble += "#define __OBJC_RW_EXTERN extern\n";
208 Preamble += "// Runtime copy/destroy helper functions\n";
209 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
210 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
211 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
212 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
213 Preamble += "__OBJC_RW_EXTERN void _NSConcreteGlobalBlock;\n";
214 Preamble += "__OBJC_RW_EXTERN void _NSConcreteStackBlock;\n";
215 Preamble += "#endif\n";
216
217 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
218 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000219}
220
221void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData,
222 unsigned StrLen)
223{
224 if (!Rewrite.InsertText(Loc, StrData, StrLen))
225 return;
226 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
227}
228
229void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength,
230 const char *NewStr, unsigned NewLength) {
231 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength))
232 return;
233 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
234}
235
236void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) {
237 bool haveBlockPtrs = false;
238 for (ObjCMethodDecl::param_iterator I = Method->param_begin(),
239 E = Method->param_end(); I != E; ++I)
240 if (isBlockPointerType((*I)->getType()))
241 haveBlockPtrs = true;
242
243 if (!haveBlockPtrs)
244 return;
245
246 // Do a fuzzy rewrite.
247 // We have 1 or more arguments that have closure pointers.
248 SourceLocation Loc = Method->getLocStart();
249 SourceLocation LocEnd = Method->getLocEnd();
250 const char *startBuf = SM->getCharacterData(Loc);
251 const char *endBuf = SM->getCharacterData(LocEnd);
252
253 const char *methodPtr = startBuf;
Steve Naroff8af6a452008-10-02 17:12:56 +0000254 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000255
256 while (*methodPtr++ && (methodPtr != endBuf)) {
257 switch (*methodPtr) {
258 case ':':
259 methodPtr++;
260 if (*methodPtr == '(') {
261 const char *scanType = ++methodPtr;
262 bool foundBlockPointer = false;
263 unsigned parenCount = 1;
264
265 while (parenCount) {
266 switch (*scanType) {
267 case '(':
268 parenCount++;
269 break;
270 case ')':
271 parenCount--;
272 break;
273 case '^':
274 foundBlockPointer = true;
275 break;
276 }
277 scanType++;
278 }
279 if (foundBlockPointer) {
280 // advance the location to startArgList.
281 Loc = Loc.getFileLocWithOffset(methodPtr-startBuf);
282 assert((Loc.isValid()) && "Invalid Loc");
283 ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size());
284
285 // Advance startBuf. Since the underlying buffer has changed,
286 // it's very important to advance startBuf (so we can correctly
287 // compute a relative Loc the next time around).
288 startBuf = methodPtr;
289 }
290 // Advance the method ptr to the end of the type.
291 methodPtr = scanType;
292 }
293 break;
294 }
295 }
296 return;
297}
298
299void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
300 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
301 E = ClassDecl->instmeth_end(); I != E; ++I)
302 RewriteMethodDecl(*I);
303 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
304 E = ClassDecl->classmeth_end(); I != E; ++I)
305 RewriteMethodDecl(*I);
306}
307
308void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
309 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
310 E = CatDecl->instmeth_end(); I != E; ++I)
311 RewriteMethodDecl(*I);
312 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
313 E = CatDecl->classmeth_end(); I != E; ++I)
314 RewriteMethodDecl(*I);
315}
316
317void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
318 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
319 E = PDecl->instmeth_end(); I != E; ++I)
320 RewriteMethodDecl(*I);
321 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
322 E = PDecl->classmeth_end(); I != E; ++I)
323 RewriteMethodDecl(*I);
324}
325
326//===----------------------------------------------------------------------===//
327// Top Level Driver Code
328//===----------------------------------------------------------------------===//
329
330void RewriteBlocks::HandleTopLevelDecl(Decl *D) {
331 // Two cases: either the decl could be in the main file, or it could be in a
332 // #included file. If the former, rewrite it now. If the later, check to see
333 // if we rewrote the #include/#import.
334 SourceLocation Loc = D->getLocation();
335 Loc = SM->getLogicalLoc(Loc);
336
337 // If this is for a builtin, ignore it.
338 if (Loc.isInvalid()) return;
339
340 if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D))
341 RewriteInterfaceDecl(MD);
342 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D))
343 RewriteCategoryDecl(CD);
344 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
345 RewriteProtocolDecl(PD);
346
347 // If we have a decl in the main file, see if we should rewrite it.
348 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
349 HandleDeclInMainFile(D);
350 return;
351}
352
353std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i,
354 const char *funcName,
355 std::string Tag) {
356 const FunctionType *AFT = CE->getFunctionType();
357 QualType RT = AFT->getResultType();
358 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000359 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000360
361 if (isa<FunctionTypeNoProto>(AFT)) {
362 S += "()";
363 } else if (CE->arg_empty()) {
364 S += "(" + Tag + " *__cself)";
365 } else {
366 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
367 assert(FT && "SynthesizeBlockFunc: No function proto");
368 S += '(';
369 // first add the implicit argument.
370 S += Tag + " *__cself, ";
371 std::string ParamStr;
Steve Naroff9c3c9022008-09-17 18:37:59 +0000372 for (BlockExpr::arg_iterator AI = CE->arg_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000373 E = CE->arg_end(); AI != E; ++AI) {
374 if (AI != CE->arg_begin()) S += ", ";
375 ParamStr = (*AI)->getName();
376 (*AI)->getType().getAsStringInternal(ParamStr);
377 S += ParamStr;
378 }
379 if (FT->isVariadic()) {
380 if (!CE->arg_empty()) S += ", ";
381 S += "...";
382 }
383 S += ')';
384 }
385 S += " {\n";
386
387 bool haveByRefDecls = false;
388
389 // Create local declarations to avoid rewriting all closure decl ref exprs.
390 // First, emit a declaration for all "by ref" decls.
391 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
392 E = BlockByRefDecls.end(); I != E; ++I) {
393 // Note: It is not possible to have "by ref" closure pointer decls.
394 haveByRefDecls = true;
395 S += " ";
396 std::string Name = (*I)->getName();
397 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
398 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
399 }
400 // Next, emit a declaration for all "by copy" declarations.
401 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
402 E = BlockByCopyDecls.end(); I != E; ++I) {
403 S += " ";
404 std::string Name = (*I)->getName();
405 // Handle nested closure invocation. For example:
406 //
407 // void (^myImportedClosure)(void);
408 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
409 //
410 // void (^anotherClosure)(void);
411 // anotherClosure = ^(void) {
412 // myImportedClosure(); // import and invoke the closure
413 // };
414 //
415 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000416 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000417 else
418 (*I)->getType().getAsStringInternal(Name);
419 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
420 }
Steve Naroff9c3c9022008-09-17 18:37:59 +0000421 if (BlockExpr *CBE = dyn_cast<BlockExpr>(CE)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000422 std::string BodyBuf;
423
424 SourceLocation BodyLocStart = CBE->getBody()->getLocStart();
425 SourceLocation BodyLocEnd = CBE->getBody()->getLocEnd();
426 const char *BodyStartBuf = SM->getCharacterData(BodyLocStart);
427 const char *BodyEndBuf = SM->getCharacterData(BodyLocEnd);
428
429 BodyBuf.append(BodyStartBuf, BodyEndBuf-BodyStartBuf+1);
430
431 if (BlockDeclRefs.size()) {
432 unsigned int nCharsAdded = 0;
433 for (unsigned i = 0; i < BlockDeclRefs.size(); i++) {
434 if (BlockDeclRefs[i]->isByRef()) {
435 // Add a level of indirection! The code below assumes
436 // the closure decl refs/locations are in strictly ascending
437 // order. The traversal performed by GetBlockDeclRefExprs()
438 // currently does this. FIXME: Wrap the *x with parens,
439 // just in case x is a more complex expression, like x->member,
440 // which needs to be rewritten to (*x)->member.
441 SourceLocation StarLoc = BlockDeclRefs[i]->getLocStart();
442 const char *StarBuf = SM->getCharacterData(StarLoc);
443 BodyBuf.insert(StarBuf-BodyStartBuf+nCharsAdded, 1, '*');
444 // Get a fresh buffer, the insert might have caused it to grow.
445 BodyStartBuf = SM->getCharacterData(BodyLocStart);
446 nCharsAdded++;
447 } else if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
448 Diags.Report(NoNestedBlockCalls);
449
450 GetBlockCallExprs(CE);
451
452 // Rewrite the closure in place.
453 // The character based equivalent of RewriteBlockCall().
454 // Need to get the CallExpr associated with this BlockDeclRef.
455 std::string BlockCall = SynthesizeBlockCall(BlockCallExprs[BlockDeclRefs[i]]);
456
457 SourceLocation CallLocStart = BlockCallExprs[BlockDeclRefs[i]]->getLocStart();
458 SourceLocation CallLocEnd = BlockCallExprs[BlockDeclRefs[i]]->getLocEnd();
459 const char *CallStart = SM->getCharacterData(CallLocStart);
460 const char *CallEnd = SM->getCharacterData(CallLocEnd);
461 unsigned CallBytes = CallEnd-CallStart;
462 BodyBuf.replace(CallStart-BodyStartBuf, CallBytes, BlockCall.c_str());
463 nCharsAdded += CallBytes;
464 }
465 }
466 }
467 if (haveByRefDecls) {
468 // Remove |...|.
Steve Naroffeab5f632008-09-23 19:24:41 +0000469 //const char *firstBarPtr = strchr(BodyStartBuf, '|');
470 //const char *secondBarPtr = strchr(firstBarPtr+1, '|');
471 //BodyBuf.replace(firstBarPtr-BodyStartBuf, secondBarPtr-firstBarPtr+1, "");
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000472 }
473 S += " ";
474 S += BodyBuf;
475 }
476 S += "\n}\n";
477 return S;
478}
479
480std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE,
481 std::string Tag) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000482 std::string S = Tag + " {\n struct __block_impl impl;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000483
484 GetBlockDeclRefExprs(CE);
485 if (BlockDeclRefs.size()) {
486 // Unique all "by copy" declarations.
487 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
488 if (!BlockDeclRefs[i]->isByRef())
489 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
490 // Unique all "by ref" declarations.
491 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
492 if (BlockDeclRefs[i]->isByRef())
493 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
494
495 // Output all "by copy" declarations.
496 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
497 E = BlockByCopyDecls.end(); I != E; ++I) {
498 S += " ";
499 std::string Name = (*I)->getName();
500 // Handle nested closure invocation. For example:
501 //
502 // void (^myImportedBlock)(void);
503 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
504 //
505 // void (^anotherBlock)(void);
506 // anotherBlock = ^(void) {
507 // myImportedBlock(); // import and invoke the closure
508 // };
509 //
510 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000511 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000512 else
513 (*I)->getType().getAsStringInternal(Name);
514 S += Name + ";\n";
515 }
516 // Output all "by ref" declarations.
517 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
518 E = BlockByRefDecls.end(); I != E; ++I) {
519 S += " ";
520 std::string Name = (*I)->getName();
521 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000522 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000523 else
524 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
525 S += Name + "; // by ref\n";
526 }
527 }
528 S += "};\n";
529 return S;
530}
531
532void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
533 const char *FunName) {
534 // Insert closures that were part of the function.
535 for (unsigned i = 0; i < Blocks.size(); i++) {
536
537 std::string Tag = "struct __" + std::string(FunName) +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000538 "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000539
540 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag);
541
542 InsertText(FunLocStart, CI.c_str(), CI.size());
543
544 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
545
546 InsertText(FunLocStart, CF.c_str(), CF.size());
547
548 BlockDeclRefs.clear();
549 BlockByRefDecls.clear();
550 BlockByCopyDecls.clear();
551 BlockCallExprs.clear();
552 }
553 Blocks.clear();
554}
555
556void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
557 SourceLocation FunLocStart = FD->getLocation();
558 const char *FuncName = FD->getName();
559
560 SynthesizeBlockLiterals(FunLocStart, FuncName);
561}
562
563void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
564 SourceLocation FunLocStart = MD->getLocStart();
565 std::string FuncName = std::string(MD->getSelector().getName());
566 // Convert colons to underscores.
567 std::string::size_type loc = 0;
568 while ((loc = FuncName.find(":", loc)) != std::string::npos)
569 FuncName.replace(loc, 1, "_");
570
571 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
572}
573
574/// HandleDeclInMainFile - This is called for each top-level decl defined in the
575/// main file of the input.
576void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
577 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
578
579 // Since function prototypes don't have ParmDecl's, we check the function
580 // prototype. This enables us to rewrite function declarations and
581 // definitions using the same code.
582 QualType funcType = FD->getType();
583
584 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
585 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
586 E = fproto->arg_type_end(); I && (I != E); ++I)
587 if (isBlockPointerType(*I)) {
588 // All the args are checked/rewritten. Don't call twice!
589 RewriteBlockPointerDecl(FD);
590 break;
591 }
592 }
593 if (Stmt *Body = FD->getBody()) {
594 CurFunctionDef = FD;
595 FD->setBody(RewriteFunctionBody(Body));
596 InsertBlockLiteralsWithinFunction(FD);
597 CurFunctionDef = 0;
598 }
599 return;
600 }
601 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
602 RewriteMethodDecl(MD);
603 if (Stmt *Body = MD->getBody()) {
604 CurMethodDef = MD;
605 RewriteFunctionBody(Body);
606 InsertBlockLiteralsWithinMethod(MD);
607 CurMethodDef = 0;
608 }
609 }
610 if (ValueDecl *ND = dyn_cast<ValueDecl>(D)) {
611 if (isBlockPointerType(ND->getType()))
612 RewriteBlockPointerDecl(ND);
613 return;
614 }
615 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
616 if (isBlockPointerType(TD->getUnderlyingType()))
617 RewriteBlockPointerDecl(TD);
618 return;
619 }
620}
621
622void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
623 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
624 CI != E; ++CI)
625 if (*CI)
626 GetBlockDeclRefExprs(*CI);
627
628 // Handle specific things.
629 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
630 // FIXME: Handle enums.
631 if (!isa<FunctionDecl>(CDRE->getDecl()))
632 BlockDeclRefs.push_back(CDRE);
633 return;
634}
635
636void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
637 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
638 CI != E; ++CI)
639 if (*CI)
640 GetBlockCallExprs(*CI);
641
642 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
643 if (CE->getCallee()->getType()->isBlockPointerType())
644 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
645 }
646 return;
647}
648
649//===----------------------------------------------------------------------===//
650// Function Body / Expression rewriting
651//===----------------------------------------------------------------------===//
652
653Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
654 // Start by rewriting all children.
655 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
656 CI != E; ++CI)
657 if (*CI) {
Steve Naroff9c3c9022008-09-17 18:37:59 +0000658 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000659 // We intentionally avoid rewritting the contents of a closure block
660 // expr. InsertBlockLiteralsWithinFunction() will rewrite the body.
Steve Naroff9c3c9022008-09-17 18:37:59 +0000661 RewriteBlockExpr(CBE);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000662 } else {
663 Stmt *newStmt = RewriteFunctionBody(*CI);
664 if (newStmt)
665 *CI = newStmt;
666 }
667 }
668 // Handle specific things.
669 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
670 if (CE->getCallee()->getType()->isBlockPointerType())
671 RewriteBlockCall(CE);
672 }
673 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
674 ScopedDecl *SD = DS->getDecl();
675 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
676 if (isBlockPointerType(ND->getType()))
677 RewriteBlockPointerDecl(ND);
678 }
679 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
680 if (isBlockPointerType(TD->getUnderlyingType()))
681 RewriteBlockPointerDecl(TD);
682 }
683 }
684 // Return this stmt unmodified.
685 return S;
686}
687
688std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
689 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000690 const char *closureName = 0;
691 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000692
693 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
694 closureName = DRE->getDecl()->getName();
695 CPT = DRE->getType()->getAsBlockPointerType();
696 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
697 closureName = CDRE->getDecl()->getName();
698 CPT = CDRE->getType()->getAsBlockPointerType();
699 } else {
700 assert(1 && "RewriteBlockClass: Bad type");
701 }
702 assert(CPT && "RewriteBlockClass: Bad type");
703 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
704 assert(FT && "RewriteBlockClass: Bad type");
705 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
706 // FTP will be null for closures that don't take arguments.
707
708 // Build a closure call - start with a paren expr to enforce precedence.
709 std::string BlockCall = "(";
710
711 // Synthesize the cast.
712 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000713 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000714 if (FTP) {
715 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
716 E = FTP->arg_type_end(); I && (I != E); ++I)
717 BlockCall += ", " + (*I).getAsString();
718 }
719 BlockCall += "))"; // close the argument list and paren expression.
720
721 // Invoke the closure.
722 BlockCall += closureName;
723 BlockCall += "->Invoke)";
724
725 // Add the arguments.
726 BlockCall += "(";
727 BlockCall += closureName;
728 for (CallExpr::arg_iterator I = Exp->arg_begin(),
729 E = Exp->arg_end(); I != E; ++I) {
730 std::string syncExprBufS;
731 llvm::raw_string_ostream Buf(syncExprBufS);
732 (*I)->printPretty(Buf);
733 BlockCall += ", " + Buf.str();
734 }
735 return BlockCall;
736}
737
738void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
739 std::string BlockCall = SynthesizeBlockCall(Exp);
740
741 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
742 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
743
744 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
745 BlockCall.c_str(), BlockCall.size());
746}
747
748void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
749 SourceLocation DeclLoc = FD->getLocation();
750 unsigned parenCount = 0, nArgs = 0;
751
752 // We have 1 or more arguments that have closure pointers.
753 const char *startBuf = SM->getCharacterData(DeclLoc);
754 const char *startArgList = strchr(startBuf, '(');
755
756 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
757
758 parenCount++;
759 // advance the location to startArgList.
760 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf+1);
761 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
762
763 const char *topLevelCommaCursor = 0;
764 const char *argPtr = startArgList;
765 bool scannedBlockDecl = false;
Steve Naroff8af6a452008-10-02 17:12:56 +0000766 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000767
768 while (*argPtr++ && parenCount) {
769 switch (*argPtr) {
770 case '^':
771 scannedBlockDecl = true;
772 break;
773 case '(':
774 parenCount++;
775 break;
776 case ')':
777 parenCount--;
778 if (parenCount == 0) {
779 if (scannedBlockDecl) {
780 // If we are rewriting a definition, don't forget the arg name.
781 if (FD->getBody())
782 Tag += FD->getParamDecl(nArgs)->getName();
783 // The last argument is a closure pointer decl, rewrite it!
784 if (topLevelCommaCursor)
785 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-2, Tag.c_str(), Tag.size());
786 else
787 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
788 scannedBlockDecl = false; // reset.
789 }
790 nArgs++;
791 }
792 break;
793 case ',':
794 if (parenCount == 1) {
795 // Make sure the function takes more than one argument.
796 assert((FD->getNumParams() > 1) && "Rewriter fuzzy parser confused");
797 if (scannedBlockDecl) {
798 // If we are rewriting a definition, don't forget the arg name.
799 if (FD->getBody())
800 Tag += FD->getParamDecl(nArgs)->getName();
801 // The current argument is a closure pointer decl, rewrite it!
802 if (topLevelCommaCursor)
803 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-1, Tag.c_str(), Tag.size());
804 else
805 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
806 scannedBlockDecl = false;
807 }
808 nArgs++;
809 // advance the location to topLevelCommaCursor.
810 if (topLevelCommaCursor)
811 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-topLevelCommaCursor);
812 else
813 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList+1);
814 topLevelCommaCursor = argPtr;
815 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
816 }
817 break;
818 }
819 }
820 return;
821}
822
Steve Naroffeab5f632008-09-23 19:24:41 +0000823bool RewriteBlocks::BlockPointerTypeTakesAnyBlockArguments(QualType QT) {
824 const BlockPointerType *BPT = QT->getAsBlockPointerType();
825 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
826 const FunctionTypeProto *FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
827 if (FTP) {
828 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
829 E = FTP->arg_type_end(); I != E; ++I)
830 if (isBlockPointerType(*I))
831 return true;
832 }
833 return false;
834}
835
836void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000837 const char *&LParen, const char *&RParen) {
838 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000839 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
840
841 LParen = argPtr; // output the start.
842 argPtr++; // skip past the left paren.
843 unsigned parenCount = 1;
844
845 while (*argPtr && parenCount) {
846 switch (*argPtr) {
847 case '(': parenCount++; break;
848 case ')': parenCount--; break;
849 default: break;
850 }
851 if (parenCount) argPtr++;
852 }
853 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
854 RParen = argPtr; // output the end
855}
856
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000857void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000858 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
859 RewriteBlockPointerFunctionArgs(FD);
860 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000861 }
862 // Handle Variables and Typedefs.
863 SourceLocation DeclLoc = ND->getLocation();
864 QualType DeclT;
865 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
866 DeclT = VD->getType();
867 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
868 DeclT = TDD->getUnderlyingType();
869 else
870 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000871
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000872 const char *startBuf = SM->getCharacterData(DeclLoc);
873 const char *endBuf = startBuf;
874 // scan backward (from the decl location) for the end of the previous decl.
875 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
876 startBuf--;
877 assert((*startBuf == '^') &&
878 "RewriteBlockPointerDecl() scan error: no caret");
879 // Replace the '^' with '*', computing a negative offset.
880 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
881 ReplaceText(DeclLoc, 1, "*", 1);
882
883 if (BlockPointerTypeTakesAnyBlockArguments(DeclT)) {
884 // Replace the '^' with '*' for arguments.
885 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000886 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000887 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000888 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
889 while (argListBegin < argListEnd) {
890 if (*argListBegin == '^') {
891 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
892 ReplaceText(CaretLoc, 1, "*", 1);
893 }
894 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000895 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000896 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000897 return;
898}
899
Steve Naroff9c3c9022008-09-17 18:37:59 +0000900void RewriteBlocks::RewriteBlockExpr(BlockExpr *Exp) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000901 Blocks.push_back(Exp);
902 bool haveByRefDecls = false;
903
904 // Add initializers for any closure decl refs.
905 GetBlockDeclRefExprs(Exp);
906 if (BlockDeclRefs.size()) {
907 // Unique all "by copy" declarations.
908 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
909 if (!BlockDeclRefs[i]->isByRef())
910 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
911 // Unique all "by ref" declarations.
912 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
913 if (BlockDeclRefs[i]->isByRef()) {
914 haveByRefDecls = true;
915 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
916 }
917 }
918 std::string FuncName;
919
920 if (CurFunctionDef)
921 FuncName = std::string(CurFunctionDef->getName());
922 else if (CurMethodDef) {
923 FuncName = std::string(CurMethodDef->getSelector().getName());
924 // Convert colons to underscores.
925 std::string::size_type loc = 0;
926 while ((loc = FuncName.find(":", loc)) != std::string::npos)
927 FuncName.replace(loc, 1, "_");
928 }
929 std::string BlockNumber = utostr(Blocks.size()-1);
930
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000931 std::string Tag = "struct __" + FuncName + "_block_impl_" + BlockNumber;
932 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000933
934 // Rewrite the closure block with a compound literal. The first cast is
935 // to prevent warnings from the C compiler.
Steve Naroff8af6a452008-10-02 17:12:56 +0000936 std::string Init = "(struct __block_impl *)&(" + Tag + "){{0,";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000937
938 // Initialize the Flags, Size, and Invoke fields.
939 Init += (haveByRefDecls ? "HAS_BYREF," : "0,");
940 Init += "sizeof(" + Tag + ")," + Func + "}";
941
942 // Add initializers for any closure decl refs.
943 if (BlockDeclRefs.size()) {
944 // Output all "by copy" declarations.
945 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
946 E = BlockByCopyDecls.end(); I != E; ++I) {
947 Init += ",";
948 if (isObjCType((*I)->getType())) {
949 Init += "[[";
950 Init += (*I)->getName();
951 Init += " retain] autorelease]";
952 } else {
953 Init += (*I)->getName();
954 }
955 }
956 // Output all "by ref" declarations.
957 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
958 E = BlockByRefDecls.end(); I != E; ++I) {
959 Init += ",&";
960 Init += (*I)->getName();
961 }
962 }
963 Init += "}";
964 BlockDeclRefs.clear();
965 BlockByRefDecls.clear();
966 BlockByCopyDecls.clear();
967
968 // Do the rewrite.
969 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
970 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
971 ReplaceText(Exp->getLocStart(), endBuf-startBuf+1, Init.c_str(), Init.size());
972 return;
973}