blob: 8fbe768876147812173dbce392d4783eb5f2e4ae [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 Naroff1c9f81b2008-09-17 00:13:27 +000053
54 // The function/method we are rewriting.
55 FunctionDecl *CurFunctionDef;
56 ObjCMethodDecl *CurMethodDef;
57
58 bool IsHeader;
Steve Naroff13188952008-09-18 14:10:13 +000059 std::string InFileName;
60 std::string OutFileName;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000061
62 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000063public:
Steve Naroff13188952008-09-18 14:10:13 +000064 RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D,
65 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000066 ~RewriteBlocks() {
67 // Get the buffer corresponding to MainFileID.
68 // If we haven't changed it, then we are done.
69 if (const RewriteBuffer *RewriteBuf =
70 Rewrite.getRewriteBufferFor(MainFileID)) {
71 std::string S(RewriteBuf->begin(), RewriteBuf->end());
72 printf("%s\n", S.c_str());
73 } else {
74 printf("No changes\n");
75 }
76 }
77
78 void Initialize(ASTContext &context);
79
80 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen);
81 void ReplaceText(SourceLocation Start, unsigned OrigLength,
82 const char *NewStr, unsigned NewLength);
83
84 // Top Level Driver code.
85 virtual void HandleTopLevelDecl(Decl *D);
86 void HandleDeclInMainFile(Decl *D);
87
88 // Top level
89 Stmt *RewriteFunctionBody(Stmt *S);
90 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
91 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
92
93 // Block specific rewrite rules.
Steve Naroff39622b92008-10-03 15:38:09 +000094 void RewriteBlockExpr(BlockExpr *Exp, VarDecl *VD=0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000095
96 void RewriteBlockCall(CallExpr *Exp);
97 void RewriteBlockPointerDecl(NamedDecl *VD);
98 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
99
Steve Naroff4e13b762008-10-03 20:28:15 +0000100 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
101 const char *funcName, std::string Tag);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000102 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
103 const char *funcName, std::string Tag);
104 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag);
105 std::string SynthesizeBlockCall(CallExpr *Exp);
106 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
107 const char *FunName);
108
109 void GetBlockDeclRefExprs(Stmt *S);
110 void GetBlockCallExprs(Stmt *S);
111
112 // We avoid calling Type::isBlockPointerType(), since it operates on the
113 // canonical type. We only care if the top-level type is a closure pointer.
114 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
115
116 // FIXME: This predicate seems like it would be useful to add to ASTContext.
117 bool isObjCType(QualType T) {
118 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
119 return false;
120
121 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
122
123 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
124 OCT == Context->getCanonicalType(Context->getObjCClassType()))
125 return true;
126
127 if (const PointerType *PT = OCT->getAsPointerType()) {
128 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
129 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
130 return true;
131 }
132 return false;
133 }
134 // ObjC rewrite methods.
135 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
136 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
137 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
138 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffeab5f632008-09-23 19:24:41 +0000139
140 bool BlockPointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000141 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000142};
143
144}
145
146static bool IsHeaderFile(const std::string &Filename) {
147 std::string::size_type DotPos = Filename.rfind('.');
148
149 if (DotPos == std::string::npos) {
150 // no file extension
151 return false;
152 }
153
154 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
155 // C header: .h
156 // C++ header: .hh or .H;
157 return Ext == "h" || Ext == "hh" || Ext == "H";
158}
159
Steve Naroff13188952008-09-18 14:10:13 +0000160RewriteBlocks::RewriteBlocks(std::string inFile, std::string outFile,
161 Diagnostic &D, const LangOptions &LOpts) :
162 Diags(D), LangOpts(LOpts) {
163 IsHeader = IsHeaderFile(inFile);
164 InFileName = inFile;
165 OutFileName = outFile;
166 CurFunctionDef = 0;
167 CurMethodDef = 0;
168 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
169 "rewriting failed");
170 NoNestedBlockCalls = Diags.getCustomDiagID(Diagnostic::Warning,
171 "Rewrite support for closure calls nested within closure blocks is incomplete");
172}
173
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000174ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
Steve Naroff13188952008-09-18 14:10:13 +0000175 const std::string& OutFile,
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000176 Diagnostic &Diags,
177 const LangOptions &LangOpts) {
Steve Naroff13188952008-09-18 14:10:13 +0000178 return new RewriteBlocks(InFile, OutFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000179}
180
181void RewriteBlocks::Initialize(ASTContext &context) {
182 Context = &context;
183 SM = &Context->getSourceManager();
184
185 // Get the ID and start/end of the main file.
186 MainFileID = SM->getMainFileID();
187 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
188 MainFileStart = MainBuf->getBufferStart();
189 MainFileEnd = MainBuf->getBufferEnd();
190
191 Rewrite.setSourceMgr(Context->getSourceManager());
192
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000193 if (IsHeader)
194 Preamble = "#pragma once\n";
195 Preamble += "#ifndef BLOCK_IMPL\n";
196 Preamble += "#define BLOCK_IMPL\n";
197 Preamble += "struct __block_impl {\n";
198 Preamble += " void *isa;\n";
199 Preamble += " int Flags;\n";
200 Preamble += " int Size;\n";
201 Preamble += " void *FuncPtr;\n";
202 Preamble += "};\n";
203 Preamble += "enum {\n";
204 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
205 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
206 Preamble += "};\n";
207 if (LangOpts.Microsoft)
208 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
209 else
210 Preamble += "#define __OBJC_RW_EXTERN extern\n";
211 Preamble += "// Runtime copy/destroy helper functions\n";
212 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
213 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
214 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
215 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000216 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
217 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000218 Preamble += "#endif\n";
219
220 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
221 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000222}
223
224void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData,
225 unsigned StrLen)
226{
227 if (!Rewrite.InsertText(Loc, StrData, StrLen))
228 return;
229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230}
231
232void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength,
233 const char *NewStr, unsigned NewLength) {
234 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength))
235 return;
236 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
237}
238
239void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) {
240 bool haveBlockPtrs = false;
241 for (ObjCMethodDecl::param_iterator I = Method->param_begin(),
242 E = Method->param_end(); I != E; ++I)
243 if (isBlockPointerType((*I)->getType()))
244 haveBlockPtrs = true;
245
246 if (!haveBlockPtrs)
247 return;
248
249 // Do a fuzzy rewrite.
250 // We have 1 or more arguments that have closure pointers.
251 SourceLocation Loc = Method->getLocStart();
252 SourceLocation LocEnd = Method->getLocEnd();
253 const char *startBuf = SM->getCharacterData(Loc);
254 const char *endBuf = SM->getCharacterData(LocEnd);
255
256 const char *methodPtr = startBuf;
Steve Naroff8af6a452008-10-02 17:12:56 +0000257 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000258
259 while (*methodPtr++ && (methodPtr != endBuf)) {
260 switch (*methodPtr) {
261 case ':':
262 methodPtr++;
263 if (*methodPtr == '(') {
264 const char *scanType = ++methodPtr;
265 bool foundBlockPointer = false;
266 unsigned parenCount = 1;
267
268 while (parenCount) {
269 switch (*scanType) {
270 case '(':
271 parenCount++;
272 break;
273 case ')':
274 parenCount--;
275 break;
276 case '^':
277 foundBlockPointer = true;
278 break;
279 }
280 scanType++;
281 }
282 if (foundBlockPointer) {
283 // advance the location to startArgList.
284 Loc = Loc.getFileLocWithOffset(methodPtr-startBuf);
285 assert((Loc.isValid()) && "Invalid Loc");
286 ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size());
287
288 // Advance startBuf. Since the underlying buffer has changed,
289 // it's very important to advance startBuf (so we can correctly
290 // compute a relative Loc the next time around).
291 startBuf = methodPtr;
292 }
293 // Advance the method ptr to the end of the type.
294 methodPtr = scanType;
295 }
296 break;
297 }
298 }
299 return;
300}
301
302void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
303 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
304 E = ClassDecl->instmeth_end(); I != E; ++I)
305 RewriteMethodDecl(*I);
306 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
307 E = ClassDecl->classmeth_end(); I != E; ++I)
308 RewriteMethodDecl(*I);
309}
310
311void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
312 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
313 E = CatDecl->instmeth_end(); I != E; ++I)
314 RewriteMethodDecl(*I);
315 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
316 E = CatDecl->classmeth_end(); I != E; ++I)
317 RewriteMethodDecl(*I);
318}
319
320void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
321 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
322 E = PDecl->instmeth_end(); I != E; ++I)
323 RewriteMethodDecl(*I);
324 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
325 E = PDecl->classmeth_end(); I != E; ++I)
326 RewriteMethodDecl(*I);
327}
328
329//===----------------------------------------------------------------------===//
330// Top Level Driver Code
331//===----------------------------------------------------------------------===//
332
333void RewriteBlocks::HandleTopLevelDecl(Decl *D) {
334 // Two cases: either the decl could be in the main file, or it could be in a
335 // #included file. If the former, rewrite it now. If the later, check to see
336 // if we rewrote the #include/#import.
337 SourceLocation Loc = D->getLocation();
338 Loc = SM->getLogicalLoc(Loc);
339
340 // If this is for a builtin, ignore it.
341 if (Loc.isInvalid()) return;
342
343 if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D))
344 RewriteInterfaceDecl(MD);
345 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D))
346 RewriteCategoryDecl(CD);
347 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
348 RewriteProtocolDecl(PD);
349
350 // If we have a decl in the main file, see if we should rewrite it.
351 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
352 HandleDeclInMainFile(D);
353 return;
354}
355
356std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i,
357 const char *funcName,
358 std::string Tag) {
359 const FunctionType *AFT = CE->getFunctionType();
360 QualType RT = AFT->getResultType();
Steve Naroff48a8c612008-10-03 12:09:49 +0000361 std::string StructRef = "struct " + Tag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000362 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000363 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000364
365 if (isa<FunctionTypeNoProto>(AFT)) {
366 S += "()";
367 } else if (CE->arg_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000368 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000369 } else {
370 const FunctionTypeProto *FT = cast<FunctionTypeProto>(AFT);
371 assert(FT && "SynthesizeBlockFunc: No function proto");
372 S += '(';
373 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000374 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000375 std::string ParamStr;
Steve Naroff9c3c9022008-09-17 18:37:59 +0000376 for (BlockExpr::arg_iterator AI = CE->arg_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000377 E = CE->arg_end(); AI != E; ++AI) {
378 if (AI != CE->arg_begin()) S += ", ";
379 ParamStr = (*AI)->getName();
380 (*AI)->getType().getAsStringInternal(ParamStr);
381 S += ParamStr;
382 }
383 if (FT->isVariadic()) {
384 if (!CE->arg_empty()) S += ", ";
385 S += "...";
386 }
387 S += ')';
388 }
389 S += " {\n";
390
391 bool haveByRefDecls = false;
392
393 // Create local declarations to avoid rewriting all closure decl ref exprs.
394 // First, emit a declaration for all "by ref" decls.
395 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
396 E = BlockByRefDecls.end(); I != E; ++I) {
397 // Note: It is not possible to have "by ref" closure pointer decls.
398 haveByRefDecls = true;
399 S += " ";
400 std::string Name = (*I)->getName();
401 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
402 S += Name + " = __cself->" + (*I)->getName() + "; // bound by ref\n";
403 }
404 // Next, emit a declaration for all "by copy" declarations.
405 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
406 E = BlockByCopyDecls.end(); I != E; ++I) {
407 S += " ";
408 std::string Name = (*I)->getName();
409 // Handle nested closure invocation. For example:
410 //
411 // void (^myImportedClosure)(void);
412 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
413 //
414 // void (^anotherClosure)(void);
415 // anotherClosure = ^(void) {
416 // myImportedClosure(); // import and invoke the closure
417 // };
418 //
419 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000420 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000421 else
422 (*I)->getType().getAsStringInternal(Name);
423 S += Name + " = __cself->" + (*I)->getName() + "; // bound by copy\n";
424 }
Steve Naroff9c3c9022008-09-17 18:37:59 +0000425 if (BlockExpr *CBE = dyn_cast<BlockExpr>(CE)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000426 std::string BodyBuf;
427
428 SourceLocation BodyLocStart = CBE->getBody()->getLocStart();
429 SourceLocation BodyLocEnd = CBE->getBody()->getLocEnd();
430 const char *BodyStartBuf = SM->getCharacterData(BodyLocStart);
431 const char *BodyEndBuf = SM->getCharacterData(BodyLocEnd);
432
433 BodyBuf.append(BodyStartBuf, BodyEndBuf-BodyStartBuf+1);
434
Steve Naroff4e13b762008-10-03 20:28:15 +0000435 //fprintf(stderr, "BodyBuf=>%s\n", BodyBuf.c_str());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000436 if (BlockDeclRefs.size()) {
437 unsigned int nCharsAdded = 0;
438 for (unsigned i = 0; i < BlockDeclRefs.size(); i++) {
439 if (BlockDeclRefs[i]->isByRef()) {
440 // Add a level of indirection! The code below assumes
441 // the closure decl refs/locations are in strictly ascending
442 // order. The traversal performed by GetBlockDeclRefExprs()
443 // currently does this. FIXME: Wrap the *x with parens,
444 // just in case x is a more complex expression, like x->member,
445 // which needs to be rewritten to (*x)->member.
446 SourceLocation StarLoc = BlockDeclRefs[i]->getLocStart();
447 const char *StarBuf = SM->getCharacterData(StarLoc);
448 BodyBuf.insert(StarBuf-BodyStartBuf+nCharsAdded, 1, '*');
449 // Get a fresh buffer, the insert might have caused it to grow.
450 BodyStartBuf = SM->getCharacterData(BodyLocStart);
451 nCharsAdded++;
452 } else if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
453 Diags.Report(NoNestedBlockCalls);
454
455 GetBlockCallExprs(CE);
Steve Naroff4e13b762008-10-03 20:28:15 +0000456 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000457
458 // Rewrite the closure in place.
459 // The character based equivalent of RewriteBlockCall().
460 // Need to get the CallExpr associated with this BlockDeclRef.
461 std::string BlockCall = SynthesizeBlockCall(BlockCallExprs[BlockDeclRefs[i]]);
462
Steve Naroff4e13b762008-10-03 20:28:15 +0000463 // FIXME: this is still incomplete.
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000464 SourceLocation CallLocStart = BlockCallExprs[BlockDeclRefs[i]]->getLocStart();
465 SourceLocation CallLocEnd = BlockCallExprs[BlockDeclRefs[i]]->getLocEnd();
Steve Naroff4e13b762008-10-03 20:28:15 +0000466 const char *CallStart = SM->getCharacterData(CallLocStart) + nCharsAdded;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000467 const char *CallEnd = SM->getCharacterData(CallLocEnd);
468 unsigned CallBytes = CallEnd-CallStart;
Steve Naroff4e13b762008-10-03 20:28:15 +0000469 //fprintf(stderr, "BlockCall=>%s CallStart=%d\n", BlockCall.c_str(),CallStart);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000470 BodyBuf.replace(CallStart-BodyStartBuf, CallBytes, BlockCall.c_str());
471 nCharsAdded += CallBytes;
472 }
473 }
474 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000475 S += " ";
476 S += BodyBuf;
477 }
478 S += "\n}\n";
479 return S;
480}
481
Steve Naroff4e13b762008-10-03 20:28:15 +0000482std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
483 const char *funcName,
484 std::string Tag) {
485 std::string StructRef = "struct " + Tag;
486 std::string S = "static void __";
487
488 S += funcName;
489 S += "_block_copy_" + utostr(i);
490 S += "(" + StructRef;
491 S += "*dst, " + StructRef;
492 S += "*src) {";
493 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
494 E = ImportedBlockDecls.end(); I != E; ++I) {
495 S += "_Block_copy_assign(&dst->";
496 S += (*I)->getName();
497 S += ", src->";
498 S += (*I)->getName();
499 S += ");}";
500 }
501 S += "\nstatic void __";
502 S += funcName;
503 S += "_block_dispose_" + utostr(i);
504 S += "(" + StructRef;
505 S += "*src) {";
506 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
507 E = ImportedBlockDecls.end(); I != E; ++I) {
508 S += "_Block_destroy(src->";
509 S += (*I)->getName();
510 S += ");";
511 }
512 S += "}\n";
513 return S;
514}
515
Steve Naroff48a8c612008-10-03 12:09:49 +0000516std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag) {
517 std::string S = "struct " + Tag;
518 std::string Constructor = " " + Tag;
519
520 S += " {\n struct __block_impl impl;\n";
521 Constructor += "(void *fp";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000522
523 GetBlockDeclRefExprs(CE);
524 if (BlockDeclRefs.size()) {
525 // Unique all "by copy" declarations.
526 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
527 if (!BlockDeclRefs[i]->isByRef())
528 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
529 // Unique all "by ref" declarations.
530 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
531 if (BlockDeclRefs[i]->isByRef())
532 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
533
534 // Output all "by copy" declarations.
535 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
536 E = BlockByCopyDecls.end(); I != E; ++I) {
537 S += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000538 std::string FieldName = (*I)->getName();
539 std::string ArgName = "_" + FieldName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000540 // Handle nested closure invocation. For example:
541 //
542 // void (^myImportedBlock)(void);
543 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
544 //
545 // void (^anotherBlock)(void);
546 // anotherBlock = ^(void) {
547 // myImportedBlock(); // import and invoke the closure
548 // };
549 //
Steve Naroff4e13b762008-10-03 20:28:15 +0000550 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000551 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000552 Constructor += ", void *" + ArgName;
553 } else {
554 (*I)->getType().getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000555 (*I)->getType().getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000556 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000557 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000558 S += FieldName + ";\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000559 }
560 // Output all "by ref" declarations.
561 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
562 E = BlockByRefDecls.end(); I != E; ++I) {
563 S += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000564 std::string FieldName = (*I)->getName();
565 std::string ArgName = "_" + FieldName;
566 // Handle nested closure invocation. For example:
567 //
568 // void (^myImportedBlock)(void);
569 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
570 //
571 // void (^anotherBlock)(void);
572 // anotherBlock = ^(void) {
573 // myImportedBlock(); // import and invoke the closure
574 // };
575 //
576 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000577 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000578 Constructor += ", void *" + ArgName;
579 } else {
580 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000581 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000582 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000583 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000584 S += FieldName + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000585 }
586 // Finish writing the constructor.
587 // FIXME: handle NSConcreteGlobalBlock.
588 Constructor += ", int flags=0) {\n";
Steve Naroff83ba14e2008-10-03 15:04:50 +0000589 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
Steve Naroff48a8c612008-10-03 12:09:49 +0000590 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
591
592 // Initialize all "by copy" arguments.
593 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
594 E = BlockByCopyDecls.end(); I != E; ++I) {
595 std::string Name = (*I)->getName();
596 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000597 if (isBlockPointerType((*I)->getType()))
598 Constructor += Name + " = (struct __block_impl *)_";
599 else
600 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000601 Constructor += Name + ";\n";
602 }
603 // Initialize all "by ref" arguments.
604 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
605 E = BlockByRefDecls.end(); I != E; ++I) {
606 std::string Name = (*I)->getName();
607 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000608 if (isBlockPointerType((*I)->getType()))
609 Constructor += Name + " = (struct __block_impl *)_";
610 else
611 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000612 Constructor += Name + ";\n";
613 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000614 } else {
615 // Finish writing the constructor.
616 // FIXME: handle NSConcreteGlobalBlock.
617 Constructor += ", int flags=0) {\n";
618 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
619 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000620 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000621 Constructor += " ";
622 Constructor += "}\n";
623 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000624 S += "};\n";
625 return S;
626}
627
628void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
629 const char *FunName) {
630 // Insert closures that were part of the function.
631 for (unsigned i = 0; i < Blocks.size(); i++) {
632
Steve Naroff48a8c612008-10-03 12:09:49 +0000633 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000634
635 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag);
636
637 InsertText(FunLocStart, CI.c_str(), CI.size());
Steve Naroff4e13b762008-10-03 20:28:15 +0000638
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000639 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
640
641 InsertText(FunLocStart, CF.c_str(), CF.size());
642
Steve Naroff4e13b762008-10-03 20:28:15 +0000643 if (ImportedBlockDecls.size()) {
644 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
645 InsertText(FunLocStart, HF.c_str(), HF.size());
646 }
647
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000648 BlockDeclRefs.clear();
649 BlockByRefDecls.clear();
650 BlockByCopyDecls.clear();
651 BlockCallExprs.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000652 ImportedBlockDecls.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000653 }
654 Blocks.clear();
655}
656
657void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000658 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000659 const char *FuncName = FD->getName();
660
661 SynthesizeBlockLiterals(FunLocStart, FuncName);
662}
663
664void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
665 SourceLocation FunLocStart = MD->getLocStart();
666 std::string FuncName = std::string(MD->getSelector().getName());
667 // Convert colons to underscores.
668 std::string::size_type loc = 0;
669 while ((loc = FuncName.find(":", loc)) != std::string::npos)
670 FuncName.replace(loc, 1, "_");
671
672 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
673}
674
675/// HandleDeclInMainFile - This is called for each top-level decl defined in the
676/// main file of the input.
677void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
679
680 // Since function prototypes don't have ParmDecl's, we check the function
681 // prototype. This enables us to rewrite function declarations and
682 // definitions using the same code.
683 QualType funcType = FD->getType();
684
685 if (FunctionTypeProto *fproto = dyn_cast<FunctionTypeProto>(funcType)) {
686 for (FunctionTypeProto::arg_type_iterator I = fproto->arg_type_begin(),
687 E = fproto->arg_type_end(); I && (I != E); ++I)
688 if (isBlockPointerType(*I)) {
689 // All the args are checked/rewritten. Don't call twice!
690 RewriteBlockPointerDecl(FD);
691 break;
692 }
693 }
694 if (Stmt *Body = FD->getBody()) {
695 CurFunctionDef = FD;
696 FD->setBody(RewriteFunctionBody(Body));
697 InsertBlockLiteralsWithinFunction(FD);
698 CurFunctionDef = 0;
699 }
700 return;
701 }
702 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
703 RewriteMethodDecl(MD);
704 if (Stmt *Body = MD->getBody()) {
705 CurMethodDef = MD;
706 RewriteFunctionBody(Body);
707 InsertBlockLiteralsWithinMethod(MD);
708 CurMethodDef = 0;
709 }
710 }
Steve Naroff39622b92008-10-03 15:38:09 +0000711 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
712 if (isBlockPointerType(VD->getType())) {
713 RewriteBlockPointerDecl(VD);
714 if (VD->getInit()) {
715 if (BlockExpr *BExp = dyn_cast<BlockExpr>(VD->getInit())) {
716 RewriteBlockExpr(BExp, VD);
717 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
718 }
719 }
720 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000721 return;
722 }
723 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
724 if (isBlockPointerType(TD->getUnderlyingType()))
725 RewriteBlockPointerDecl(TD);
726 return;
727 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000728 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
729 if (RD->isDefinition()) {
730 for (RecordDecl::field_const_iterator i = RD->field_begin(),
731 e = RD->field_end(); i != e; ++i) {
732 FieldDecl *FD = *i;
733 if (isBlockPointerType(FD->getType()))
734 RewriteBlockPointerDecl(FD);
735 }
736 }
737 return;
738 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000739}
740
741void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
742 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
743 CI != E; ++CI)
744 if (*CI)
745 GetBlockDeclRefExprs(*CI);
746
747 // Handle specific things.
748 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
749 // FIXME: Handle enums.
750 if (!isa<FunctionDecl>(CDRE->getDecl()))
751 BlockDeclRefs.push_back(CDRE);
752 return;
753}
754
755void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
756 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
757 CI != E; ++CI)
758 if (*CI)
759 GetBlockCallExprs(*CI);
760
761 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff4e13b762008-10-03 20:28:15 +0000762 if (CE->getCallee()->getType()->isBlockPointerType()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000763 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
Steve Naroff4e13b762008-10-03 20:28:15 +0000764 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000765 }
766 return;
767}
768
769//===----------------------------------------------------------------------===//
770// Function Body / Expression rewriting
771//===----------------------------------------------------------------------===//
772
773Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
774 // Start by rewriting all children.
775 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
776 CI != E; ++CI)
777 if (*CI) {
Steve Naroff9c3c9022008-09-17 18:37:59 +0000778 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000779 // We intentionally avoid rewritting the contents of a closure block
780 // expr. InsertBlockLiteralsWithinFunction() will rewrite the body.
Steve Naroff9c3c9022008-09-17 18:37:59 +0000781 RewriteBlockExpr(CBE);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000782 } else {
783 Stmt *newStmt = RewriteFunctionBody(*CI);
784 if (newStmt)
785 *CI = newStmt;
786 }
787 }
788 // Handle specific things.
789 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
790 if (CE->getCallee()->getType()->isBlockPointerType())
791 RewriteBlockCall(CE);
792 }
793 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
794 ScopedDecl *SD = DS->getDecl();
795 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
796 if (isBlockPointerType(ND->getType()))
797 RewriteBlockPointerDecl(ND);
798 }
799 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
800 if (isBlockPointerType(TD->getUnderlyingType()))
801 RewriteBlockPointerDecl(TD);
802 }
803 }
804 // Return this stmt unmodified.
805 return S;
806}
807
808std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
809 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000810 const char *closureName = 0;
811 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000812
813 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
814 closureName = DRE->getDecl()->getName();
815 CPT = DRE->getType()->getAsBlockPointerType();
816 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
817 closureName = CDRE->getDecl()->getName();
818 CPT = CDRE->getType()->getAsBlockPointerType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000819 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
820 closureName = MExpr->getMemberDecl()->getName();
821 CPT = MExpr->getType()->getAsBlockPointerType();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000822 } else {
823 assert(1 && "RewriteBlockClass: Bad type");
824 }
825 assert(CPT && "RewriteBlockClass: Bad type");
826 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
827 assert(FT && "RewriteBlockClass: Bad type");
828 const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FT);
829 // FTP will be null for closures that don't take arguments.
830
831 // Build a closure call - start with a paren expr to enforce precedence.
832 std::string BlockCall = "(";
833
834 // Synthesize the cast.
835 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000836 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000837 if (FTP) {
838 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
839 E = FTP->arg_type_end(); I && (I != E); ++I)
840 BlockCall += ", " + (*I).getAsString();
841 }
842 BlockCall += "))"; // close the argument list and paren expression.
843
Steve Naroff83ba14e2008-10-03 15:04:50 +0000844 // Invoke the closure. We need to cast it since the declaration type is
845 // bogus (it's a function pointer type)
846 BlockCall += "((struct __block_impl *)";
847 std::string closureExprBufStr;
848 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
849 Exp->getCallee()->printPretty(closureExprBuf);
850 BlockCall += closureExprBuf.str();
851 BlockCall += ")->FuncPtr)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000852
853 // Add the arguments.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000854 BlockCall += "((struct __block_impl *)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000855 BlockCall += closureName;
856 for (CallExpr::arg_iterator I = Exp->arg_begin(),
857 E = Exp->arg_end(); I != E; ++I) {
858 std::string syncExprBufS;
859 llvm::raw_string_ostream Buf(syncExprBufS);
860 (*I)->printPretty(Buf);
861 BlockCall += ", " + Buf.str();
862 }
863 return BlockCall;
864}
865
866void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
867 std::string BlockCall = SynthesizeBlockCall(Exp);
868
869 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
870 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
871
872 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
873 BlockCall.c_str(), BlockCall.size());
874}
875
876void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
877 SourceLocation DeclLoc = FD->getLocation();
878 unsigned parenCount = 0, nArgs = 0;
879
880 // We have 1 or more arguments that have closure pointers.
881 const char *startBuf = SM->getCharacterData(DeclLoc);
882 const char *startArgList = strchr(startBuf, '(');
883
884 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
885
886 parenCount++;
887 // advance the location to startArgList.
888 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf+1);
889 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
890
891 const char *topLevelCommaCursor = 0;
892 const char *argPtr = startArgList;
893 bool scannedBlockDecl = false;
Steve Naroff8af6a452008-10-02 17:12:56 +0000894 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000895
896 while (*argPtr++ && parenCount) {
897 switch (*argPtr) {
898 case '^':
899 scannedBlockDecl = true;
900 break;
901 case '(':
902 parenCount++;
903 break;
904 case ')':
905 parenCount--;
906 if (parenCount == 0) {
907 if (scannedBlockDecl) {
908 // If we are rewriting a definition, don't forget the arg name.
909 if (FD->getBody())
910 Tag += FD->getParamDecl(nArgs)->getName();
911 // The last argument is a closure pointer decl, rewrite it!
912 if (topLevelCommaCursor)
913 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-2, Tag.c_str(), Tag.size());
914 else
915 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
916 scannedBlockDecl = false; // reset.
917 }
918 nArgs++;
919 }
920 break;
921 case ',':
922 if (parenCount == 1) {
923 // Make sure the function takes more than one argument.
924 assert((FD->getNumParams() > 1) && "Rewriter fuzzy parser confused");
925 if (scannedBlockDecl) {
926 // If we are rewriting a definition, don't forget the arg name.
927 if (FD->getBody())
928 Tag += FD->getParamDecl(nArgs)->getName();
929 // The current argument is a closure pointer decl, rewrite it!
930 if (topLevelCommaCursor)
931 ReplaceText(DeclLoc, argPtr-topLevelCommaCursor-1, Tag.c_str(), Tag.size());
932 else
933 ReplaceText(DeclLoc, argPtr-startArgList-1, Tag.c_str(), Tag.size());
934 scannedBlockDecl = false;
935 }
936 nArgs++;
937 // advance the location to topLevelCommaCursor.
938 if (topLevelCommaCursor)
939 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-topLevelCommaCursor);
940 else
941 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList+1);
942 topLevelCommaCursor = argPtr;
943 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
944 }
945 break;
946 }
947 }
948 return;
949}
950
Steve Naroffeab5f632008-09-23 19:24:41 +0000951bool RewriteBlocks::BlockPointerTypeTakesAnyBlockArguments(QualType QT) {
952 const BlockPointerType *BPT = QT->getAsBlockPointerType();
953 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
954 const FunctionTypeProto *FTP = BPT->getPointeeType()->getAsFunctionTypeProto();
955 if (FTP) {
956 for (FunctionTypeProto::arg_type_iterator I = FTP->arg_type_begin(),
957 E = FTP->arg_type_end(); I != E; ++I)
958 if (isBlockPointerType(*I))
959 return true;
960 }
961 return false;
962}
963
964void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000965 const char *&LParen, const char *&RParen) {
966 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000967 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
968
969 LParen = argPtr; // output the start.
970 argPtr++; // skip past the left paren.
971 unsigned parenCount = 1;
972
973 while (*argPtr && parenCount) {
974 switch (*argPtr) {
975 case '(': parenCount++; break;
976 case ')': parenCount--; break;
977 default: break;
978 }
979 if (parenCount) argPtr++;
980 }
981 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
982 RParen = argPtr; // output the end
983}
984
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000985void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000986 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
987 RewriteBlockPointerFunctionArgs(FD);
988 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000989 }
990 // Handle Variables and Typedefs.
991 SourceLocation DeclLoc = ND->getLocation();
992 QualType DeclT;
993 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
994 DeclT = VD->getType();
995 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
996 DeclT = TDD->getUnderlyingType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000997 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
998 DeclT = FD->getType();
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000999 else
1000 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +00001001
Steve Naroffca3bb4f2008-09-23 21:15:53 +00001002 const char *startBuf = SM->getCharacterData(DeclLoc);
1003 const char *endBuf = startBuf;
1004 // scan backward (from the decl location) for the end of the previous decl.
1005 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
1006 startBuf--;
1007 assert((*startBuf == '^') &&
1008 "RewriteBlockPointerDecl() scan error: no caret");
1009 // Replace the '^' with '*', computing a negative offset.
1010 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
1011 ReplaceText(DeclLoc, 1, "*", 1);
1012
1013 if (BlockPointerTypeTakesAnyBlockArguments(DeclT)) {
1014 // Replace the '^' with '*' for arguments.
1015 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001016 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +00001017 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +00001018 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
1019 while (argListBegin < argListEnd) {
1020 if (*argListBegin == '^') {
1021 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
1022 ReplaceText(CaretLoc, 1, "*", 1);
1023 }
1024 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001025 }
Steve Naroffeab5f632008-09-23 19:24:41 +00001026 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001027 return;
1028}
1029
Steve Naroff39622b92008-10-03 15:38:09 +00001030void RewriteBlocks::RewriteBlockExpr(BlockExpr *Exp, VarDecl *VD) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001031 Blocks.push_back(Exp);
1032 bool haveByRefDecls = false;
1033
1034 // Add initializers for any closure decl refs.
1035 GetBlockDeclRefExprs(Exp);
1036 if (BlockDeclRefs.size()) {
1037 // Unique all "by copy" declarations.
1038 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
1039 if (!BlockDeclRefs[i]->isByRef())
1040 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
1041 // Unique all "by ref" declarations.
1042 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
1043 if (BlockDeclRefs[i]->isByRef()) {
1044 haveByRefDecls = true;
1045 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
1046 }
1047 }
1048 std::string FuncName;
1049
1050 if (CurFunctionDef)
1051 FuncName = std::string(CurFunctionDef->getName());
1052 else if (CurMethodDef) {
1053 FuncName = std::string(CurMethodDef->getSelector().getName());
1054 // Convert colons to underscores.
1055 std::string::size_type loc = 0;
1056 while ((loc = FuncName.find(":", loc)) != std::string::npos)
1057 FuncName.replace(loc, 1, "_");
Steve Naroff39622b92008-10-03 15:38:09 +00001058 } else if (VD)
1059 FuncName = std::string(VD->getName());
1060
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001061 std::string BlockNumber = utostr(Blocks.size()-1);
1062
Steve Naroff83ba14e2008-10-03 15:04:50 +00001063 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
Steve Naroffa0b75cf2008-10-02 23:30:43 +00001064 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001065
Steve Naroff83ba14e2008-10-03 15:04:50 +00001066 std::string FunkTypeStr;
1067
1068 // Get a pointer to the function type so we can cast appropriately.
1069 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
1070
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001071 // Rewrite the closure block with a compound literal. The first cast is
1072 // to prevent warnings from the C compiler.
Steve Naroff83ba14e2008-10-03 15:04:50 +00001073 std::string Init = "(" + FunkTypeStr;
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001074
Steve Naroff83ba14e2008-10-03 15:04:50 +00001075 Init += ")&" + Tag;
1076
1077 // Initialize the block function.
1078 Init += "((void*)" + Func;
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001079
1080 // Add initializers for any closure decl refs.
1081 if (BlockDeclRefs.size()) {
1082 // Output all "by copy" declarations.
1083 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
1084 E = BlockByCopyDecls.end(); I != E; ++I) {
1085 Init += ",";
1086 if (isObjCType((*I)->getType())) {
1087 Init += "[[";
1088 Init += (*I)->getName();
1089 Init += " retain] autorelease]";
Steve Naroff4e13b762008-10-03 20:28:15 +00001090 } else if (isBlockPointerType((*I)->getType())) {
1091 Init += "(void *)";
1092 Init += (*I)->getName();
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001093 } else {
1094 Init += (*I)->getName();
1095 }
1096 }
1097 // Output all "by ref" declarations.
1098 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
1099 E = BlockByRefDecls.end(); I != E; ++I) {
1100 Init += ",&";
1101 Init += (*I)->getName();
1102 }
1103 }
Steve Naroff83ba14e2008-10-03 15:04:50 +00001104 Init += ")";
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001105 BlockDeclRefs.clear();
1106 BlockByRefDecls.clear();
1107 BlockByCopyDecls.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +00001108 ImportedBlockDecls.clear();
1109
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001110 // Do the rewrite.
1111 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
1112 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
1113 ReplaceText(Exp->getLocStart(), endBuf-startBuf+1, Init.c_str(), Init.size());
1114 return;
1115}