blob: 57d3a84560c23a987f2f4a4e2573fd4a4942b1a9 [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;
Steve Naroff4e13b762008-10-03 20:28:15 +000052 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Steve Naroff70f95502008-10-04 17:06:23 +000053
54 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000055
56 // The function/method we are rewriting.
57 FunctionDecl *CurFunctionDef;
58 ObjCMethodDecl *CurMethodDef;
59
60 bool IsHeader;
Steve Naroff13188952008-09-18 14:10:13 +000061 std::string InFileName;
62 std::string OutFileName;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000063
64 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000065public:
Steve Naroff13188952008-09-18 14:10:13 +000066 RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D,
67 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000068 ~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 Naroff70f95502008-10-04 17:06:23 +000096 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000097
98 void RewriteBlockCall(CallExpr *Exp);
99 void RewriteBlockPointerDecl(NamedDecl *VD);
100 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
101
Steve Naroff4e13b762008-10-03 20:28:15 +0000102 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
103 const char *funcName, std::string Tag);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000104 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 Naroffeab5f632008-09-23 19:24:41 +0000141
142 bool BlockPointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000143 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000144};
145
146}
147
148static 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 Naroff13188952008-09-18 14:10:13 +0000162RewriteBlocks::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 Naroff1c9f81b2008-09-17 00:13:27 +0000176ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
Steve Naroff13188952008-09-18 14:10:13 +0000177 const std::string& OutFile,
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000178 Diagnostic &Diags,
179 const LangOptions &LangOpts) {
Steve Naroff13188952008-09-18 14:10:13 +0000180 return new RewriteBlocks(InFile, OutFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000181}
182
183void 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 Naroffa0b75cf2008-10-02 23:30:43 +0000195 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 Naroff48a8c612008-10-03 12:09:49 +0000218 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
219 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000220 Preamble += "#endif\n";
221
222 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
223 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000224}
225
226void 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
234void 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
241void 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 Naroff8af6a452008-10-02 17:12:56 +0000259 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000260
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
304void 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
313void 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
322void 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
335void 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
358std::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 Naroff48a8c612008-10-03 12:09:49 +0000363 std::string StructRef = "struct " + Tag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000364 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000365 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000366
367 if (isa<FunctionTypeNoProto>(AFT)) {
368 S += "()";
369 } else if (CE->arg_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000370 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000371 } else {
372 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
373 assert(FT && "SynthesizeBlockFunc: No function proto");
374 S += '(';
375 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000376 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000377 std::string ParamStr;
Steve Naroff9c3c9022008-09-17 18:37:59 +0000378 for (BlockExpr::arg_iterator AI = CE->arg_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000379 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 Naroff8af6a452008-10-02 17:12:56 +0000422 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000423 else
424 (*I)->getType().getAsStringInternal(Name);
425 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000426 }
Steve Naroff70f95502008-10-04 17:06:23 +0000427 std::string RewrittenStr = RewrittenBlockExprs[CE];
428 const char *cstr = RewrittenStr.c_str();
429 while (*cstr++ != '{') ;
430 S += cstr;
431 S += "\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000432 return S;
433}
434
Steve Naroff4e13b762008-10-03 20:28:15 +0000435std::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 Naroff48a8c612008-10-03 12:09:49 +0000469std::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 Naroff1c9f81b2008-09-17 00:13:27 +0000475
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());
Steve Naroff3b0fd642008-10-04 18:00:11 +0000486
487 // Find any imported blocks...they will need special attention.
488 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
489 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
490 GetBlockCallExprs(CE);
491 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
492 }
493
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000494 // Output all "by copy" declarations.
495 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
496 E = BlockByCopyDecls.end(); I != E; ++I) {
497 S += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000498 std::string FieldName = (*I)->getName();
499 std::string ArgName = "_" + FieldName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000500 // 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 //
Steve Naroff4e13b762008-10-03 20:28:15 +0000510 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000511 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000512 Constructor += ", void *" + ArgName;
513 } else {
514 (*I)->getType().getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000515 (*I)->getType().getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000516 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000517 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000518 S += FieldName + ";\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000519 }
520 // Output all "by ref" declarations.
521 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
522 E = BlockByRefDecls.end(); I != E; ++I) {
523 S += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000524 std::string FieldName = (*I)->getName();
525 std::string ArgName = "_" + FieldName;
526 // Handle nested closure invocation. For example:
527 //
528 // void (^myImportedBlock)(void);
529 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
530 //
531 // void (^anotherBlock)(void);
532 // anotherBlock = ^(void) {
533 // myImportedBlock(); // import and invoke the closure
534 // };
535 //
536 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000537 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000538 Constructor += ", void *" + ArgName;
539 } else {
540 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000541 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000542 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000543 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000544 S += FieldName + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000545 }
546 // Finish writing the constructor.
547 // FIXME: handle NSConcreteGlobalBlock.
548 Constructor += ", int flags=0) {\n";
Steve Naroff83ba14e2008-10-03 15:04:50 +0000549 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
Steve Naroff48a8c612008-10-03 12:09:49 +0000550 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
551
552 // Initialize all "by copy" arguments.
553 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
554 E = BlockByCopyDecls.end(); I != E; ++I) {
555 std::string Name = (*I)->getName();
556 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000557 if (isBlockPointerType((*I)->getType()))
558 Constructor += Name + " = (struct __block_impl *)_";
559 else
560 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000561 Constructor += Name + ";\n";
562 }
563 // Initialize all "by ref" arguments.
564 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
565 E = BlockByRefDecls.end(); I != E; ++I) {
566 std::string Name = (*I)->getName();
567 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000568 if (isBlockPointerType((*I)->getType()))
569 Constructor += Name + " = (struct __block_impl *)_";
570 else
571 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000572 Constructor += Name + ";\n";
573 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000574 } else {
575 // Finish writing the constructor.
576 // FIXME: handle NSConcreteGlobalBlock.
577 Constructor += ", int flags=0) {\n";
578 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
579 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000580 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000581 Constructor += " ";
582 Constructor += "}\n";
583 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000584 S += "};\n";
585 return S;
586}
587
588void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
589 const char *FunName) {
590 // Insert closures that were part of the function.
591 for (unsigned i = 0; i < Blocks.size(); i++) {
592
Steve Naroff48a8c612008-10-03 12:09:49 +0000593 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000594
595 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag);
596
597 InsertText(FunLocStart, CI.c_str(), CI.size());
Steve Naroff4e13b762008-10-03 20:28:15 +0000598
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000599 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
600
601 InsertText(FunLocStart, CF.c_str(), CF.size());
602
Steve Naroff4e13b762008-10-03 20:28:15 +0000603 if (ImportedBlockDecls.size()) {
604 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
605 InsertText(FunLocStart, HF.c_str(), HF.size());
606 }
607
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000608 BlockDeclRefs.clear();
609 BlockByRefDecls.clear();
610 BlockByCopyDecls.clear();
611 BlockCallExprs.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000612 ImportedBlockDecls.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000613 }
614 Blocks.clear();
Steve Naroff8e9216d2008-10-04 17:10:02 +0000615 RewrittenBlockExprs.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000616}
617
618void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000619 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000620 const char *FuncName = FD->getName();
621
622 SynthesizeBlockLiterals(FunLocStart, FuncName);
623}
624
625void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
626 SourceLocation FunLocStart = MD->getLocStart();
627 std::string FuncName = std::string(MD->getSelector().getName());
628 // Convert colons to underscores.
629 std::string::size_type loc = 0;
630 while ((loc = FuncName.find(":", loc)) != std::string::npos)
631 FuncName.replace(loc, 1, "_");
632
633 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
634}
635
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000636
637void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
638 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
639 CI != E; ++CI)
640 if (*CI)
641 GetBlockDeclRefExprs(*CI);
642
643 // Handle specific things.
644 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
645 // FIXME: Handle enums.
646 if (!isa<FunctionDecl>(CDRE->getDecl()))
647 BlockDeclRefs.push_back(CDRE);
648 return;
649}
650
651void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
652 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
653 CI != E; ++CI)
654 if (*CI)
655 GetBlockCallExprs(*CI);
656
657 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff4e13b762008-10-03 20:28:15 +0000658 if (CE->getCallee()->getType()->isBlockPointerType()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000659 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
Steve Naroff4e13b762008-10-03 20:28:15 +0000660 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000661 }
662 return;
663}
664
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000665std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
666 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000667 const char *closureName = 0;
668 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000669
670 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
671 closureName = DRE->getDecl()->getName();
672 CPT = DRE->getType()->getAsBlockPointerType();
673 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
674 closureName = CDRE->getDecl()->getName();
675 CPT = CDRE->getType()->getAsBlockPointerType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000676 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
677 closureName = MExpr->getMemberDecl()->getName();
678 CPT = MExpr->getType()->getAsBlockPointerType();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000679 } else {
680 assert(1 && "RewriteBlockClass: Bad type");
681 }
682 assert(CPT && "RewriteBlockClass: Bad type");
683 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
684 assert(FT && "RewriteBlockClass: Bad type");
685 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
686 // FTP will be null for closures that don't take arguments.
687
688 // Build a closure call - start with a paren expr to enforce precedence.
689 std::string BlockCall = "(";
690
691 // Synthesize the cast.
692 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000693 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000694 if (FTP) {
695 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
696 E = FTP->arg_type_end(); I && (I != E); ++I)
697 BlockCall += ", " + (*I).getAsString();
698 }
699 BlockCall += "))"; // close the argument list and paren expression.
700
Steve Naroff83ba14e2008-10-03 15:04:50 +0000701 // Invoke the closure. We need to cast it since the declaration type is
702 // bogus (it's a function pointer type)
703 BlockCall += "((struct __block_impl *)";
704 std::string closureExprBufStr;
705 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
706 Exp->getCallee()->printPretty(closureExprBuf);
707 BlockCall += closureExprBuf.str();
708 BlockCall += ")->FuncPtr)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000709
710 // Add the arguments.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000711 BlockCall += "((struct __block_impl *)";
Steve Naroffb65a4f12008-10-04 17:45:51 +0000712 BlockCall += closureExprBuf.str();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000713 for (CallExpr::arg_iterator I = Exp->arg_begin(),
714 E = Exp->arg_end(); I != E; ++I) {
715 std::string syncExprBufS;
716 llvm::raw_string_ostream Buf(syncExprBufS);
717 (*I)->printPretty(Buf);
718 BlockCall += ", " + Buf.str();
719 }
720 return BlockCall;
721}
722
723void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
724 std::string BlockCall = SynthesizeBlockCall(Exp);
725
726 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
727 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
728
729 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
730 BlockCall.c_str(), BlockCall.size());
731}
732
733void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
734 SourceLocation DeclLoc = FD->getLocation();
735 unsigned parenCount = 0, nArgs = 0;
736
737 // We have 1 or more arguments that have closure pointers.
738 const char *startBuf = SM->getCharacterData(DeclLoc);
739 const char *startArgList = strchr(startBuf, '(');
740
741 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
742
743 parenCount++;
744 // advance the location to startArgList.
745 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf+1);
746 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
747
748 const char *topLevelCommaCursor = 0;
749 const char *argPtr = startArgList;
750 bool scannedBlockDecl = false;
Steve Naroff8af6a452008-10-02 17:12:56 +0000751 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000752
753 while (*argPtr++ && parenCount) {
754 switch (*argPtr) {
755 case '^':
756 scannedBlockDecl = true;
757 break;
758 case '(':
759 parenCount++;
760 break;
761 case ')':
762 parenCount--;
763 if (parenCount == 0) {
764 if (scannedBlockDecl) {
765 // If we are rewriting a definition, don't forget the arg name.
766 if (FD->getBody())
767 Tag += FD->getParamDecl(nArgs)->getName();
768 // The last argument is a closure pointer decl, rewrite it!
769 if (topLevelCommaCursor)
770 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-2, Tag.c_str(), Tag.size());
771 else
772 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
773 scannedBlockDecl = false; // reset.
774 }
775 nArgs++;
776 }
777 break;
778 case ',':
779 if (parenCount == 1) {
780 // Make sure the function takes more than one argument.
781 assert((FD->getNumParams() > 1) && "Rewriter fuzzy parser confused");
782 if (scannedBlockDecl) {
783 // If we are rewriting a definition, don't forget the arg name.
784 if (FD->getBody())
785 Tag += FD->getParamDecl(nArgs)->getName();
786 // The current argument is a closure pointer decl, rewrite it!
787 if (topLevelCommaCursor)
788 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-1, Tag.c_str(), Tag.size());
789 else
790 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
791 scannedBlockDecl = false;
792 }
793 nArgs++;
794 // advance the location to topLevelCommaCursor.
795 if (topLevelCommaCursor)
796 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-topLevelCommaCursor);
797 else
798 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList+1);
799 topLevelCommaCursor = argPtr;
800 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
801 }
802 break;
803 }
804 }
805 return;
806}
807
Steve Naroffeab5f632008-09-23 19:24:41 +0000808bool RewriteBlocks::BlockPointerTypeTakesAnyBlockArguments(QualType QT) {
809 const BlockPointerType *BPT = QT->getAsBlockPointerType();
810 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
811 const FunctionTypeProto *FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
812 if (FTP) {
813 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
814 E = FTP->arg_type_end(); I != E; ++I)
815 if (isBlockPointerType(*I))
816 return true;
817 }
818 return false;
819}
820
821void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000822 const char *&LParen, const char *&RParen) {
823 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000824 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
825
826 LParen = argPtr; // output the start.
827 argPtr++; // skip past the left paren.
828 unsigned parenCount = 1;
829
830 while (*argPtr && parenCount) {
831 switch (*argPtr) {
832 case '(': parenCount++; break;
833 case ')': parenCount--; break;
834 default: break;
835 }
836 if (parenCount) argPtr++;
837 }
838 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
839 RParen = argPtr; // output the end
840}
841
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000842void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000843 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
844 RewriteBlockPointerFunctionArgs(FD);
845 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000846 }
847 // Handle Variables and Typedefs.
848 SourceLocation DeclLoc = ND->getLocation();
849 QualType DeclT;
850 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
851 DeclT = VD->getType();
852 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
853 DeclT = TDD->getUnderlyingType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000854 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
855 DeclT = FD->getType();
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000856 else
857 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000858
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000859 const char *startBuf = SM->getCharacterData(DeclLoc);
860 const char *endBuf = startBuf;
861 // scan backward (from the decl location) for the end of the previous decl.
862 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
863 startBuf--;
864 assert((*startBuf == '^') &&
865 "RewriteBlockPointerDecl() scan error: no caret");
866 // Replace the '^' with '*', computing a negative offset.
867 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
868 ReplaceText(DeclLoc, 1, "*", 1);
869
870 if (BlockPointerTypeTakesAnyBlockArguments(DeclT)) {
871 // Replace the '^' with '*' for arguments.
872 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000873 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000874 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000875 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
876 while (argListBegin < argListEnd) {
877 if (*argListBegin == '^') {
878 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
879 ReplaceText(CaretLoc, 1, "*", 1);
880 }
881 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000882 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000883 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000884 return;
885}
886
Steve Naroff70f95502008-10-04 17:06:23 +0000887std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000888 Blocks.push_back(Exp);
889 bool haveByRefDecls = false;
890
891 // Add initializers for any closure decl refs.
892 GetBlockDeclRefExprs(Exp);
893 if (BlockDeclRefs.size()) {
894 // Unique all "by copy" declarations.
895 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
896 if (!BlockDeclRefs[i]->isByRef())
897 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
898 // Unique all "by ref" declarations.
899 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
900 if (BlockDeclRefs[i]->isByRef()) {
901 haveByRefDecls = true;
902 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
903 }
904 }
905 std::string FuncName;
906
907 if (CurFunctionDef)
908 FuncName = std::string(CurFunctionDef->getName());
909 else if (CurMethodDef) {
910 FuncName = std::string(CurMethodDef->getSelector().getName());
911 // Convert colons to underscores.
912 std::string::size_type loc = 0;
913 while ((loc = FuncName.find(":", loc)) != std::string::npos)
914 FuncName.replace(loc, 1, "_");
Steve Naroff39622b92008-10-03 15:38:09 +0000915 } else if (VD)
916 FuncName = std::string(VD->getName());
917
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000918 std::string BlockNumber = utostr(Blocks.size()-1);
919
Steve Naroff83ba14e2008-10-03 15:04:50 +0000920 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000921 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000922
Steve Naroff83ba14e2008-10-03 15:04:50 +0000923 std::string FunkTypeStr;
924
925 // Get a pointer to the function type so we can cast appropriately.
926 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
927
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000928 // Rewrite the closure block with a compound literal. The first cast is
929 // to prevent warnings from the C compiler.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000930 std::string Init = "(" + FunkTypeStr;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000931
Steve Naroff83ba14e2008-10-03 15:04:50 +0000932 Init += ")&" + Tag;
933
934 // Initialize the block function.
935 Init += "((void*)" + Func;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000936
937 // Add initializers for any closure decl refs.
938 if (BlockDeclRefs.size()) {
939 // Output all "by copy" declarations.
940 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
941 E = BlockByCopyDecls.end(); I != E; ++I) {
942 Init += ",";
943 if (isObjCType((*I)->getType())) {
944 Init += "[[";
945 Init += (*I)->getName();
946 Init += " retain] autorelease]";
Steve Naroff4e13b762008-10-03 20:28:15 +0000947 } else if (isBlockPointerType((*I)->getType())) {
948 Init += "(void *)";
949 Init += (*I)->getName();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000950 } else {
951 Init += (*I)->getName();
952 }
953 }
954 // Output all "by ref" declarations.
955 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
956 E = BlockByRefDecls.end(); I != E; ++I) {
957 Init += ",&";
958 Init += (*I)->getName();
959 }
960 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000961 Init += ")";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000962 BlockDeclRefs.clear();
963 BlockByRefDecls.clear();
964 BlockByCopyDecls.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000965 ImportedBlockDecls.clear();
966
Steve Naroff70f95502008-10-04 17:06:23 +0000967 return Init;
968}
969
970//===----------------------------------------------------------------------===//
971// Function Body / Expression rewriting
972//===----------------------------------------------------------------------===//
973
974Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
975 // Start by rewriting all children.
976 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
977 CI != E; ++CI)
978 if (*CI) {
979 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
980 Stmt *newStmt = RewriteFunctionBody(*CI);
981 if (newStmt)
982 *CI = newStmt;
983
984 // We've just rewritten the block body in place.
985 // Now we snarf the rewritten text and stash it away for later use.
986 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
987 RewrittenBlockExprs[CBE] = S;
988 std::string Init = SynthesizeBlockInitExpr(CBE);
989 // Do the rewrite, using S.size() which contains the rewritten size.
990 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
991 } else {
992 Stmt *newStmt = RewriteFunctionBody(*CI);
993 if (newStmt)
994 *CI = newStmt;
995 }
996 }
997 // Handle specific things.
998 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
999 if (CE->getCallee()->getType()->isBlockPointerType())
1000 RewriteBlockCall(CE);
1001 }
1002 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
1003 ScopedDecl *SD = DS->getDecl();
1004 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1005 if (isBlockPointerType(ND->getType()))
1006 RewriteBlockPointerDecl(ND);
1007 }
1008 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1009 if (isBlockPointerType(TD->getUnderlyingType()))
1010 RewriteBlockPointerDecl(TD);
1011 }
1012 }
1013 // Return this stmt unmodified.
1014 return S;
1015}
1016
1017/// HandleDeclInMainFile - This is called for each top-level decl defined in the
1018/// main file of the input.
1019void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
1020 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1021
1022 // Since function prototypes don't have ParmDecl's, we check the function
1023 // prototype. This enables us to rewrite function declarations and
1024 // definitions using the same code.
1025 QualType funcType = FD->getType();
1026
1027 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
1028 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
1029 E = fproto->arg_type_end(); I && (I != E); ++I)
1030 if (isBlockPointerType(*I)) {
1031 // All the args are checked/rewritten. Don't call twice!
1032 RewriteBlockPointerDecl(FD);
1033 break;
1034 }
1035 }
1036 if (Stmt *Body = FD->getBody()) {
1037 CurFunctionDef = FD;
1038 FD->setBody(RewriteFunctionBody(Body));
1039 // This synthesizes and inserts the block "impl" struct, invoke function,
1040 // and any copy/dispose helper functions.
1041 InsertBlockLiteralsWithinFunction(FD);
1042 CurFunctionDef = 0;
1043 }
1044 return;
1045 }
1046 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1047 RewriteMethodDecl(MD);
1048 if (Stmt *Body = MD->getBody()) {
1049 CurMethodDef = MD;
1050 RewriteFunctionBody(Body);
1051 InsertBlockLiteralsWithinMethod(MD);
1052 CurMethodDef = 0;
1053 }
1054 }
1055 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1056 if (isBlockPointerType(VD->getType())) {
1057 RewriteBlockPointerDecl(VD);
1058 if (VD->getInit()) {
1059 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
1060 RewriteFunctionBody(VD->getInit());
1061
1062 // We've just rewritten the block body in place.
1063 // Now we snarf the rewritten text and stash it away for later use.
1064 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1065 RewrittenBlockExprs[CBE] = S;
1066 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
1067 // Do the rewrite, using S.size() which contains the rewritten size.
1068 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1069 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
1070 }
1071 }
1072 }
1073 return;
1074 }
1075 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1076 if (isBlockPointerType(TD->getUnderlyingType()))
1077 RewriteBlockPointerDecl(TD);
1078 return;
1079 }
1080 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1081 if (RD->isDefinition()) {
1082 for (RecordDecl::field_const_iterator i = RD->field_begin(),
1083 e = RD->field_end(); i != e; ++i) {
1084 FieldDecl *FD = *i;
1085 if (isBlockPointerType(FD->getType()))
1086 RewriteBlockPointerDecl(FD);
1087 }
1088 }
1089 return;
1090 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001091}