blob: f302913661872ff7b031713d9a9f906bc31b04e8 [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;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000037
38 ASTContext *Context;
39 SourceManager *SM;
Chris Lattner2b2453a2009-01-17 06:22:33 +000040 FileID MainFileID;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000041 const char *MainFileStart, *MainFileEnd;
42
43 // Block expressions.
44 llvm::SmallVector<BlockExpr *, 32> Blocks;
45 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
46 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
47
48 // Block related declarations.
49 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
50 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Steve Naroff4e13b762008-10-03 20:28:15 +000051 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Steve Naroff70f95502008-10-04 17:06:23 +000052
53 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000054
55 // The function/method we are rewriting.
56 FunctionDecl *CurFunctionDef;
57 ObjCMethodDecl *CurMethodDef;
58
59 bool IsHeader;
Steve Naroff13188952008-09-18 14:10:13 +000060 std::string InFileName;
61 std::string OutFileName;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000062
63 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000064public:
Steve Naroff13188952008-09-18 14:10:13 +000065 RewriteBlocks(std::string inFile, std::string outFile, Diagnostic &D,
66 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000067 ~RewriteBlocks() {
68 // Get the buffer corresponding to MainFileID.
69 // If we haven't changed it, then we are done.
70 if (const RewriteBuffer *RewriteBuf =
71 Rewrite.getRewriteBufferFor(MainFileID)) {
72 std::string S(RewriteBuf->begin(), RewriteBuf->end());
73 printf("%s\n", S.c_str());
74 } else {
75 printf("No changes\n");
76 }
77 }
78
79 void Initialize(ASTContext &context);
80
81 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen);
82 void ReplaceText(SourceLocation Start, unsigned OrigLength,
83 const char *NewStr, unsigned NewLength);
84
85 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +000086 virtual void HandleTopLevelDecl(DeclGroupRef D) {
87 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
88 HandleTopLevelSingleDecl(*I);
89 }
90 void HandleTopLevelSingleDecl(Decl *D);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000091 void HandleDeclInMainFile(Decl *D);
92
93 // Top level
94 Stmt *RewriteFunctionBody(Stmt *S);
95 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
96 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
97
98 // Block specific rewrite rules.
Steve Naroff70f95502008-10-04 17:06:23 +000099 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000100
101 void RewriteBlockCall(CallExpr *Exp);
102 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff5e52b172008-10-04 18:52:47 +0000103 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000104 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
105
Steve Naroff4e13b762008-10-03 20:28:15 +0000106 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
107 const char *funcName, std::string Tag);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000108 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
109 const char *funcName, std::string Tag);
Steve Naroffacba0f22008-10-04 23:47:37 +0000110 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
111 bool hasCopyDisposeHelpers);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000112 std::string SynthesizeBlockCall(CallExpr *Exp);
113 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
114 const char *FunName);
115
Steve Naroffd3f77902008-10-05 00:06:12 +0000116 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000117 void GetBlockCallExprs(Stmt *S);
Steve Naroffacba0f22008-10-04 23:47:37 +0000118 void GetBlockDeclRefExprs(Stmt *S);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000119
120 // We avoid calling Type::isBlockPointerType(), since it operates on the
121 // canonical type. We only care if the top-level type is a closure pointer.
122 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
123
124 // FIXME: This predicate seems like it would be useful to add to ASTContext.
125 bool isObjCType(QualType T) {
126 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
127 return false;
128
129 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
130
131 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
132 OCT == Context->getCanonicalType(Context->getObjCClassType()))
133 return true;
134
135 if (const PointerType *PT = OCT->getAsPointerType()) {
136 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
137 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
138 return true;
139 }
140 return false;
141 }
142 // ObjC rewrite methods.
143 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
144 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
145 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
146 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffca743602008-10-15 18:38:58 +0000147
Douglas Gregor72564e72009-02-26 23:50:07 +0000148 void RewriteFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroffca743602008-10-15 18:38:58 +0000149 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
150 void RewriteCastExpr(CastExpr *CE);
Steve Naroffeab5f632008-09-23 19:24:41 +0000151
Steve Naroffca743602008-10-15 18:38:58 +0000152 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000153 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000154};
155
156}
157
158static bool IsHeaderFile(const std::string &Filename) {
159 std::string::size_type DotPos = Filename.rfind('.');
160
161 if (DotPos == std::string::npos) {
162 // no file extension
163 return false;
164 }
165
166 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
167 // C header: .h
168 // C++ header: .hh or .H;
169 return Ext == "h" || Ext == "hh" || Ext == "H";
170}
171
Steve Naroff13188952008-09-18 14:10:13 +0000172RewriteBlocks::RewriteBlocks(std::string inFile, std::string outFile,
173 Diagnostic &D, const LangOptions &LOpts) :
174 Diags(D), LangOpts(LOpts) {
175 IsHeader = IsHeaderFile(inFile);
176 InFileName = inFile;
177 OutFileName = outFile;
178 CurFunctionDef = 0;
179 CurMethodDef = 0;
180 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
181 "rewriting failed");
Steve Naroff13188952008-09-18 14:10:13 +0000182}
183
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000184ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
Steve Naroff13188952008-09-18 14:10:13 +0000185 const std::string& OutFile,
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000186 Diagnostic &Diags,
187 const LangOptions &LangOpts) {
Steve Naroff13188952008-09-18 14:10:13 +0000188 return new RewriteBlocks(InFile, OutFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000189}
190
191void RewriteBlocks::Initialize(ASTContext &context) {
192 Context = &context;
193 SM = &Context->getSourceManager();
194
195 // Get the ID and start/end of the main file.
196 MainFileID = SM->getMainFileID();
197 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
198 MainFileStart = MainBuf->getBufferStart();
199 MainFileEnd = MainBuf->getBufferEnd();
200
201 Rewrite.setSourceMgr(Context->getSourceManager());
202
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000203 if (IsHeader)
204 Preamble = "#pragma once\n";
205 Preamble += "#ifndef BLOCK_IMPL\n";
206 Preamble += "#define BLOCK_IMPL\n";
207 Preamble += "struct __block_impl {\n";
208 Preamble += " void *isa;\n";
209 Preamble += " int Flags;\n";
210 Preamble += " int Size;\n";
211 Preamble += " void *FuncPtr;\n";
212 Preamble += "};\n";
213 Preamble += "enum {\n";
214 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
215 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
216 Preamble += "};\n";
217 if (LangOpts.Microsoft)
218 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
219 else
220 Preamble += "#define __OBJC_RW_EXTERN extern\n";
221 Preamble += "// Runtime copy/destroy helper functions\n";
222 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
223 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
224 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
225 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000226 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
227 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000228 Preamble += "#endif\n";
229
Chris Lattner2b2453a2009-01-17 06:22:33 +0000230 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000231 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000232}
233
234void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData,
235 unsigned StrLen)
236{
237 if (!Rewrite.InsertText(Loc, StrData, StrLen))
238 return;
239 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
240}
241
242void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength,
243 const char *NewStr, unsigned NewLength) {
244 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength))
245 return;
246 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
247}
248
249void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) {
250 bool haveBlockPtrs = false;
251 for (ObjCMethodDecl::param_iterator I = Method->param_begin(),
252 E = Method->param_end(); I != E; ++I)
253 if (isBlockPointerType((*I)->getType()))
254 haveBlockPtrs = true;
255
256 if (!haveBlockPtrs)
257 return;
258
259 // Do a fuzzy rewrite.
260 // We have 1 or more arguments that have closure pointers.
261 SourceLocation Loc = Method->getLocStart();
262 SourceLocation LocEnd = Method->getLocEnd();
263 const char *startBuf = SM->getCharacterData(Loc);
264 const char *endBuf = SM->getCharacterData(LocEnd);
265
266 const char *methodPtr = startBuf;
Steve Naroff8af6a452008-10-02 17:12:56 +0000267 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000268
269 while (*methodPtr++ && (methodPtr != endBuf)) {
270 switch (*methodPtr) {
271 case ':':
272 methodPtr++;
273 if (*methodPtr == '(') {
274 const char *scanType = ++methodPtr;
275 bool foundBlockPointer = false;
276 unsigned parenCount = 1;
277
278 while (parenCount) {
279 switch (*scanType) {
280 case '(':
281 parenCount++;
282 break;
283 case ')':
284 parenCount--;
285 break;
286 case '^':
287 foundBlockPointer = true;
288 break;
289 }
290 scanType++;
291 }
292 if (foundBlockPointer) {
293 // advance the location to startArgList.
294 Loc = Loc.getFileLocWithOffset(methodPtr-startBuf);
295 assert((Loc.isValid()) && "Invalid Loc");
296 ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size());
297
298 // Advance startBuf. Since the underlying buffer has changed,
299 // it's very important to advance startBuf (so we can correctly
300 // compute a relative Loc the next time around).
301 startBuf = methodPtr;
302 }
303 // Advance the method ptr to the end of the type.
304 methodPtr = scanType;
305 }
306 break;
307 }
308 }
309 return;
310}
311
312void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
313 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
314 E = ClassDecl->instmeth_end(); I != E; ++I)
315 RewriteMethodDecl(*I);
316 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
317 E = ClassDecl->classmeth_end(); I != E; ++I)
318 RewriteMethodDecl(*I);
319}
320
321void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
322 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
323 E = CatDecl->instmeth_end(); I != E; ++I)
324 RewriteMethodDecl(*I);
325 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
326 E = CatDecl->classmeth_end(); I != E; ++I)
327 RewriteMethodDecl(*I);
328}
329
330void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
331 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
332 E = PDecl->instmeth_end(); I != E; ++I)
333 RewriteMethodDecl(*I);
334 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
335 E = PDecl->classmeth_end(); I != E; ++I)
336 RewriteMethodDecl(*I);
337}
338
339//===----------------------------------------------------------------------===//
340// Top Level Driver Code
341//===----------------------------------------------------------------------===//
342
Chris Lattner682bf922009-03-29 16:50:03 +0000343void RewriteBlocks::HandleTopLevelSingleDecl(Decl *D) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000344 // Two cases: either the decl could be in the main file, or it could be in a
345 // #included file. If the former, rewrite it now. If the later, check to see
346 // if we rewrote the #include/#import.
347 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000348 Loc = SM->getInstantiationLoc(Loc);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000349
350 // If this is for a builtin, ignore it.
351 if (Loc.isInvalid()) return;
352
353 if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D))
354 RewriteInterfaceDecl(MD);
355 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D))
356 RewriteCategoryDecl(CD);
357 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
358 RewriteProtocolDecl(PD);
359
360 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner23f2c582009-01-25 22:02:19 +0000361 if (SM->isFromMainFile(Loc))
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000362 HandleDeclInMainFile(D);
363 return;
364}
365
366std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i,
367 const char *funcName,
368 std::string Tag) {
369 const FunctionType *AFT = CE->getFunctionType();
370 QualType RT = AFT->getResultType();
Steve Naroff48a8c612008-10-03 12:09:49 +0000371 std::string StructRef = "struct " + Tag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000372 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000373 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000374
Steve Naroff56ee6892008-10-08 17:01:13 +0000375 BlockDecl *BD = CE->getBlockDecl();
376
Douglas Gregor72564e72009-02-26 23:50:07 +0000377 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000378 S += "()";
Steve Naroff56ee6892008-10-08 17:01:13 +0000379 } else if (BD->param_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000380 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000381 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +0000382 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000383 assert(FT && "SynthesizeBlockFunc: No function proto");
384 S += '(';
385 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000386 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000387 std::string ParamStr;
Steve Naroff56ee6892008-10-08 17:01:13 +0000388 for (BlockDecl::param_iterator AI = BD->param_begin(),
389 E = BD->param_end(); AI != E; ++AI) {
390 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000391 ParamStr = (*AI)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000392 (*AI)->getType().getAsStringInternal(ParamStr);
393 S += ParamStr;
394 }
395 if (FT->isVariadic()) {
Steve Naroff56ee6892008-10-08 17:01:13 +0000396 if (!BD->param_empty()) S += ", ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000397 S += "...";
398 }
399 S += ')';
400 }
401 S += " {\n";
402
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000403 // Create local declarations to avoid rewriting all closure decl ref exprs.
404 // First, emit a declaration for all "by ref" decls.
405 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
406 E = BlockByRefDecls.end(); I != E; ++I) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000407 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000408 std::string Name = (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000409 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000410 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000411 }
412 // Next, emit a declaration for all "by copy" declarations.
413 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
414 E = BlockByCopyDecls.end(); I != E; ++I) {
415 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000416 std::string Name = (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000417 // Handle nested closure invocation. For example:
418 //
419 // void (^myImportedClosure)(void);
420 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
421 //
422 // void (^anotherClosure)(void);
423 // anotherClosure = ^(void) {
424 // myImportedClosure(); // import and invoke the closure
425 // };
426 //
427 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000428 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000429 else
430 (*I)->getType().getAsStringInternal(Name);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000431 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000432 }
Steve Naroff70f95502008-10-04 17:06:23 +0000433 std::string RewrittenStr = RewrittenBlockExprs[CE];
434 const char *cstr = RewrittenStr.c_str();
435 while (*cstr++ != '{') ;
436 S += cstr;
437 S += "\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000438 return S;
439}
440
Steve Naroff4e13b762008-10-03 20:28:15 +0000441std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
442 const char *funcName,
443 std::string Tag) {
444 std::string StructRef = "struct " + Tag;
445 std::string S = "static void __";
446
447 S += funcName;
448 S += "_block_copy_" + utostr(i);
449 S += "(" + StructRef;
450 S += "*dst, " + StructRef;
451 S += "*src) {";
452 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
453 E = ImportedBlockDecls.end(); I != E; ++I) {
454 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000455 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000456 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000457 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000458 S += ");}";
459 }
460 S += "\nstatic void __";
461 S += funcName;
462 S += "_block_dispose_" + utostr(i);
463 S += "(" + StructRef;
464 S += "*src) {";
465 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
466 E = ImportedBlockDecls.end(); I != E; ++I) {
467 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000468 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000469 S += ");";
470 }
471 S += "}\n";
472 return S;
473}
474
Steve Naroffacba0f22008-10-04 23:47:37 +0000475std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
476 bool hasCopyDisposeHelpers) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000477 std::string S = "struct " + Tag;
478 std::string Constructor = " " + Tag;
479
480 S += " {\n struct __block_impl impl;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000481
482 if (hasCopyDisposeHelpers)
483 S += " void *copy;\n void *dispose;\n";
484
Steve Naroff48a8c612008-10-03 12:09:49 +0000485 Constructor += "(void *fp";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000486
Steve Naroffacba0f22008-10-04 23:47:37 +0000487 if (hasCopyDisposeHelpers)
488 Constructor += ", void *copyHelp, void *disposeHelp";
489
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000490 if (BlockDeclRefs.size()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000491 // Output all "by copy" declarations.
492 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
493 E = BlockByCopyDecls.end(); I != E; ++I) {
494 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000495 std::string FieldName = (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000496 std::string ArgName = "_" + FieldName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000497 // Handle nested closure invocation. For example:
498 //
499 // void (^myImportedBlock)(void);
500 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
501 //
502 // void (^anotherBlock)(void);
503 // anotherBlock = ^(void) {
504 // myImportedBlock(); // import and invoke the closure
505 // };
506 //
Steve Naroff4e13b762008-10-03 20:28:15 +0000507 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000508 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000509 Constructor += ", void *" + ArgName;
510 } else {
511 (*I)->getType().getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000512 (*I)->getType().getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000513 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000514 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000515 S += FieldName + ";\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000516 }
517 // Output all "by ref" declarations.
518 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
519 E = BlockByRefDecls.end(); I != E; ++I) {
520 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000521 std::string FieldName = (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000522 std::string ArgName = "_" + FieldName;
523 // Handle nested closure invocation. For example:
524 //
525 // void (^myImportedBlock)(void);
526 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
527 //
528 // void (^anotherBlock)(void);
529 // anotherBlock = ^(void) {
530 // myImportedBlock(); // import and invoke the closure
531 // };
532 //
533 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000534 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000535 Constructor += ", void *" + ArgName;
536 } else {
537 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
Steve Naroff48a8c612008-10-03 12:09:49 +0000538 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
Steve Naroff4e13b762008-10-03 20:28:15 +0000539 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000540 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000541 S += FieldName + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000542 }
543 // Finish writing the constructor.
544 // FIXME: handle NSConcreteGlobalBlock.
545 Constructor += ", int flags=0) {\n";
Steve Naroff83ba14e2008-10-03 15:04:50 +0000546 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
Steve Naroff48a8c612008-10-03 12:09:49 +0000547 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
548
Steve Naroffacba0f22008-10-04 23:47:37 +0000549 if (hasCopyDisposeHelpers)
550 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
551
Steve Naroff48a8c612008-10-03 12:09:49 +0000552 // Initialize all "by copy" arguments.
553 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
554 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000555 std::string Name = (*I)->getNameAsString();
Steve Naroff48a8c612008-10-03 12:09:49 +0000556 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) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000566 std::string Name = (*I)->getNameAsString();
Steve Naroff48a8c612008-10-03 12:09:49 +0000567 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 Naroffacba0f22008-10-04 23:47:37 +0000580 if (hasCopyDisposeHelpers)
581 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000582 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000583 Constructor += " ";
584 Constructor += "}\n";
585 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000586 S += "};\n";
587 return S;
588}
589
590void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
591 const char *FunName) {
592 // Insert closures that were part of the function.
593 for (unsigned i = 0; i < Blocks.size(); i++) {
Steve Naroffacba0f22008-10-04 23:47:37 +0000594
Steve Naroffd3f77902008-10-05 00:06:12 +0000595 CollectBlockDeclRefInfo(Blocks[i]);
596
Steve Naroff48a8c612008-10-03 12:09:49 +0000597 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000598
Steve Naroffacba0f22008-10-04 23:47:37 +0000599 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
600 ImportedBlockDecls.size() > 0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000601
602 InsertText(FunLocStart, CI.c_str(), CI.size());
Steve Naroff4e13b762008-10-03 20:28:15 +0000603
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000604 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
605
606 InsertText(FunLocStart, CF.c_str(), CF.size());
607
Steve Naroff4e13b762008-10-03 20:28:15 +0000608 if (ImportedBlockDecls.size()) {
609 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
610 InsertText(FunLocStart, HF.c_str(), HF.size());
611 }
612
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000613 BlockDeclRefs.clear();
614 BlockByRefDecls.clear();
615 BlockByCopyDecls.clear();
616 BlockCallExprs.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000617 ImportedBlockDecls.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000618 }
619 Blocks.clear();
Steve Naroff8e9216d2008-10-04 17:10:02 +0000620 RewrittenBlockExprs.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000621}
622
623void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000624 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +0000625 const char *FuncName = FD->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000626
627 SynthesizeBlockLiterals(FunLocStart, FuncName);
628}
629
630void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
631 SourceLocation FunLocStart = MD->getLocStart();
Chris Lattner077bf5e2008-11-24 03:33:13 +0000632 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000633 // Convert colons to underscores.
634 std::string::size_type loc = 0;
635 while ((loc = FuncName.find(":", loc)) != std::string::npos)
636 FuncName.replace(loc, 1, "_");
637
638 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
639}
640
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000641void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
642 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
643 CI != E; ++CI)
Steve Naroff84a969f2008-10-08 17:31:13 +0000644 if (*CI) {
645 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
646 GetBlockDeclRefExprs(CBE->getBody());
647 else
648 GetBlockDeclRefExprs(*CI);
649 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000650 // Handle specific things.
651 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
652 // FIXME: Handle enums.
653 if (!isa<FunctionDecl>(CDRE->getDecl()))
654 BlockDeclRefs.push_back(CDRE);
655 return;
656}
657
658void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
659 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
660 CI != E; ++CI)
Steve Naroff84a969f2008-10-08 17:31:13 +0000661 if (*CI) {
662 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
663 GetBlockCallExprs(CBE->getBody());
664 else
665 GetBlockCallExprs(*CI);
666 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000667
668 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff4e13b762008-10-03 20:28:15 +0000669 if (CE->getCallee()->getType()->isBlockPointerType()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000670 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
Steve Naroff4e13b762008-10-03 20:28:15 +0000671 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000672 }
673 return;
674}
675
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000676std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
677 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000678 const char *closureName = 0;
679 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000680
681 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000682 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000683 CPT = DRE->getType()->getAsBlockPointerType();
684 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000685 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000686 CPT = CDRE->getType()->getAsBlockPointerType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000687 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000688 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000689 CPT = MExpr->getType()->getAsBlockPointerType();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000690 } else {
691 assert(1 && "RewriteBlockClass: Bad type");
692 }
693 assert(CPT && "RewriteBlockClass: Bad type");
694 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
695 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +0000696 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000697 // FTP will be null for closures that don't take arguments.
698
699 // Build a closure call - start with a paren expr to enforce precedence.
700 std::string BlockCall = "(";
701
702 // Synthesize the cast.
703 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000704 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000705 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000706 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000707 E = FTP->arg_type_end(); I && (I != E); ++I)
708 BlockCall += ", " + (*I).getAsString();
709 }
710 BlockCall += "))"; // close the argument list and paren expression.
711
Steve Naroff83ba14e2008-10-03 15:04:50 +0000712 // Invoke the closure. We need to cast it since the declaration type is
713 // bogus (it's a function pointer type)
714 BlockCall += "((struct __block_impl *)";
715 std::string closureExprBufStr;
716 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
717 Exp->getCallee()->printPretty(closureExprBuf);
718 BlockCall += closureExprBuf.str();
719 BlockCall += ")->FuncPtr)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000720
721 // Add the arguments.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000722 BlockCall += "((struct __block_impl *)";
Steve Naroffb65a4f12008-10-04 17:45:51 +0000723 BlockCall += closureExprBuf.str();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000724 for (CallExpr::arg_iterator I = Exp->arg_begin(),
725 E = Exp->arg_end(); I != E; ++I) {
726 std::string syncExprBufS;
727 llvm::raw_string_ostream Buf(syncExprBufS);
728 (*I)->printPretty(Buf);
729 BlockCall += ", " + Buf.str();
730 }
731 return BlockCall;
732}
733
734void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
735 std::string BlockCall = SynthesizeBlockCall(Exp);
736
737 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
738 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
739
740 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
741 BlockCall.c_str(), BlockCall.size());
742}
743
Steve Naroff5e52b172008-10-04 18:52:47 +0000744void RewriteBlocks::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
745 // FIXME: Add more elaborate code generation required by the ABI.
746 InsertText(BDRE->getLocStart(), "*", 1);
747}
748
Steve Naroffca743602008-10-15 18:38:58 +0000749void RewriteBlocks::RewriteCastExpr(CastExpr *CE) {
750 SourceLocation LocStart = CE->getLocStart();
751 SourceLocation LocEnd = CE->getLocEnd();
752
Steve Naroff8f6ce572008-11-03 11:20:24 +0000753 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
754 return;
755
Steve Naroffca743602008-10-15 18:38:58 +0000756 const char *startBuf = SM->getCharacterData(LocStart);
757 const char *endBuf = SM->getCharacterData(LocEnd);
758
759 // advance the location to startArgList.
760 const char *argPtr = startBuf;
761
762 while (*argPtr++ && (argPtr < endBuf)) {
763 switch (*argPtr) {
764 case '^':
765 // Replace the '^' with '*'.
766 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
767 ReplaceText(LocStart, 1, "*", 1);
768 break;
769 }
770 }
771 return;
772}
773
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000774void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
775 SourceLocation DeclLoc = FD->getLocation();
Steve Naroffe0109a52008-10-10 15:33:34 +0000776 unsigned parenCount = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000777
778 // We have 1 or more arguments that have closure pointers.
779 const char *startBuf = SM->getCharacterData(DeclLoc);
780 const char *startArgList = strchr(startBuf, '(');
781
782 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
783
784 parenCount++;
785 // advance the location to startArgList.
Steve Naroffe0109a52008-10-10 15:33:34 +0000786 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000787 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
788
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000789 const char *argPtr = startArgList;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000790
791 while (*argPtr++ && parenCount) {
792 switch (*argPtr) {
793 case '^':
Steve Naroffe0109a52008-10-10 15:33:34 +0000794 // Replace the '^' with '*'.
795 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
796 ReplaceText(DeclLoc, 1, "*", 1);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000797 break;
798 case '(':
799 parenCount++;
800 break;
801 case ')':
802 parenCount--;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000803 break;
804 }
805 }
806 return;
807}
808
Steve Naroffca743602008-10-15 18:38:58 +0000809bool RewriteBlocks::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000810 const FunctionProtoType *FTP;
Steve Naroffca743602008-10-15 18:38:58 +0000811 const PointerType *PT = QT->getAsPointerType();
812 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000813 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroffca743602008-10-15 18:38:58 +0000814 } else {
815 const BlockPointerType *BPT = QT->getAsBlockPointerType();
816 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +0000817 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroffca743602008-10-15 18:38:58 +0000818 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000819 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000820 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffeab5f632008-09-23 19:24:41 +0000821 E = FTP->arg_type_end(); I != E; ++I)
822 if (isBlockPointerType(*I))
823 return true;
824 }
825 return false;
826}
827
828void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000829 const char *&LParen, const char *&RParen) {
830 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000831 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
832
833 LParen = argPtr; // output the start.
834 argPtr++; // skip past the left paren.
835 unsigned parenCount = 1;
836
837 while (*argPtr && parenCount) {
838 switch (*argPtr) {
839 case '(': parenCount++; break;
840 case ')': parenCount--; break;
841 default: break;
842 }
843 if (parenCount) argPtr++;
844 }
845 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
846 RParen = argPtr; // output the end
847}
848
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000849void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000850 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
851 RewriteBlockPointerFunctionArgs(FD);
852 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000853 }
854 // Handle Variables and Typedefs.
855 SourceLocation DeclLoc = ND->getLocation();
856 QualType DeclT;
857 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
858 DeclT = VD->getType();
859 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
860 DeclT = TDD->getUnderlyingType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000861 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
862 DeclT = FD->getType();
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000863 else
864 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000865
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000866 const char *startBuf = SM->getCharacterData(DeclLoc);
867 const char *endBuf = startBuf;
868 // scan backward (from the decl location) for the end of the previous decl.
869 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
870 startBuf--;
Steve Naroffca743602008-10-15 18:38:58 +0000871
872 // *startBuf != '^' if we are dealing with a pointer to function that
873 // may take block argument types (which will be handled below).
874 if (*startBuf == '^') {
875 // Replace the '^' with '*', computing a negative offset.
876 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
877 ReplaceText(DeclLoc, 1, "*", 1);
878 }
879 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000880 // Replace the '^' with '*' for arguments.
881 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000882 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000883 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000884 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
885 while (argListBegin < argListEnd) {
886 if (*argListBegin == '^') {
887 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
888 ReplaceText(CaretLoc, 1, "*", 1);
889 }
890 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000891 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000892 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000893 return;
894}
895
Steve Naroffd3f77902008-10-05 00:06:12 +0000896void RewriteBlocks::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000897 // Add initializers for any closure decl refs.
Steve Naroff84a969f2008-10-08 17:31:13 +0000898 GetBlockDeclRefExprs(Exp->getBody());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000899 if (BlockDeclRefs.size()) {
900 // Unique all "by copy" declarations.
901 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
902 if (!BlockDeclRefs[i]->isByRef())
903 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
904 // Unique all "by ref" declarations.
905 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
906 if (BlockDeclRefs[i]->isByRef()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000907 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
908 }
Steve Naroffacba0f22008-10-04 23:47:37 +0000909 // Find any imported blocks...they will need special attention.
910 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
911 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
912 GetBlockCallExprs(Blocks[i]);
913 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
914 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000915 }
Steve Naroffd3f77902008-10-05 00:06:12 +0000916}
917
918std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
919 Blocks.push_back(Exp);
920
921 CollectBlockDeclRefInfo(Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000922 std::string FuncName;
923
924 if (CurFunctionDef)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000925 FuncName = std::string(CurFunctionDef->getNameAsString());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000926 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000927 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000928 // Convert colons to underscores.
929 std::string::size_type loc = 0;
930 while ((loc = FuncName.find(":", loc)) != std::string::npos)
931 FuncName.replace(loc, 1, "_");
Steve Naroff39622b92008-10-03 15:38:09 +0000932 } else if (VD)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000933 FuncName = std::string(VD->getNameAsString());
Steve Naroff39622b92008-10-03 15:38:09 +0000934
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000935 std::string BlockNumber = utostr(Blocks.size()-1);
936
Steve Naroff83ba14e2008-10-03 15:04:50 +0000937 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000938 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000939
Steve Naroff83ba14e2008-10-03 15:04:50 +0000940 std::string FunkTypeStr;
941
942 // Get a pointer to the function type so we can cast appropriately.
943 Context->getPointerType(QualType(Exp->getFunctionType(),0)).getAsStringInternal(FunkTypeStr);
944
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000945 // Rewrite the closure block with a compound literal. The first cast is
946 // to prevent warnings from the C compiler.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000947 std::string Init = "(" + FunkTypeStr;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000948
Steve Naroff83ba14e2008-10-03 15:04:50 +0000949 Init += ")&" + Tag;
950
951 // Initialize the block function.
952 Init += "((void*)" + Func;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000953
Steve Naroffacba0f22008-10-04 23:47:37 +0000954 if (ImportedBlockDecls.size()) {
955 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
956 Init += ",(void*)" + Buf;
957 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
958 Init += ",(void*)" + Buf;
959 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000960 // Add initializers for any closure decl refs.
961 if (BlockDeclRefs.size()) {
962 // Output all "by copy" declarations.
963 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
964 E = BlockByCopyDecls.end(); I != E; ++I) {
965 Init += ",";
966 if (isObjCType((*I)->getType())) {
967 Init += "[[";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000968 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000969 Init += " retain] autorelease]";
Steve Naroff4e13b762008-10-03 20:28:15 +0000970 } else if (isBlockPointerType((*I)->getType())) {
971 Init += "(void *)";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000972 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000973 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000974 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000975 }
976 }
977 // Output all "by ref" declarations.
978 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
979 E = BlockByRefDecls.end(); I != E; ++I) {
980 Init += ",&";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000981 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000982 }
983 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000984 Init += ")";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000985 BlockDeclRefs.clear();
986 BlockByRefDecls.clear();
987 BlockByCopyDecls.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000988 ImportedBlockDecls.clear();
989
Steve Naroff70f95502008-10-04 17:06:23 +0000990 return Init;
991}
992
993//===----------------------------------------------------------------------===//
994// Function Body / Expression rewriting
995//===----------------------------------------------------------------------===//
996
997Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
998 // Start by rewriting all children.
999 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1000 CI != E; ++CI)
1001 if (*CI) {
1002 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
Steve Naroff84a969f2008-10-08 17:31:13 +00001003 Stmt *newStmt = RewriteFunctionBody(CBE->getBody());
Steve Naroff70f95502008-10-04 17:06:23 +00001004 if (newStmt)
1005 *CI = newStmt;
1006
1007 // We've just rewritten the block body in place.
1008 // Now we snarf the rewritten text and stash it away for later use.
1009 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1010 RewrittenBlockExprs[CBE] = S;
1011 std::string Init = SynthesizeBlockInitExpr(CBE);
1012 // Do the rewrite, using S.size() which contains the rewritten size.
1013 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1014 } else {
1015 Stmt *newStmt = RewriteFunctionBody(*CI);
1016 if (newStmt)
1017 *CI = newStmt;
1018 }
1019 }
1020 // Handle specific things.
1021 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1022 if (CE->getCallee()->getType()->isBlockPointerType())
1023 RewriteBlockCall(CE);
1024 }
Steve Naroffca743602008-10-15 18:38:58 +00001025 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
1026 RewriteCastExpr(CE);
1027 }
Steve Naroff70f95502008-10-04 17:06:23 +00001028 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001029 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1030 DI != DE; ++DI) {
1031
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001032 Decl *SD = *DI;
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001033 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1034 if (isBlockPointerType(ND->getType()))
1035 RewriteBlockPointerDecl(ND);
Steve Naroffca743602008-10-15 18:38:58 +00001036 else if (ND->getType()->isFunctionPointerType())
1037 CheckFunctionPointerDecl(ND->getType(), ND);
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001038 }
1039 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1040 if (isBlockPointerType(TD->getUnderlyingType()))
1041 RewriteBlockPointerDecl(TD);
Steve Naroffca743602008-10-15 18:38:58 +00001042 else if (TD->getUnderlyingType()->isFunctionPointerType())
1043 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001044 }
Steve Naroff70f95502008-10-04 17:06:23 +00001045 }
1046 }
Steve Naroff5e52b172008-10-04 18:52:47 +00001047 // Handle specific things.
1048 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1049 if (BDRE->isByRef())
1050 RewriteBlockDeclRefExpr(BDRE);
1051 }
Steve Naroff70f95502008-10-04 17:06:23 +00001052 // Return this stmt unmodified.
1053 return S;
1054}
1055
Douglas Gregor72564e72009-02-26 23:50:07 +00001056void RewriteBlocks::RewriteFunctionProtoType(QualType funcType, NamedDecl *D) {
1057 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
1058 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroffca743602008-10-15 18:38:58 +00001059 E = fproto->arg_type_end(); I && (I != E); ++I)
1060 if (isBlockPointerType(*I)) {
1061 // All the args are checked/rewritten. Don't call twice!
1062 RewriteBlockPointerDecl(D);
1063 break;
1064 }
1065 }
1066}
1067
1068void RewriteBlocks::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
1069 const PointerType *PT = funcType->getAsPointerType();
1070 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +00001071 RewriteFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroffca743602008-10-15 18:38:58 +00001072}
1073
Steve Naroff70f95502008-10-04 17:06:23 +00001074/// HandleDeclInMainFile - This is called for each top-level decl defined in the
1075/// main file of the input.
1076void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
1077 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff70f95502008-10-04 17:06:23 +00001078 // Since function prototypes don't have ParmDecl's, we check the function
1079 // prototype. This enables us to rewrite function declarations and
1080 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00001081 RewriteFunctionProtoType(FD->getType(), FD);
Steve Naroff70f95502008-10-04 17:06:23 +00001082
Ted Kremenekeaab2062009-03-12 18:33:24 +00001083 if (CompoundStmt *Body = FD->getBody()) {
Steve Naroff70f95502008-10-04 17:06:23 +00001084 CurFunctionDef = FD;
Ted Kremenekeaab2062009-03-12 18:33:24 +00001085 FD->setBody(cast_or_null<CompoundStmt>(RewriteFunctionBody(Body)));
Steve Naroff70f95502008-10-04 17:06:23 +00001086 // This synthesizes and inserts the block "impl" struct, invoke function,
1087 // and any copy/dispose helper functions.
1088 InsertBlockLiteralsWithinFunction(FD);
1089 CurFunctionDef = 0;
1090 }
1091 return;
1092 }
1093 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1094 RewriteMethodDecl(MD);
1095 if (Stmt *Body = MD->getBody()) {
1096 CurMethodDef = MD;
1097 RewriteFunctionBody(Body);
1098 InsertBlockLiteralsWithinMethod(MD);
1099 CurMethodDef = 0;
1100 }
1101 }
1102 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1103 if (isBlockPointerType(VD->getType())) {
1104 RewriteBlockPointerDecl(VD);
1105 if (VD->getInit()) {
1106 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
Steve Naroff84a969f2008-10-08 17:31:13 +00001107 RewriteFunctionBody(CBE->getBody());
Steve Naroff70f95502008-10-04 17:06:23 +00001108
1109 // We've just rewritten the block body in place.
1110 // Now we snarf the rewritten text and stash it away for later use.
1111 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1112 RewrittenBlockExprs[CBE] = S;
1113 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
1114 // Do the rewrite, using S.size() which contains the rewritten size.
1115 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001116 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00001117 VD->getNameAsCString());
Steve Naroffca743602008-10-15 18:38:58 +00001118 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
1119 RewriteCastExpr(CE);
1120 }
1121 }
1122 } else if (VD->getType()->isFunctionPointerType()) {
1123 CheckFunctionPointerDecl(VD->getType(), VD);
1124 if (VD->getInit()) {
1125 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
1126 RewriteCastExpr(CE);
Steve Naroff70f95502008-10-04 17:06:23 +00001127 }
1128 }
1129 }
1130 return;
1131 }
1132 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1133 if (isBlockPointerType(TD->getUnderlyingType()))
1134 RewriteBlockPointerDecl(TD);
Steve Naroffca743602008-10-15 18:38:58 +00001135 else if (TD->getUnderlyingType()->isFunctionPointerType())
1136 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff70f95502008-10-04 17:06:23 +00001137 return;
1138 }
1139 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1140 if (RD->isDefinition()) {
Douglas Gregora4c46df2008-12-11 17:59:21 +00001141 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Naroff70f95502008-10-04 17:06:23 +00001142 e = RD->field_end(); i != e; ++i) {
1143 FieldDecl *FD = *i;
1144 if (isBlockPointerType(FD->getType()))
1145 RewriteBlockPointerDecl(FD);
1146 }
1147 }
1148 return;
1149 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001150}