blob: 4245856efa537a51128934c08348bdec2449e430 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahaniane3891582010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner0bd1c972007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000061
Chris Lattnerc6d91c02007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000068
Ted Kremenek1b0ea822008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffce8e8862008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000083
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000094
Steve Naroffa397efd2007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000098
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +0000101
Steve Naroff7fa2f042007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Steve Naroffd9803712009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000109
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Narofff9e7c902008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000118
Steve Naroff00a31762008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000125
Steve Naroff677ab3a2008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
129 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
130
131 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
132
Steve Naroff4588d0f2008-12-04 16:24:46 +0000133 // This maps a property to it's assignment statement.
134 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000135 // This maps a property to it's synthesied message expression.
136 // This allows us to rewrite chained getters (e.g. o.a.b.c).
137 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000138
Steve Naroff22216db2008-12-04 23:50:32 +0000139 // This maps an original source AST to it's rewritten form. This allows
140 // us to avoid rewriting the same node twice (which is very uncommon).
141 // This is needed to support some of the exotic property rewriting.
142 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000143
Steve Naroff677ab3a2008-10-27 17:20:55 +0000144 FunctionDecl *CurFunctionDef;
Steve Naroffd8907b72008-10-29 18:15:37 +0000145 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000146
Steve Naroff08628db2008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000148
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000149 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000150 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000151 virtual void Initialize(ASTContext &context);
152
Chris Lattner3c799d72007-10-24 17:06:59 +0000153 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000154 virtual void HandleTopLevelDecl(DeclGroupRef D) {
155 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
156 HandleTopLevelSingleDecl(*I);
157 }
158 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000159 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000160 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000161 Diagnostic &D, const LangOptions &LOpts,
162 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000163
164 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000165
Chris Lattnercf169832009-03-28 04:11:33 +0000166 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000167
Chris Lattner2e0d2602008-01-31 19:37:57 +0000168 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000169 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000170
Steve Naroff22216db2008-12-04 23:50:32 +0000171 if (ReplacingStmt)
172 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000173
Steve Naroff08628db2008-12-09 12:56:34 +0000174 if (DisableReplaceStmt)
175 return; // Used when rewriting the assignment of a property setter.
176
Steve Naroff22216db2008-12-04 23:50:32 +0000177 // If replacement succeeded or warning disabled return with no warning.
178 if (!Rewrite.ReplaceStmt(Old, New)) {
179 ReplacedNodes[Old] = New;
180 return;
181 }
182 if (SilenceRewriteMacroWarning)
183 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000184 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
185 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000186 }
Steve Naroff08628db2008-12-09 12:56:34 +0000187
188 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
189 // Measaure the old text.
190 int Size = Rewrite.getRangeSize(SrcRange);
191 if (Size == -1) {
192 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
193 << Old->getSourceRange();
194 return;
195 }
196 // Get the new text.
197 std::string SStr;
198 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000199 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000200 const std::string &Str = S.str();
201
202 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000203 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000204 ReplacedNodes[Old] = New;
205 return;
206 }
207 if (SilenceRewriteMacroWarning)
208 return;
209 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
210 << Old->getSourceRange();
211 }
212
Steve Naroff00a31762008-03-27 22:29:16 +0000213 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
214 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000215 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000216 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
217 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000218 SilenceRewriteMacroWarning)
219 return;
Mike Stump11289f42009-09-09 15:08:12 +0000220
Chris Lattner1780a852008-01-31 19:42:41 +0000221 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner9cc55f52008-01-31 19:51:04 +0000224 void RemoveText(SourceLocation Loc, unsigned StrLen) {
225 // If removal succeeded or warning disabled return with no warning.
226 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
227 return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattner9cc55f52008-01-31 19:51:04 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000231
Chris Lattner9cc55f52008-01-31 19:51:04 +0000232 void ReplaceText(SourceLocation Start, unsigned OrigLength,
233 const char *NewStr, unsigned NewLength) {
234 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000235 if (!Rewrite.ReplaceText(Start, OrigLength,
236 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000237 SilenceRewriteMacroWarning)
238 return;
Mike Stump11289f42009-09-09 15:08:12 +0000239
Chris Lattner9cc55f52008-01-31 19:51:04 +0000240 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
241 }
Mike Stump11289f42009-09-09 15:08:12 +0000242
Chris Lattner3c799d72007-10-24 17:06:59 +0000243 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000244 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000245 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000246 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000247 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000248 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
249 ObjCImplementationDecl *IMD,
250 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000251 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000252 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000253 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
254 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
255 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
256 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
257 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000258 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000259 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000260 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000261 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000262 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000263 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000264 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000265 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000266 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000267
Chris Lattner3c799d72007-10-24 17:06:59 +0000268 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000269 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000270 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000271
Steve Naroff1042ff32008-12-08 16:43:47 +0000272 Stmt *CurrentBody;
273 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000274
Chris Lattner69534692007-10-24 16:57:36 +0000275 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000276 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000277 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000278 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000279 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000280 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000281 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000282 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000283 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000284 void WarnAboutReturnGotoStmts(Stmt *S);
285 void HasReturnStmts(Stmt *S, bool &hasReturns);
286 void RewriteTryReturnStmts(Stmt *S);
287 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000288 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000289 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000290 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
291 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
292 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000293 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
294 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000295 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000296 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000297 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000298 Stmt *RewriteBreakStmt(BreakStmt *S);
299 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000300 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000301
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000302 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000303 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000304 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000305 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000306 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000307 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000308 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000309 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000310 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000311
Chris Lattner3c799d72007-10-24 17:06:59 +0000312 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000313 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000314 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000315
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000316 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000317 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000319 template<typename MethodIterator>
320 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
321 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000322 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000323 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000324 const char *ClassName,
325 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000326
Steve Naroffd9803712009-04-29 16:37:50 +0000327 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
328 const char *prefix,
329 const char *ClassName,
330 std::string &Result);
331 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000332 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000333 const char *ClassName,
334 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000335 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000336 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000337 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
338 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000339 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000340 void RewriteImplementations();
341 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000342
Steve Naroff677ab3a2008-10-27 17:20:55 +0000343 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000344 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000345 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000346
Steve Naroff677ab3a2008-10-27 17:20:55 +0000347 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
348 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000349
350 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000351 void RewriteBlockCall(CallExpr *Exp);
352 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000353 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000354 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000355 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000357
358 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000359 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000360 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000362 std::string SynthesizeBlockImpl(BlockExpr *CE,
363 std::string Tag, std::string Desc);
364 std::string SynthesizeBlockDescriptor(std::string DescTag,
365 std::string ImplTag,
366 int i, const char *funcName,
367 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000368 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000369 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
370 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000371 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Steve Naroff677ab3a2008-10-27 17:20:55 +0000373 void CollectBlockDeclRefInfo(BlockExpr *Exp);
374 void GetBlockCallExprs(Stmt *S);
375 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Steve Naroff677ab3a2008-10-27 17:20:55 +0000377 // We avoid calling Type::isBlockPointerType(), since it operates on the
378 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000379 bool isTopLevelBlockPointerType(QualType T) {
380 return isa<BlockPointerType>(T);
381 }
Mike Stump11289f42009-09-09 15:08:12 +0000382
Steve Naroff677ab3a2008-10-27 17:20:55 +0000383 // FIXME: This predicate seems like it would be useful to add to ASTContext.
384 bool isObjCType(QualType T) {
385 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
386 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000387
Steve Naroff677ab3a2008-10-27 17:20:55 +0000388 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000389
Steve Naroff677ab3a2008-10-27 17:20:55 +0000390 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
391 OCT == Context->getCanonicalType(Context->getObjCClassType()))
392 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000393
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000394 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000395 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000396 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000397 return true;
398 }
399 return false;
400 }
401 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000402 void GetExtentOfArgList(const char *Name, const char *&LParen,
403 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000404 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000405
Steve Narofff4b992a2008-10-28 20:29:00 +0000406 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000407 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000408
Steve Naroffd9803712009-04-29 16:37:50 +0000409 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000410 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000411 if (From[i] == '"')
412 To += "\\\"";
413 else
414 To += From[i];
415 }
416 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000417 };
418}
419
Mike Stump11289f42009-09-09 15:08:12 +0000420void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
421 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000422 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000423 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000424 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000425 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000426 // All the args are checked/rewritten. Don't call twice!
427 RewriteBlockPointerDecl(D);
428 break;
429 }
430 }
431}
432
433void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000434 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000435 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000436 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000437}
438
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000439static bool IsHeaderFile(const std::string &Filename) {
440 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000441
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000442 if (DotPos == std::string::npos) {
443 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000444 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000445 }
Mike Stump11289f42009-09-09 15:08:12 +0000446
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000447 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
448 // C header: .h
449 // C++ header: .hh or .H;
450 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000451}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000452
Eli Friedman94cf21e2009-05-18 22:20:00 +0000453RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000454 Diagnostic &D, const LangOptions &LOpts,
455 bool silenceMacroWarn)
456 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
457 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000458 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000459 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000460 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000461 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000462 "rewriter doesn't support user-specified control flow semantics "
463 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000464}
465
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000466ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
467 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000468 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000469 const LangOptions &LOpts,
470 bool SilenceRewriteMacroWarning) {
471 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000472}
Chris Lattnere99c8322007-10-11 00:43:27 +0000473
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000474void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000475 Context = &context;
476 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000477 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000478 MsgSendFunctionDecl = 0;
479 MsgSendSuperFunctionDecl = 0;
480 MsgSendStretFunctionDecl = 0;
481 MsgSendSuperStretFunctionDecl = 0;
482 MsgSendFpretFunctionDecl = 0;
483 GetClassFunctionDecl = 0;
484 GetMetaClassFunctionDecl = 0;
485 SelGetUidFunctionDecl = 0;
486 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000487 ConstantStringClassReference = 0;
488 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000489 CurMethodDef = 0;
490 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000491 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000492 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000493 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000494 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000495 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000496 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000497 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000498 PropParentMap = 0;
499 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000500 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000501 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000502
Chris Lattner187f6262008-01-31 19:38:44 +0000503 // Get the ID and start/end of the main file.
504 MainFileID = SM->getMainFileID();
505 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
506 MainFileStart = MainBuf->getBufferStart();
507 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattner184e65d2009-04-14 23:22:57 +0000509 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000510
Chris Lattner187f6262008-01-31 19:38:44 +0000511 // declaring objc_selector outside the parameter list removes a silly
512 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000513 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000514 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000515 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000516 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000517 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000518 if (LangOpts.Microsoft) {
519 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000520 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
521 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000522 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000523 }
Steve Naroff00a31762008-03-27 22:29:16 +0000524 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000525 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
526 Preamble += "typedef struct objc_object Protocol;\n";
527 Preamble += "#define _REWRITER_typedef_Protocol\n";
528 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000529 if (LangOpts.Microsoft) {
530 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
531 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
532 } else
533 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
534 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000535 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000537 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000538 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000539 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000540 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000541 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000542 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000543 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000544 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000545 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000546 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000547 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000548 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
549 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
550 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
551 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
552 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000553 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000554 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000555 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
556 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
557 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000558 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
559 Preamble += "struct __objcFastEnumerationState {\n\t";
560 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000561 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000562 Preamble += "unsigned long *mutationsPtr;\n\t";
563 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000565 Preamble += "#define __FASTENUMERATIONSTATE\n";
566 Preamble += "#endif\n";
567 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
568 Preamble += "struct __NSConstantStringImpl {\n";
569 Preamble += " int *isa;\n";
570 Preamble += " int flags;\n";
571 Preamble += " char *str;\n";
572 Preamble += " long length;\n";
573 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000574 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
575 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
576 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000577 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000578 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000579 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
580 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000581 // Blocks preamble.
582 Preamble += "#ifndef BLOCK_IMPL\n";
583 Preamble += "#define BLOCK_IMPL\n";
584 Preamble += "struct __block_impl {\n";
585 Preamble += " void *isa;\n";
586 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000587 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000588 Preamble += " void *FuncPtr;\n";
589 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000590 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000591 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000592 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
593 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
594 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
595 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
596 Preamble += "#else\n";
Steve Naroff7bf01ea2010-01-05 18:09:31 +0000597 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
598 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000599 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
600 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
601 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000602 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000603 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000604 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
605 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000606 Preamble += "#define __attribute__(X)\n";
607 }
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000608 else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000609 Preamble += "#define __block\n";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +0000610 Preamble += "#define __weak\n";
611 }
Chris Lattner187f6262008-01-31 19:38:44 +0000612}
613
614
Chris Lattner3c799d72007-10-24 17:06:59 +0000615//===----------------------------------------------------------------------===//
616// Top Level Driver Code
617//===----------------------------------------------------------------------===//
618
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000619void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000620 // Two cases: either the decl could be in the main file, or it could be in a
621 // #included file. If the former, rewrite it now. If the later, check to see
622 // if we rewrote the #include/#import.
623 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000624 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000625
Chris Lattner0bd1c972007-10-16 21:07:07 +0000626 // If this is for a builtin, ignore it.
627 if (Loc.isInvalid()) return;
628
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000629 // Look for built-in declarations that we need to refer during the rewrite.
630 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000631 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000632 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000633 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000634 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000635 ConstantStringClassReference = FVD;
636 return;
637 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000638 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000639 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000640 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000641 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000642 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000643 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000644 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000645 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000646 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000647 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
648 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000649 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
650 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000651 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000652 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000653 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000654 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000655 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000656 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000657}
658
Chris Lattner3c799d72007-10-24 17:06:59 +0000659//===----------------------------------------------------------------------===//
660// Syntactic (non-AST) Rewriting Code
661//===----------------------------------------------------------------------===//
662
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000663void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000664 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000665 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
666 const char *MainBufStart = MainBuf.first;
667 const char *MainBufEnd = MainBuf.second;
668 size_t ImportLen = strlen("import");
669 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000670
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000671 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000672 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
673 if (*BufPtr == '#') {
674 if (++BufPtr == MainBufEnd)
675 return;
676 while (*BufPtr == ' ' || *BufPtr == '\t')
677 if (++BufPtr == MainBufEnd)
678 return;
679 if (!strncmp(BufPtr, "import", ImportLen)) {
680 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000681 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000682 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000683 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000684 BufPtr += ImportLen;
685 }
686 }
687 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000688}
689
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000690void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000691 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
692 const char *MainBufStart = MainBuf.first;
693 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner3c799d72007-10-24 17:06:59 +0000695 // Loop over the whole file, looking for tabs.
696 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
697 if (*BufPtr != '\t')
698 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner3c799d72007-10-24 17:06:59 +0000700 // Okay, we found a tab. This tab will turn into at least one character,
701 // but it depends on which 'virtual column' it is in. Compute that now.
702 unsigned VCol = 0;
703 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
704 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
705 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000706
Chris Lattner3c799d72007-10-24 17:06:59 +0000707 // Okay, now that we know the virtual column, we know how many spaces to
708 // insert. We assume 8-character tab-stops.
709 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattner3c799d72007-10-24 17:06:59 +0000711 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000712 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
713 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000714
Chris Lattner3c799d72007-10-24 17:06:59 +0000715 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000716 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000717 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000718}
719
Steve Naroff9af94912008-12-02 15:48:25 +0000720static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
721 ObjCIvarDecl *OID) {
722 std::string S;
723 S = "((struct ";
724 S += ClassDecl->getIdentifier()->getName();
725 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000726 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000727 return S;
728}
729
Steve Naroffc038b3a2008-12-02 17:36:43 +0000730void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
731 ObjCImplementationDecl *IMD,
732 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000733 SourceLocation startLoc = PID->getLocStart();
734 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000735 const char *startBuf = SM->getCharacterData(startLoc);
736 assert((*startBuf == '@') && "bogus @synthesize location");
737 const char *semiBuf = strchr(startBuf, ';');
738 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000739 SourceLocation onePastSemiLoc =
740 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000741
742 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
743 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000744
Steve Naroff9af94912008-12-02 15:48:25 +0000745 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000746 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000747 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000748 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000749
Steve Naroff003d00e2008-12-02 16:05:55 +0000750 if (!OID)
751 return;
Mike Stump11289f42009-09-09 15:08:12 +0000752
Steve Naroff003d00e2008-12-02 16:05:55 +0000753 std::string Getr;
754 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
755 Getr += "{ ";
756 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000757 // FIXME: deal with code generation implications for various property
758 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000759 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000760 Getr += "return " + getIvarAccessString(ClassDecl, OID);
761 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000762 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000763 if (PD->isReadOnly())
764 return;
Mike Stump11289f42009-09-09 15:08:12 +0000765
Steve Naroff9af94912008-12-02 15:48:25 +0000766 // Generate the 'setter' function.
767 std::string Setr;
768 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000769 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000770 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000771 // FIXME: deal with code generation implications for various property
772 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000773 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000774 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000775 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000776 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000777 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000778}
Chris Lattner16a0de42007-10-11 18:38:32 +0000779
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000780void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000781 // Get the start location and compute the semi location.
782 SourceLocation startLoc = ClassDecl->getLocation();
783 const char *startBuf = SM->getCharacterData(startLoc);
784 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000785
Chris Lattner3c799d72007-10-24 17:06:59 +0000786 // Translate to typedef's that forward reference structs with the same name
787 // as the class. As a convenience, we include the original declaration
788 // as a comment.
789 std::string typedefString;
790 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000791 typedefString.append(startBuf, semiPtr-startBuf+1);
792 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000793 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
794 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000795 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000796 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000797 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000798 typedefString += "\n";
799 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000800 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000801 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000802 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000803 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000804 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000805 }
Mike Stump11289f42009-09-09 15:08:12 +0000806
Steve Naroff574440f2007-10-24 22:48:43 +0000807 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000808 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000809 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000810}
811
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000812void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000813 SourceLocation LocStart = Method->getLocStart();
814 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000815
Chris Lattner88ea93e2009-02-04 01:06:56 +0000816 if (SM->getInstantiationLineNumber(LocEnd) >
817 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000818 InsertText(LocStart, "#if 0\n", 6);
819 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000820 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000821 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000822 }
823}
824
Mike Stump11289f42009-09-09 15:08:12 +0000825void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000826 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000827
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000828 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000829
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000830 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000831}
832
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000833void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000834 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000835
Steve Naroff5448cf62007-10-30 13:30:57 +0000836 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000837 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000838
839 for (ObjCCategoryDecl::instmeth_iterator
840 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000841 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000842 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000843 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000844 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000845 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000846 RewriteMethodDeclaration(*I);
847
Steve Naroff5448cf62007-10-30 13:30:57 +0000848 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000849 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000850}
851
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000852void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000853 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000854
Steve Narofff921385f2007-10-30 16:42:30 +0000855 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000856
Steve Narofff921385f2007-10-30 16:42:30 +0000857 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000858 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000859
860 for (ObjCProtocolDecl::instmeth_iterator
861 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000862 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000863 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000864 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000865 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000866 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000867 RewriteMethodDeclaration(*I);
868
Steve Narofff921385f2007-10-30 16:42:30 +0000869 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000870 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000871 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000872
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000873 // Must comment out @optional/@required
874 const char *startBuf = SM->getCharacterData(LocStart);
875 const char *endBuf = SM->getCharacterData(LocEnd);
876 for (const char *p = startBuf; p < endBuf; p++) {
877 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
878 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000879 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000880 ReplaceText(OptionalLoc, strlen("@optional"),
881 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000882
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000883 }
884 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
885 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000886 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000887 ReplaceText(OptionalLoc, strlen("@required"),
888 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000889
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000890 }
891 }
Steve Narofff921385f2007-10-30 16:42:30 +0000892}
893
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000894void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000895 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000896 if (LocStart.isInvalid())
897 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000898 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000899 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000900}
901
Mike Stump11289f42009-09-09 15:08:12 +0000902void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000903 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000904 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000905 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000906 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000907 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000908 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000909 else if (OMD->getResultType()->isFunctionPointerType() ||
910 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000911 // needs special handling, since pointer-to-functions have special
912 // syntax (where a decaration models use).
913 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000914 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000915 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000916 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000917 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000918 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000919 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000920 ResultStr += FPRetType->getResultType().getAsString();
921 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000922 }
923 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000924 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000925 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000926
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000927 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000928 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000929
Douglas Gregorffca3a22009-01-09 17:18:27 +0000930 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000931 NameStr += "_I_";
932 else
933 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000934
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000935 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000936 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000937
938 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000939 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000940 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000941 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000942 }
Mike Stump11289f42009-09-09 15:08:12 +0000943 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000944 {
945 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000946 int len = selString.size();
947 for (int i = 0; i < len; i++)
948 if (selString[i] == ':')
949 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000950 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000951 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000952 // Remember this name for metadata emission
953 MethodInternalNames[OMD] = NameStr;
954 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000955
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000956 // Rewrite arguments
957 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000958
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000959 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000960 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000961 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000962 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000963 if (!LangOpts.Microsoft) {
964 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
965 ResultStr += "struct ";
966 }
967 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000968 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000969 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000970 }
971 else
Steve Naroffd9803712009-04-29 16:37:50 +0000972 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000973
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000974 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000975 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000976 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000977
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000978 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000979 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
980 E = OMD->param_end(); PI != E; ++PI) {
981 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000982 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000983 if (PDecl->getType()->isObjCQualifiedIdType()) {
984 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000985 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000986 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000987 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000988 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000989 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000990 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000991 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
992 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000993 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000994 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000995 ResultStr += Name;
996 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000997 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000998 if (OMD->isVariadic())
999 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001000 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001001
Steve Naroffb067bbd2008-07-16 14:40:40 +00001002 if (FPRetType) {
1003 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001004
Steve Naroffb067bbd2008-07-16 14:40:40 +00001005 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001006 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001007 ResultStr += "(";
1008 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1009 if (i) ResultStr += ", ";
1010 std::string ParamStr = FT->getArgType(i).getAsString();
1011 ResultStr += ParamStr;
1012 }
1013 if (FT->isVariadic()) {
1014 if (FT->getNumArgs()) ResultStr += ", ";
1015 ResultStr += "...";
1016 }
1017 ResultStr += ")";
1018 } else {
1019 ResultStr += "()";
1020 }
1021 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001022}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001023void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001024 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1025 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001027 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001028 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001029 else
Chris Lattner1780a852008-01-31 19:42:41 +00001030 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001031
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001032 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001033 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1034 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001035 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001036 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001037 ObjCMethodDecl *OMD = *I;
1038 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001039 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001040 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001041
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001042 const char *startBuf = SM->getCharacterData(LocStart);
1043 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001044 ReplaceText(LocStart, endBuf-startBuf,
1045 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001046 }
Mike Stump11289f42009-09-09 15:08:12 +00001047
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001048 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001049 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1050 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001051 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001052 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001053 ObjCMethodDecl *OMD = *I;
1054 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001055 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001056 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001057
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001058 const char *startBuf = SM->getCharacterData(LocStart);
1059 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001060 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001061 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001062 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001063 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001064 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001065 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001066 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001067 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001068 }
1069
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001070 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001071 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001072 else
Mike Stump11289f42009-09-09 15:08:12 +00001073 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001074}
1075
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001076void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001077 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001078 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001079 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001080 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001081 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001082 ResultStr += "\n";
1083 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001084 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001085 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001086 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001087 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001088 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001089 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001090 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001091 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001092 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001093
1094 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001095 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001096 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001097 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001098 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001099 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001100 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001101 for (ObjCInterfaceDecl::classmeth_iterator
1102 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001103 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001104 RewriteMethodDeclaration(*I);
1105
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001106 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001107 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001108}
1109
Steve Naroff08628db2008-12-09 12:56:34 +00001110Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1111 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001112 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1113 // This allows us to reuse all the fun and games in SynthMessageExpr().
1114 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1115 ObjCMessageExpr *MsgExpr;
1116 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1117 llvm::SmallVector<Expr *, 1> ExprVec;
1118 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001119
Steve Naroff1042ff32008-12-08 16:43:47 +00001120 Stmt *Receiver = PropRefExpr->getBase();
1121 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1122 if (PRE && PropGetters[PRE]) {
1123 // This allows us to handle chain/nested property getters.
1124 Receiver = PropGetters[PRE];
1125 }
Mike Stump11289f42009-09-09 15:08:12 +00001126 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1127 PDecl->getSetterName(), PDecl->getType(),
1128 PDecl->getSetterMethodDecl(),
1129 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001130 &ExprVec[0], 1);
1131 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001132
Steve Naroff4588d0f2008-12-04 16:24:46 +00001133 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001134 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001135 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001136 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1137 // to things that stay around.
1138 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001139 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001140}
1141
Steve Naroff4588d0f2008-12-04 16:24:46 +00001142Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001143 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1144 // This allows us to reuse all the fun and games in SynthMessageExpr().
1145 ObjCMessageExpr *MsgExpr;
1146 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001147
Steve Naroff1042ff32008-12-08 16:43:47 +00001148 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001149
Steve Naroff1042ff32008-12-08 16:43:47 +00001150 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1151 if (PRE && PropGetters[PRE]) {
1152 // This allows us to handle chain/nested property getters.
1153 Receiver = PropGetters[PRE];
1154 }
Mike Stump11289f42009-09-09 15:08:12 +00001155 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1156 PDecl->getGetterName(), PDecl->getType(),
1157 PDecl->getGetterMethodDecl(),
1158 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001159 0, 0);
1160
Steve Naroff22216db2008-12-04 23:50:32 +00001161 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001162
1163 if (!PropParentMap)
1164 PropParentMap = new ParentMap(CurrentBody);
1165
1166 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1167 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1168 // We stash away the ReplacingStmt since actually doing the
1169 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1170 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001171 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1172 // to things that stay around.
1173 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001174 return PropRefExpr; // return the original...
1175 } else {
1176 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001177 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001178 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1179 // to things that stay around.
1180 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001181 return ReplacingStmt;
1182 }
Steve Narofff326f402008-12-03 00:56:33 +00001183}
1184
Mike Stump11289f42009-09-09 15:08:12 +00001185Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001186 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001187 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001188 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001189 if (CurMethodDef) {
Fariborz Jahanian14442302010-01-07 22:15:31 +00001190 if (IV->isArrow() && isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001191 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001192 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001193 // lookup which class implements the instance variable.
1194 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001195 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001196 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001197 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001198
Steve Naroffb1c02372008-05-08 17:52:16 +00001199 // Synthesize an explicit cast to gain access to the ivar.
1200 std::string RecName = clsDeclared->getIdentifier()->getName();
1201 RecName += "_IMPL";
1202 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001203 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001204 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001205 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1206 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001207 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001208 CastExpr::CK_Unknown,
1209 IV->getBase(),
1210 castT,SourceLocation(),
1211 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001212 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001213 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1214 IV->getBase()->getLocEnd(),
1215 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001216 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001217 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001218 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1219 IV->getLocation(),
1220 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001221 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001222 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001223 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001224 }
Mike Stump11289f42009-09-09 15:08:12 +00001225
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001226 ReplaceStmt(IV->getBase(), PE);
1227 // Cannot delete IV->getBase(), since PE points to it.
1228 // Replace the old base with the cast. This is important when doing
1229 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001230 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001231 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001232 }
Steve Naroff24840f62008-04-18 21:55:08 +00001233 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001234 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001235
Steve Naroff29ce4e52008-05-06 23:20:07 +00001236 // Explicit ivar refs need to have a cast inserted.
1237 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001238 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001239 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001240 // lookup which class implements the instance variable.
1241 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001242 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001243 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001244 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001245
Steve Naroff29ce4e52008-05-06 23:20:07 +00001246 // Synthesize an explicit cast to gain access to the ivar.
1247 std::string RecName = clsDeclared->getIdentifier()->getName();
1248 RecName += "_IMPL";
1249 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001250 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001251 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001252 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1253 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001254 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001255 CastExpr::CK_Unknown,
1256 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001257 castT, SourceLocation(),
1258 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001259 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001260 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001261 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001262 ReplaceStmt(IV->getBase(), PE);
1263 // Cannot delete IV->getBase(), since PE points to it.
1264 // Replace the old base with the cast. This is important when doing
1265 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001266 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001267 return IV;
1268 }
Steve Naroff05caa482007-11-15 11:33:00 +00001269 }
Steve Naroff24840f62008-04-18 21:55:08 +00001270 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001271}
1272
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001273/// SynthCountByEnumWithState - To print:
1274/// ((unsigned int (*)
1275/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001276/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001277/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001278/// "countByEnumeratingWithState:objects:count:"),
1279/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001280/// (id *)items, (unsigned int)16)
1281///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001282void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001283 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1284 "id *, unsigned int))(void *)objc_msgSend)";
1285 buf += "\n\t\t";
1286 buf += "((id)l_collection,\n\t\t";
1287 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1288 buf += "\n\t\t";
1289 buf += "&enumState, "
1290 "(id *)items, (unsigned int)16)";
1291}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001292
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001293/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1294/// statement to exit to its outer synthesized loop.
1295///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001296Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001297 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1298 return S;
1299 // replace break with goto __break_label
1300 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001301
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001302 SourceLocation startLoc = S->getLocStart();
1303 buf = "goto __break_label_";
1304 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001305 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001306
1307 return 0;
1308}
1309
1310/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1311/// statement to continue with its inner synthesized loop.
1312///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001313Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001314 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1315 return S;
1316 // replace continue with goto __continue_label
1317 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001318
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001319 SourceLocation startLoc = S->getLocStart();
1320 buf = "goto __continue_label_";
1321 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001322 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001323
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001324 return 0;
1325}
1326
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001327/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001328/// It rewrites:
1329/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001330
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001331/// Into:
1332/// {
Mike Stump11289f42009-09-09 15:08:12 +00001333/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001334/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001335/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001336/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001337/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001338/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001339/// if (limit) {
1340/// unsigned long startMutations = *enumState.mutationsPtr;
1341/// do {
1342/// unsigned long counter = 0;
1343/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001344/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001345/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001346/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001347/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001348/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001349/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001350/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001351/// objects:items count:16]);
1352/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001353/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001354/// }
1355/// else
1356/// elem = nil;
1357/// }
1358///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001359Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001360 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001361 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001362 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001363 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001364 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001365 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001366
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001367 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001368 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001369 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001370 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001371 std::string buf;
1372 buf = "\n{\n\t";
1373 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1374 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001375 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001376 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001377 if (ElementType->isObjCQualifiedIdType() ||
1378 ElementType->isObjCQualifiedInterfaceType())
1379 // Simply use 'id' for all qualified types.
1380 elementTypeAsString = "id";
1381 else
1382 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001383 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001384 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001385 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001386 buf += elementName;
1387 buf += ";\n\t";
1388 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001389 else {
1390 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001391 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001392 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1393 if (VD->getType()->isObjCQualifiedIdType() ||
1394 VD->getType()->isObjCQualifiedInterfaceType())
1395 // Simply use 'id' for all qualified types.
1396 elementTypeAsString = "id";
1397 else
1398 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001399 }
Mike Stump11289f42009-09-09 15:08:12 +00001400
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001401 // struct __objcFastEnumerationState enumState = { 0 };
1402 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1403 // id items[16];
1404 buf += "id items[16];\n\t";
1405 // id l_collection = (id)
1406 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001407 // Find start location of 'collection' the hard way!
1408 const char *startCollectionBuf = startBuf;
1409 startCollectionBuf += 3; // skip 'for'
1410 startCollectionBuf = strchr(startCollectionBuf, '(');
1411 startCollectionBuf++; // skip '('
1412 // find 'in' and skip it.
1413 while (*startCollectionBuf != ' ' ||
1414 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1415 (*(startCollectionBuf+3) != ' ' &&
1416 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1417 startCollectionBuf++;
1418 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001419
1420 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001421 ReplaceText(startLoc, startCollectionBuf - startBuf,
1422 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001423 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001424 SourceLocation rightParenLoc = S->getRParenLoc();
1425 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1426 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001427 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001428
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001429 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1430 // objects:items count:16];
1431 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001432 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001433 // ((unsigned int (*)
1434 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001435 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001436 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001437 // "countByEnumeratingWithState:objects:count:"),
1438 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001439 // (id *)items, (unsigned int)16);
1440 buf += "unsigned long limit =\n\t\t";
1441 SynthCountByEnumWithState(buf);
1442 buf += ";\n\t";
1443 /// if (limit) {
1444 /// unsigned long startMutations = *enumState.mutationsPtr;
1445 /// do {
1446 /// unsigned long counter = 0;
1447 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001448 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001449 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001450 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001451 buf += "if (limit) {\n\t";
1452 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1453 buf += "do {\n\t\t";
1454 buf += "unsigned long counter = 0;\n\t\t";
1455 buf += "do {\n\t\t\t";
1456 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1457 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1458 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001459 buf += " = (";
1460 buf += elementTypeAsString;
1461 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001462 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001463 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001464
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001465 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001466 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001467 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001468 /// objects:items count:16]);
1469 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001470 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001471 /// }
1472 /// else
1473 /// elem = nil;
1474 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001475 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001476 buf = ";\n\t";
1477 buf += "__continue_label_";
1478 buf += utostr(ObjCBcLabelNo.back());
1479 buf += ": ;";
1480 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481 buf += "} while (counter < limit);\n\t";
1482 buf += "} while (limit = ";
1483 SynthCountByEnumWithState(buf);
1484 buf += ");\n\t";
1485 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001486 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001487 buf += "__break_label_";
1488 buf += utostr(ObjCBcLabelNo.back());
1489 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490 buf += "}\n\t";
1491 buf += "else\n\t\t";
1492 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001493 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001494 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001495
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001496 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001497 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001498 if (isa<CompoundStmt>(S->getBody())) {
1499 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1500 InsertText(endBodyLoc, buf.c_str(), buf.size());
1501 } else {
1502 /* Need to treat single statements specially. For example:
1503 *
1504 * for (A *a in b) if (stuff()) break;
1505 * for (A *a in b) xxxyy;
1506 *
1507 * The following code simply scans ahead to the semi to find the actual end.
1508 */
1509 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1510 const char *semiBuf = strchr(stmtBuf, ';');
1511 assert(semiBuf && "Can't find ';'");
1512 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1513 InsertText(endBodyLoc, buf.c_str(), buf.size());
1514 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001515 Stmts.pop_back();
1516 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001517 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001518}
1519
Mike Stump11289f42009-09-09 15:08:12 +00001520/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001521/// This routine rewrites @synchronized(expr) stmt;
1522/// into:
1523/// objc_sync_enter(expr);
1524/// @try stmt @finally { objc_sync_exit(expr); }
1525///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001526Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001527 // Get the start location and compute the semi location.
1528 SourceLocation startLoc = S->getLocStart();
1529 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001530
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001531 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001532
1533 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001534 buf = "objc_sync_enter((id)";
1535 const char *lparenBuf = startBuf;
1536 while (*lparenBuf != '(') lparenBuf++;
1537 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001538 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1539 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001540 // been rewritten! (which implies the SourceLocation's are invalid).
1541 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001542 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001543 while (*endBuf != ')') endBuf--;
1544 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001545 buf = ");\n";
1546 // declare a new scope with two variables, _stack and _rethrow.
1547 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1548 buf += "int buf[18/*32-bit i386*/];\n";
1549 buf += "char *pointers[4];} _stack;\n";
1550 buf += "id volatile _rethrow = 0;\n";
1551 buf += "objc_exception_try_enter(&_stack);\n";
1552 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001553 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001554 startLoc = S->getSynchBody()->getLocEnd();
1555 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001556
Steve Naroffad7013b2008-08-19 13:04:19 +00001557 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001558 SourceLocation lastCurlyLoc = startLoc;
1559 buf = "}\nelse {\n";
1560 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001561 buf += "}\n";
1562 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001563 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001564
1565 std::string syncBuf;
1566 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001567 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001568 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001569 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001570 Context->getObjCIdType(),
1571 SourceLocation(),
1572 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001573 std::string syncExprBufS;
1574 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001575 syncExpr->printPretty(syncExprBuf, *Context, 0,
1576 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001577 syncBuf += syncExprBuf.str();
1578 syncBuf += ");";
1579
1580 buf += syncBuf;
1581 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001582 buf += "}\n";
1583 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattner9cc55f52008-01-31 19:51:04 +00001585 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001586
1587 bool hasReturns = false;
1588 HasReturnStmts(S->getSynchBody(), hasReturns);
1589 if (hasReturns)
1590 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1591
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001592 return 0;
1593}
1594
Steve Naroffec60b432009-12-05 21:43:12 +00001595void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1596{
Steve Naroff6d6da252008-12-05 17:03:39 +00001597 // Perform a bottom up traversal of all children.
1598 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1599 CI != E; ++CI)
1600 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001601 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001602
Steve Naroffec60b432009-12-05 21:43:12 +00001603 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001604 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001605 TryFinallyContainsReturnDiag);
1606 }
1607 return;
1608}
1609
Steve Naroffec60b432009-12-05 21:43:12 +00001610void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1611{
1612 // Perform a bottom up traversal of all children.
1613 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1614 CI != E; ++CI)
1615 if (*CI)
1616 HasReturnStmts(*CI, hasReturns);
1617
1618 if (isa<ReturnStmt>(S))
1619 hasReturns = true;
1620 return;
1621}
1622
1623void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1624 // Perform a bottom up traversal of all children.
1625 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1626 CI != E; ++CI)
1627 if (*CI) {
1628 RewriteTryReturnStmts(*CI);
1629 }
1630 if (isa<ReturnStmt>(S)) {
1631 SourceLocation startLoc = S->getLocStart();
1632 const char *startBuf = SM->getCharacterData(startLoc);
1633
1634 const char *semiBuf = strchr(startBuf, ';');
1635 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1636 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1637
1638 std::string buf;
1639 buf = "{ objc_exception_try_exit(&_stack); return";
1640
1641 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1642 InsertText(onePastSemiLoc, "}", 1);
1643 }
1644 return;
1645}
1646
1647void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1648 // Perform a bottom up traversal of all children.
1649 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1650 CI != E; ++CI)
1651 if (*CI) {
1652 RewriteSyncReturnStmts(*CI, syncExitBuf);
1653 }
1654 if (isa<ReturnStmt>(S)) {
1655 SourceLocation startLoc = S->getLocStart();
1656 const char *startBuf = SM->getCharacterData(startLoc);
1657
1658 const char *semiBuf = strchr(startBuf, ';');
1659 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1660 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1661
1662 std::string buf;
1663 buf = "{ objc_exception_try_exit(&_stack);";
1664 buf += syncExitBuf;
1665 buf += " return";
1666
1667 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1668 InsertText(onePastSemiLoc, "}", 1);
1669 }
1670 return;
1671}
1672
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001673Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001674 // Get the start location and compute the semi location.
1675 SourceLocation startLoc = S->getLocStart();
1676 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001677
Steve Naroffbf478ec2007-11-07 04:08:17 +00001678 assert((*startBuf == '@') && "bogus @try location");
1679
1680 std::string buf;
1681 // declare a new scope with two variables, _stack and _rethrow.
1682 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1683 buf += "int buf[18/*32-bit i386*/];\n";
1684 buf += "char *pointers[4];} _stack;\n";
1685 buf += "id volatile _rethrow = 0;\n";
1686 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001687 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001688
Chris Lattner9cc55f52008-01-31 19:51:04 +00001689 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001690
Steve Naroffbf478ec2007-11-07 04:08:17 +00001691 startLoc = S->getTryBody()->getLocEnd();
1692 startBuf = SM->getCharacterData(startLoc);
1693
1694 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001695
Steve Naroffbf478ec2007-11-07 04:08:17 +00001696 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001697 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1698 if (catchList) {
1699 startLoc = startLoc.getFileLocWithOffset(1);
1700 buf = " /* @catch begin */ else {\n";
1701 buf += " id _caught = objc_exception_extract(&_stack);\n";
1702 buf += " objc_exception_try_enter (&_stack);\n";
1703 buf += " if (_setjmp(_stack.buf))\n";
1704 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1705 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001706
Steve Naroffce2dca12008-07-16 15:31:30 +00001707 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001708 } else { /* no catch list */
1709 buf = "}\nelse {\n";
1710 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1711 buf += "}";
1712 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001713 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001714 bool sawIdTypedCatch = false;
1715 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001716 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001717 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001718
Mike Stump11289f42009-09-09 15:08:12 +00001719 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001720 buf = "if ("; // we are generating code for the first catch clause
1721 else
1722 buf = "else if (";
1723 startLoc = catchList->getLocStart();
1724 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001725
Steve Naroffbf478ec2007-11-07 04:08:17 +00001726 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001727
Steve Naroffbf478ec2007-11-07 04:08:17 +00001728 const char *lParenLoc = strchr(startBuf, '(');
1729
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001730 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001731 // Now rewrite the body...
1732 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001733 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1734 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001735 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1736 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001737 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001738
Steve Naroffedb5bc62008-02-01 20:02:07 +00001739 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001740 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001741 } else if (catchDecl) {
1742 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001743 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001744 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001745 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001746 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001747 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001748 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001749
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001750 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001751 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001752 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001753 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001754 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001755 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001756 }
1757 }
1758 // Now rewrite the body...
1759 lastCatchBody = catchList->getCatchBody();
1760 SourceLocation rParenLoc = catchList->getRParenLoc();
1761 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1762 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1763 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1764 assert((*rParenBuf == ')') && "bogus @catch paren location");
1765 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001766
Steve Naroffbf478ec2007-11-07 04:08:17 +00001767 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001768 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001769 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001770 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001771 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001772 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001773 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001774 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001775 catchList = catchList->getNextCatchStmt();
1776 }
1777 // Complete the catch list...
1778 if (lastCatchBody) {
1779 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001780 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1781 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001782
Steve Naroff4adbe312008-09-11 15:29:03 +00001783 // Insert the last (implicit) else clause *before* the right curly brace.
1784 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1785 buf = "} /* last catch end */\n";
1786 buf += "else {\n";
1787 buf += " _rethrow = _caught;\n";
1788 buf += " objc_exception_try_exit(&_stack);\n";
1789 buf += "} } /* @catch end */\n";
1790 if (!S->getFinallyStmt())
1791 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001792 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001793
Steve Naroffbf478ec2007-11-07 04:08:17 +00001794 // Set lastCurlyLoc
1795 lastCurlyLoc = lastCatchBody->getLocEnd();
1796 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001797 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001798 startLoc = finalStmt->getLocStart();
1799 startBuf = SM->getCharacterData(startLoc);
1800 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001801
Steve Naroffbf478ec2007-11-07 04:08:17 +00001802 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001803 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001804
Steve Naroffbf478ec2007-11-07 04:08:17 +00001805 Stmt *body = finalStmt->getFinallyBody();
1806 SourceLocation startLoc = body->getLocStart();
1807 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001808 assert(*SM->getCharacterData(startLoc) == '{' &&
1809 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001810 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001811 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001812
Steve Naroffbf478ec2007-11-07 04:08:17 +00001813 startLoc = startLoc.getFileLocWithOffset(1);
1814 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001815 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001816 endLoc = endLoc.getFileLocWithOffset(-1);
1817 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001818 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001819
Steve Naroffbf478ec2007-11-07 04:08:17 +00001820 // Set lastCurlyLoc
1821 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001822
Steve Naroff6d6da252008-12-05 17:03:39 +00001823 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001824 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001825 } else { /* no finally clause - make sure we synthesize an implicit one */
1826 buf = "{ /* implicit finally clause */\n";
1827 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1828 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1829 buf += "}";
1830 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001831
1832 // Now check for any return/continue/go statements within the @try.
1833 // The implicit finally clause won't called if the @try contains any
1834 // jump statements.
1835 bool hasReturns = false;
1836 HasReturnStmts(S->getTryBody(), hasReturns);
1837 if (hasReturns)
1838 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001839 }
1840 // Now emit the final closing curly brace...
1841 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1842 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001843 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001844 return 0;
1845}
1846
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001847Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001848 return 0;
1849}
1850
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001851Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001852 return 0;
1853}
1854
Mike Stump11289f42009-09-09 15:08:12 +00001855// This can't be done with ReplaceStmt(S, ThrowExpr), since
1856// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001857// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001858Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001859 // Get the start location and compute the semi location.
1860 SourceLocation startLoc = S->getLocStart();
1861 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001862
Steve Naroffa733c7f2007-11-07 15:32:26 +00001863 assert((*startBuf == '@') && "bogus @throw location");
1864
1865 std::string buf;
1866 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001867 if (S->getThrowExpr())
1868 buf = "objc_exception_throw(";
1869 else // add an implicit argument
1870 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001871
Steve Naroff29788342008-07-25 15:41:30 +00001872 // handle "@ throw" correctly.
1873 const char *wBuf = strchr(startBuf, 'w');
1874 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1875 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001876
Steve Naroffa733c7f2007-11-07 15:32:26 +00001877 const char *semiBuf = strchr(startBuf, ';');
1878 assert((*semiBuf == ';') && "@throw: can't find ';'");
1879 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1880 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001881 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001882 return 0;
1883}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001884
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001885Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001886 // Create a new string expression.
1887 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001888 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001889 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001890 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1891 StrEncoding.length(), false,StrType,
1892 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001893 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001894
Chris Lattner4431a1b2007-11-30 22:53:43 +00001895 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001896 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001897 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001898}
1899
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001900Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001901 if (!SelGetUidFunctionDecl)
1902 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001903 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1904 // Create a call to sel_registerName("selName").
1905 llvm::SmallVector<Expr*, 8> SelExprs;
1906 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001907 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001908 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001909 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001910 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001911 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1912 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001913 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001914 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001915 return SelExp;
1916}
1917
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001918CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001919 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001920 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001921 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001922
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001923 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001924 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001925
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001926 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001927 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001928 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001929 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001930 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001931 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001932
John McCall9dd450b2009-09-21 23:43:11 +00001933 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001934
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001935 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1936 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001937}
1938
Steve Naroff50d42052007-11-01 13:24:47 +00001939static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1940 const char *&startRef, const char *&endRef) {
1941 while (startBuf < endBuf) {
1942 if (*startBuf == '<')
1943 startRef = startBuf; // mark the start.
1944 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001945 if (startRef && *startRef == '<') {
1946 endRef = startBuf; // mark the end.
1947 return true;
1948 }
1949 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001950 }
1951 startBuf++;
1952 }
1953 return false;
1954}
1955
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001956static void scanToNextArgument(const char *&argRef) {
1957 int angle = 0;
1958 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1959 if (*argRef == '<')
1960 angle++;
1961 else if (*argRef == '>')
1962 angle--;
1963 argRef++;
1964 }
1965 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1966}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001967
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001968bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001969 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001970}
1971
Steve Naroff873bd842008-07-29 18:15:38 +00001972void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1973 QualType Type = E->getType();
1974 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001975 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001976
Steve Naroffdbfc6932008-11-19 21:15:47 +00001977 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1978 Loc = ECE->getLParenLoc();
1979 EndLoc = ECE->getRParenLoc();
1980 } else {
1981 Loc = E->getLocStart();
1982 EndLoc = E->getLocEnd();
1983 }
1984 // This will defend against trying to rewrite synthesized expressions.
1985 if (Loc.isInvalid() || EndLoc.isInvalid())
1986 return;
1987
Steve Naroff873bd842008-07-29 18:15:38 +00001988 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001989 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001990 const char *startRef = 0, *endRef = 0;
1991 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1992 // Get the locations of the startRef, endRef.
1993 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1994 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1995 // Comment out the protocol references.
1996 InsertText(LessLoc, "/*", 2);
1997 InsertText(GreaterLoc, "*/", 2);
1998 }
1999 }
2000}
2001
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002002void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002003 SourceLocation Loc;
2004 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002005 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002006 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2007 Loc = VD->getLocation();
2008 Type = VD->getType();
2009 }
2010 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2011 Loc = FD->getLocation();
2012 // Check for ObjC 'id' and class types that have been adorned with protocol
2013 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002014 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002015 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002016 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002017 if (!proto)
2018 return;
2019 Type = proto->getResultType();
2020 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002021 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2022 Loc = FD->getLocation();
2023 Type = FD->getType();
2024 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002025 else
2026 return;
Mike Stump11289f42009-09-09 15:08:12 +00002027
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002028 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002029 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002030
Steve Naroff50d42052007-11-01 13:24:47 +00002031 const char *endBuf = SM->getCharacterData(Loc);
2032 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002033 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002034 startBuf--; // scan backward (from the decl location) for return type.
2035 const char *startRef = 0, *endRef = 0;
2036 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2037 // Get the locations of the startRef, endRef.
2038 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2039 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2040 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002041 InsertText(LessLoc, "/*", 2);
2042 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002043 }
2044 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002045 if (!proto)
2046 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002047 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002048 const char *startBuf = SM->getCharacterData(Loc);
2049 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002050 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2051 if (needToScanForQualifiers(proto->getArgType(i))) {
2052 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002053
Steve Naroff50d42052007-11-01 13:24:47 +00002054 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002055 // scan forward (from the decl location) for argument types.
2056 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002057 const char *startRef = 0, *endRef = 0;
2058 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2059 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002060 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002061 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002062 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002063 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002064 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002065 InsertText(LessLoc, "/*", 2);
2066 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002067 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002068 startBuf = ++endBuf;
2069 }
2070 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002071 // If the function name is derived from a macro expansion, then the
2072 // argument buffer will not follow the name. Need to speak with Chris.
2073 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002074 startBuf++; // scan forward (from the decl location) for argument types.
2075 startBuf++;
2076 }
Steve Naroff50d42052007-11-01 13:24:47 +00002077 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002078}
2079
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002080// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002081void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002082 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2083 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002084 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002085 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002086 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002087 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002088 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002089 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002090 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002091 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002092}
2093
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002094void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002095 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002096 if (FD->getIdentifier() &&
2097 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002098 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002099 return;
2100 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002101 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002102}
2103
Steve Naroff17978c42008-03-11 17:37:02 +00002104// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002105void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002106 if (SuperContructorFunctionDecl)
2107 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002108 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002109 llvm::SmallVector<QualType, 16> ArgTys;
2110 QualType argT = Context->getObjCIdType();
2111 assert(!argT.isNull() && "Can't find 'id' type");
2112 ArgTys.push_back(argT);
2113 ArgTys.push_back(argT);
2114 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2115 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002116 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002117 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002118 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002119 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002120 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002121}
2122
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002123// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002124void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002125 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2126 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002127 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002128 assert(!argT.isNull() && "Can't find 'id' type");
2129 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002130 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002131 assert(!argT.isNull() && "Can't find 'SEL' type");
2132 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002133 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002134 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002135 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002136 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002137 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002138 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002139 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002140}
2141
Steve Naroff7fa2f042007-11-15 10:28:18 +00002142// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002143void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002144 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2145 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002146 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002147 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002148 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002149 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2150 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2151 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002152 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002153 assert(!argT.isNull() && "Can't find 'SEL' type");
2154 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002155 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002156 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002157 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002158 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002159 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002160 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002161 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002162}
2163
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002164// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002165void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002166 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2167 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002168 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002169 assert(!argT.isNull() && "Can't find 'id' type");
2170 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002171 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002172 assert(!argT.isNull() && "Can't find 'SEL' type");
2173 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002174 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002175 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002176 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002177 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002178 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002179 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002180 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002181}
2182
Mike Stump11289f42009-09-09 15:08:12 +00002183// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002184// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002185void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002186 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002187 &Context->Idents.get("objc_msgSendSuper_stret");
2188 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002189 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002190 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002191 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002192 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2193 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2194 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002195 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002196 assert(!argT.isNull() && "Can't find 'SEL' type");
2197 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002198 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002199 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002200 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002201 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002202 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002203 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002204 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002205}
2206
Steve Naroff2e4e3852008-05-08 22:02:18 +00002207// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002208void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002209 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2210 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002211 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002212 assert(!argT.isNull() && "Can't find 'id' type");
2213 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002214 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002215 assert(!argT.isNull() && "Can't find 'SEL' type");
2216 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002217 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002218 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002219 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002220 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002221 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002222 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002223 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002224}
2225
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002226// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002227void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002228 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2229 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002230 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002231 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002232 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002233 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002234 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002235 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002236 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002237 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002238}
2239
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002240// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002241void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002242 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2243 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002244 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002245 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002246 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002247 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002248 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002249 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002250 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002251 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002252}
2253
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002254Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002255 QualType strType = getConstantStringStructType();
2256
2257 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002258
2259 std::string tmpName = InFileName;
2260 unsigned i;
2261 for (i=0; i < tmpName.length(); i++) {
2262 char c = tmpName.at(i);
2263 // replace any non alphanumeric characters with '_'.
2264 if (!isalpha(c) && (c < '0' || c > '9'))
2265 tmpName[i] = '_';
2266 }
2267 S += tmpName;
2268 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002269 S += utostr(NumObjCStringLiterals++);
2270
Steve Naroff00a31762008-03-27 22:29:16 +00002271 Preamble += "static __NSConstantStringImpl " + S;
2272 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2273 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002274 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002275 std::string prettyBufS;
2276 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002277 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2278 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002279 Preamble += prettyBuf.str();
2280 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002281 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002282
2283 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2284 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002285 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002286 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2287 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002288 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002289 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002290 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002291 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002292 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002293 Unop, Exp->getType(),
2294 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002295 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002296 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002297 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002298 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002299}
2300
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002301ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002302 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002303 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002304
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002305 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002306 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002307 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002308 assert(OPT);
2309 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002310 return IT->getDecl();
2311 }
2312 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002313}
2314
2315// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002316QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002317 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002318 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002319 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002320 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002321 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002322
Steve Naroff7fa2f042007-11-15 10:28:18 +00002323 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002324 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002325 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002326 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002327
Steve Naroff7fa2f042007-11-15 10:28:18 +00002328 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002329 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002330 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2331 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002332 FieldTypes[i], 0,
2333 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002334 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002335 }
Mike Stump11289f42009-09-09 15:08:12 +00002336
Douglas Gregor91f84212008-12-11 16:49:14 +00002337 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002338 }
2339 return Context->getTagDeclType(SuperStructDecl);
2340}
2341
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002342QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002343 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002344 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002345 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002346 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002347 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002348
Steve Naroffce8e8862008-03-15 00:55:56 +00002349 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002350 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002351 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002352 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002353 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002354 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002355 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002356 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002357
Steve Naroffce8e8862008-03-15 00:55:56 +00002358 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002359 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002360 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2361 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002362 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002363 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002364 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002365 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002366 }
2367
2368 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002369 }
2370 return Context->getTagDeclType(ConstantStringDecl);
2371}
2372
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002373Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002374 if (!SelGetUidFunctionDecl)
2375 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002376 if (!MsgSendFunctionDecl)
2377 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002378 if (!MsgSendSuperFunctionDecl)
2379 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002380 if (!MsgSendStretFunctionDecl)
2381 SynthMsgSendStretFunctionDecl();
2382 if (!MsgSendSuperStretFunctionDecl)
2383 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002384 if (!MsgSendFpretFunctionDecl)
2385 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002386 if (!GetClassFunctionDecl)
2387 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002388 if (!GetMetaClassFunctionDecl)
2389 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002390
Steve Naroff7fa2f042007-11-15 10:28:18 +00002391 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002392 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2393 // May need to use objc_msgSend_stret() as well.
2394 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002395 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2396 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002397 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002398 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002399 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002400 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002401 }
Mike Stump11289f42009-09-09 15:08:12 +00002402
Steve Naroff574440f2007-10-24 22:48:43 +00002403 // Synthesize a call to objc_msgSend().
2404 llvm::SmallVector<Expr*, 8> MsgExprs;
2405 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002406
Steve Naroff574440f2007-10-24 22:48:43 +00002407 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2408 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002409 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2410 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002411 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002412 MsgSendFlavor = MsgSendSuperFunctionDecl;
2413 if (MsgSendStretFlavor)
2414 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2415 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002416
2417 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002418 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002419
2420 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002421
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002422 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002423 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002424 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002425 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002426 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002427 Context->getObjCIdType(),
2428 SourceLocation()),
2429 Context->getObjCIdType(),
2430 SourceLocation(), SourceLocation())); // set the 'receiver'.
2431
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002432 llvm::SmallVector<Expr*, 8> ClsExprs;
2433 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002434 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002435 SuperDecl->getIdentifier()->getNameStart(),
2436 SuperDecl->getIdentifier()->getLength(),
2437 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002438 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002439 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002440 ClsExprs.size());
2441 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002442 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002443 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002444 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002445 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002446 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002447 // struct objc_super
2448 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002449 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002450
Steve Naroff0b844f02008-03-11 18:14:26 +00002451 if (LangOpts.Microsoft) {
2452 SynthSuperContructorFunctionDecl();
2453 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002454 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002455 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002456 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002457 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002458 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002459 // The code for super is a little tricky to prevent collision with
2460 // the structure definition in the header. The rewriter has it's own
2461 // internal definition (__rw_objc_super) that is uses. This is why
2462 // we need the cast below. For example:
2463 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2464 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002465 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002466 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002467 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002468 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2469 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002470 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002471 SourceLocation(), SourceLocation());
2472 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002473 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002474 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2475 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002476 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002477 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002478 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002479 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002480 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002481 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002482 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002483 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002484 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002485 } else {
2486 llvm::SmallVector<Expr*, 8> ClsExprs;
2487 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002488 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002489 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002490 clsName->getLength(),
2491 false, argType,
2492 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002493 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002494 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002495 ClsExprs.size());
2496 MsgExprs.push_back(Cls);
2497 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002498 } else { // instance message.
2499 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002500
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002501 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002502 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002503 if (MsgSendStretFlavor)
2504 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002505 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002506
Steve Naroff7fa2f042007-11-15 10:28:18 +00002507 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002508
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002509 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002510 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002511 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002512 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002513 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002514 SourceLocation()),
2515 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002516 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002517
Steve Naroff7fa2f042007-11-15 10:28:18 +00002518 llvm::SmallVector<Expr*, 8> ClsExprs;
2519 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002520 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002521 SuperDecl->getIdentifier()->getNameStart(),
2522 SuperDecl->getIdentifier()->getLength(),
2523 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002524 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002525 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002526 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002527 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002528 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002529 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002530 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002531 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002532 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002533 // struct objc_super
2534 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002535 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002536
Steve Naroff17978c42008-03-11 17:37:02 +00002537 if (LangOpts.Microsoft) {
2538 SynthSuperContructorFunctionDecl();
2539 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002540 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002541 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002542 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002543 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002544 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002545 // The code for super is a little tricky to prevent collision with
2546 // the structure definition in the header. The rewriter has it's own
2547 // internal definition (__rw_objc_super) that is uses. This is why
2548 // we need the cast below. For example:
2549 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2550 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002551 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002552 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002553 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002554 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002555 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002556 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002557 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002558 } else {
2559 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002560 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2561 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002562 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002563 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002564 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002565 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002566 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002567 // Remove all type-casts because it may contain objc-style types; e.g.
2568 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002569 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002570 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002571 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002572 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002573 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002574 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002575 MsgExprs.push_back(recExpr);
2576 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002577 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002578 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002579 llvm::SmallVector<Expr*, 8> SelExprs;
2580 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002581 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002582 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002583 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002584 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002585 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2586 &SelExprs[0], SelExprs.size());
2587 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002588
Steve Naroff574440f2007-10-24 22:48:43 +00002589 // Now push any user supplied arguments.
2590 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002591 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002592 // Make all implicit casts explicit...ICE comes in handy:-)
2593 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2594 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002595 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002596 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002597 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002598 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002599 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002600 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002601 }
2602 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002603 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002604 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002605 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002606 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002607 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002608 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002609 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002610 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002611 }
Mike Stump11289f42009-09-09 15:08:12 +00002612 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002613 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002614 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2615 // out the argument in the original expression (since we aren't deleting
2616 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2617 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002618 }
Steve Narofff36987c2007-11-04 22:37:50 +00002619 // Generate the funky cast.
2620 CastExpr *cast;
2621 llvm::SmallVector<QualType, 8> ArgTypes;
2622 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002623
Steve Narofff36987c2007-11-04 22:37:50 +00002624 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002625 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2626 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2627 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002628 ArgTypes.push_back(Context->getObjCIdType());
2629 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002630 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002631 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002632 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2633 E = OMD->param_end(); PI != E; ++PI) {
2634 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002635 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002636 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002637 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002638 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002639 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002640 t = Context->getPointerType(BPT->getPointeeType());
2641 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002642 ArgTypes.push_back(t);
2643 }
Chris Lattnera4997152009-02-20 18:43:26 +00002644 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2645 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002646 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002647 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002648 }
2649 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002650 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002651
Steve Narofff36987c2007-11-04 22:37:50 +00002652 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002653 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002654 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002655
Mike Stump11289f42009-09-09 15:08:12 +00002656 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002657 // If we don't do this cast, we get the following bizarre warning/note:
2658 // xx.m:13: warning: function called through a non-compatible type
2659 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002660 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2661 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002662 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002663 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002664
Steve Narofff36987c2007-11-04 22:37:50 +00002665 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002666 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002667 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002668 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002669 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002670 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002671 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2672 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002673 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002674
2675 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002676 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002677
John McCall9dd450b2009-09-21 23:43:11 +00002678 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002679 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002680 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002681 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002682 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002683 if (MsgSendStretFlavor) {
2684 // We have the method which returns a struct/union. Must also generate
2685 // call to objc_msgSend_stret and hang both varieties on a conditional
2686 // expression which dictate which one to envoke depending on size of
2687 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002688
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002689 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002690 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002691 SourceLocation());
2692 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002693 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2694 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002695 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002696 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002697 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002698 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002699 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002700 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002701 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002702 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2703 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002704
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002705 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002706 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002707
John McCall9dd450b2009-09-21 23:43:11 +00002708 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002709 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002710 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002711 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002712
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002713 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002714 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002715 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002716 Context->getSizeType(),
2717 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002718 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2719 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2720 // For X86 it is more complicated and some kind of target specific routine
2721 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002722 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002723 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002724 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002725 Context->IntTy,
2726 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002727 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2728 BinaryOperator::LE,
2729 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002730 SourceLocation());
2731 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002732 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002733 new (Context) ConditionalOperator(lessThanExpr,
2734 SourceLocation(), CE,
2735 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002736 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002737 }
Mike Stump11289f42009-09-09 15:08:12 +00002738 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002739 return ReplacingStmt;
2740}
2741
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002742Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002743 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002744
Steve Naroff574440f2007-10-24 22:48:43 +00002745 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002746 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002747
2748 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002749 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002750}
2751
Steve Naroffd9803712009-04-29 16:37:50 +00002752// typedef struct objc_object Protocol;
2753QualType RewriteObjC::getProtocolType() {
2754 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002755 TypeSourceInfo *TInfo
2756 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002757 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002758 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002759 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002760 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002761 }
2762 return Context->getTypeDeclType(ProtocolTypeDecl);
2763}
2764
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002765/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002766/// a synthesized/forward data reference (to the protocol's metadata).
2767/// The forward references (and metadata) are generated in
2768/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002769Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002770 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2771 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002772 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002773 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002774 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2775 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2776 Context->getPointerType(DRE->getType()),
2777 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002778 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2779 CastExpr::CK_Unknown,
2780 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002781 SourceLocation(), SourceLocation());
2782 ReplaceStmt(Exp, castExpr);
2783 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002784 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002785 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002786
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002787}
2788
Mike Stump11289f42009-09-09 15:08:12 +00002789bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002790 const char *endBuf) {
2791 while (startBuf < endBuf) {
2792 if (*startBuf == '#') {
2793 // Skip whitespace.
2794 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2795 ;
2796 if (!strncmp(startBuf, "if", strlen("if")) ||
2797 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2798 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2799 !strncmp(startBuf, "define", strlen("define")) ||
2800 !strncmp(startBuf, "undef", strlen("undef")) ||
2801 !strncmp(startBuf, "else", strlen("else")) ||
2802 !strncmp(startBuf, "elif", strlen("elif")) ||
2803 !strncmp(startBuf, "endif", strlen("endif")) ||
2804 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2805 !strncmp(startBuf, "include", strlen("include")) ||
2806 !strncmp(startBuf, "import", strlen("import")) ||
2807 !strncmp(startBuf, "include_next", strlen("include_next")))
2808 return true;
2809 }
2810 startBuf++;
2811 }
2812 return false;
2813}
2814
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002815/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002816/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002817void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002818 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002819 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002820 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002821 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002822 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002823 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002824 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002825 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002826 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002827 SourceLocation LocStart = CDecl->getLocStart();
2828 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002829
Steve Naroffdde78982007-11-14 19:25:57 +00002830 const char *startBuf = SM->getCharacterData(LocStart);
2831 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002832
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002833 // If no ivars and no root or if its root, directly or indirectly,
2834 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002835 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2836 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002837 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002838 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002839 return;
2840 }
Mike Stump11289f42009-09-09 15:08:12 +00002841
2842 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002843 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002844 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002845 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002846 if (LangOpts.Microsoft)
2847 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002848
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002849 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002850 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002851 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002852 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002853 // If the buffer contains preprocessor directives, we do more fine-grained
2854 // rewrites. This is intended to fix code that looks like (which occurs in
2855 // NSURL.h, for example):
2856 //
2857 // #ifdef XYZ
2858 // @interface Foo : NSObject
2859 // #else
2860 // @interface FooBar : NSObject
2861 // #endif
2862 // {
2863 // int i;
2864 // }
2865 // @end
2866 //
2867 // This clause is segregated to avoid breaking the common case.
2868 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002869 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002870 CDecl->getClassLoc();
2871 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002872 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002873
Chris Lattnerf5b77512009-02-20 18:18:36 +00002874 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002875 // advance to the end of the referenced protocols.
2876 while (endHeader < cursor && *endHeader != '>') endHeader++;
2877 endHeader++;
2878 }
2879 // rewrite the original header
2880 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2881 } else {
2882 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002883 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002884 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002885 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002886 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002887 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002888 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002889 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002890 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002891
Steve Naroffdde78982007-11-14 19:25:57 +00002892 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002893 SourceLocation OnePastCurly =
2894 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2895 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002896 }
2897 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002898
Steve Naroffdde78982007-11-14 19:25:57 +00002899 // Now comment out any visibility specifiers.
2900 while (cursor < endBuf) {
2901 if (*cursor == '@') {
2902 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002903 // Skip whitespace.
2904 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2905 /*scan*/;
2906
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002907 // FIXME: presence of @public, etc. inside comment results in
2908 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002909 if (!strncmp(cursor, "public", strlen("public")) ||
2910 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002911 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002912 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002913 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002914 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002915 // FIXME: If there are cases where '<' is used in ivar declaration part
2916 // of user code, then scan the ivar list and use needToScanForQualifiers
2917 // for type checking.
2918 else if (*cursor == '<') {
2919 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002920 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002921 cursor = strchr(cursor, '>');
2922 cursor++;
2923 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002924 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002925 } else if (*cursor == '^') { // rewrite block specifier.
2926 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2927 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002928 }
Steve Naroffdde78982007-11-14 19:25:57 +00002929 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002930 }
Steve Naroffdde78982007-11-14 19:25:57 +00002931 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002932 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002933 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002934 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002935 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002936 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002937 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002938 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002939 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002940 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002941 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002942 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002943 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002944 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002945}
2946
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002947// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002948/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002949template<typename MethodIterator>
2950void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2951 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002952 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002953 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002954 const char *ClassName,
2955 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002956 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002957
Chris Lattner31bc07e2007-12-12 07:46:12 +00002958 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002959 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002960 SEL _cmd;
2961 char *method_types;
2962 void *_imp;
2963 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002964 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002965 Result += "\nstruct _objc_method {\n";
2966 Result += "\tSEL _cmd;\n";
2967 Result += "\tchar *method_types;\n";
2968 Result += "\tvoid *_imp;\n";
2969 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002970
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002971 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002972 }
Mike Stump11289f42009-09-09 15:08:12 +00002973
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002974 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002975
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002976 /* struct {
2977 struct _objc_method_list *next_method;
2978 int method_count;
2979 struct _objc_method method_list[];
2980 }
2981 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002982 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002983 Result += "\nstatic struct {\n";
2984 Result += "\tstruct _objc_method_list *next_method;\n";
2985 Result += "\tint method_count;\n";
2986 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002987 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002988 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002989 Result += prefix;
2990 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2991 Result += "_METHODS_";
2992 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002993 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002994 Result += IsInstanceMethod ? "inst" : "cls";
2995 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002996 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002997
Chris Lattner31bc07e2007-12-12 07:46:12 +00002998 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002999 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003000 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003001 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003002 Result += "\", \"";
3003 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003004 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003005 Result += MethodInternalNames[*MethodBegin];
3006 Result += "}\n";
3007 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3008 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003009 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003010 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003011 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003012 Result += "\", \"";
3013 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003014 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003015 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003016 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003017 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003018 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003019}
3020
Steve Naroffd9803712009-04-29 16:37:50 +00003021/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003022void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003023RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3024 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003025 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003026
3027 // Output struct protocol_methods holder of method selector and type.
3028 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3029 /* struct protocol_methods {
3030 SEL _cmd;
3031 char *method_types;
3032 }
3033 */
3034 Result += "\nstruct _protocol_methods {\n";
3035 Result += "\tstruct objc_selector *_cmd;\n";
3036 Result += "\tchar *method_types;\n";
3037 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003038
Steve Naroffd9803712009-04-29 16:37:50 +00003039 objc_protocol_methods = true;
3040 }
3041 // Do not synthesize the protocol more than once.
3042 if (ObjCSynthesizedProtocols.count(PDecl))
3043 return;
Mike Stump11289f42009-09-09 15:08:12 +00003044
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003045 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3046 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3047 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003048 /* struct _objc_protocol_method_list {
3049 int protocol_method_count;
3050 struct protocol_methods protocols[];
3051 }
Steve Naroff251084d2008-03-12 01:06:30 +00003052 */
Steve Naroffd9803712009-04-29 16:37:50 +00003053 Result += "\nstatic struct {\n";
3054 Result += "\tint protocol_method_count;\n";
3055 Result += "\tstruct _protocol_methods protocol_methods[";
3056 Result += utostr(NumMethods);
3057 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3058 Result += PDecl->getNameAsString();
3059 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3060 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003061
Steve Naroffd9803712009-04-29 16:37:50 +00003062 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003063 for (ObjCProtocolDecl::instmeth_iterator
3064 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003065 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003066 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003067 Result += "\t ,{{(struct objc_selector *)\"";
3068 else
3069 Result += "\t ,{(struct objc_selector *)\"";
3070 Result += (*I)->getSelector().getAsString().c_str();
3071 std::string MethodTypeString;
3072 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3073 Result += "\", \"";
3074 Result += MethodTypeString;
3075 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003076 }
Steve Naroffd9803712009-04-29 16:37:50 +00003077 Result += "\t }\n};\n";
3078 }
Mike Stump11289f42009-09-09 15:08:12 +00003079
Steve Naroffd9803712009-04-29 16:37:50 +00003080 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003081 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3082 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003083 if (NumMethods > 0) {
3084 /* struct _objc_protocol_method_list {
3085 int protocol_method_count;
3086 struct protocol_methods protocols[];
3087 }
3088 */
3089 Result += "\nstatic struct {\n";
3090 Result += "\tint protocol_method_count;\n";
3091 Result += "\tstruct _protocol_methods protocol_methods[";
3092 Result += utostr(NumMethods);
3093 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3094 Result += PDecl->getNameAsString();
3095 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3096 "{\n\t";
3097 Result += utostr(NumMethods);
3098 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003099
Steve Naroffd9803712009-04-29 16:37:50 +00003100 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003101 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003102 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003103 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003104 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003105 Result += "\t ,{{(struct objc_selector *)\"";
3106 else
3107 Result += "\t ,{(struct objc_selector *)\"";
3108 Result += (*I)->getSelector().getAsString().c_str();
3109 std::string MethodTypeString;
3110 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3111 Result += "\", \"";
3112 Result += MethodTypeString;
3113 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003114 }
Steve Naroffd9803712009-04-29 16:37:50 +00003115 Result += "\t }\n};\n";
3116 }
3117
3118 // Output:
3119 /* struct _objc_protocol {
3120 // Objective-C 1.0 extensions
3121 struct _objc_protocol_extension *isa;
3122 char *protocol_name;
3123 struct _objc_protocol **protocol_list;
3124 struct _objc_protocol_method_list *instance_methods;
3125 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003126 };
Steve Naroffd9803712009-04-29 16:37:50 +00003127 */
3128 static bool objc_protocol = false;
3129 if (!objc_protocol) {
3130 Result += "\nstruct _objc_protocol {\n";
3131 Result += "\tstruct _objc_protocol_extension *isa;\n";
3132 Result += "\tchar *protocol_name;\n";
3133 Result += "\tstruct _objc_protocol **protocol_list;\n";
3134 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3135 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003136 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003137
Steve Naroffd9803712009-04-29 16:37:50 +00003138 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003139 }
Mike Stump11289f42009-09-09 15:08:12 +00003140
Steve Naroffd9803712009-04-29 16:37:50 +00003141 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3142 Result += PDecl->getNameAsString();
3143 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3144 "{\n\t0, \"";
3145 Result += PDecl->getNameAsString();
3146 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003147 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003148 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3149 Result += PDecl->getNameAsString();
3150 Result += ", ";
3151 }
3152 else
3153 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003154 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003155 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3156 Result += PDecl->getNameAsString();
3157 Result += "\n";
3158 }
3159 else
3160 Result += "0\n";
3161 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003162
Steve Naroffd9803712009-04-29 16:37:50 +00003163 // Mark this protocol as having been generated.
3164 if (!ObjCSynthesizedProtocols.insert(PDecl))
3165 assert(false && "protocol already synthesized");
3166
3167}
3168
3169void RewriteObjC::
3170RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3171 const char *prefix, const char *ClassName,
3172 std::string &Result) {
3173 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003174
Steve Naroffd9803712009-04-29 16:37:50 +00003175 for (unsigned i = 0; i != Protocols.size(); i++)
3176 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3177
Chris Lattner388f6e92008-07-21 21:33:21 +00003178 // Output the top lovel protocol meta-data for the class.
3179 /* struct _objc_protocol_list {
3180 struct _objc_protocol_list *next;
3181 int protocol_count;
3182 struct _objc_protocol *class_protocols[];
3183 }
3184 */
3185 Result += "\nstatic struct {\n";
3186 Result += "\tstruct _objc_protocol_list *next;\n";
3187 Result += "\tint protocol_count;\n";
3188 Result += "\tstruct _objc_protocol *class_protocols[";
3189 Result += utostr(Protocols.size());
3190 Result += "];\n} _OBJC_";
3191 Result += prefix;
3192 Result += "_PROTOCOLS_";
3193 Result += ClassName;
3194 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3195 "{\n\t0, ";
3196 Result += utostr(Protocols.size());
3197 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003198
Chris Lattner388f6e92008-07-21 21:33:21 +00003199 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003200 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003201 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003202
Chris Lattner388f6e92008-07-21 21:33:21 +00003203 for (unsigned i = 1; i != Protocols.size(); i++) {
3204 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003205 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003206 Result += "\n";
3207 }
3208 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003209}
3210
Steve Naroffd9803712009-04-29 16:37:50 +00003211
Mike Stump11289f42009-09-09 15:08:12 +00003212/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003213/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003214void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003215 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003216 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003217 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003218 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003219 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003220 CDecl = CDecl->getNextClassCategory())
3221 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3222 break;
Mike Stump11289f42009-09-09 15:08:12 +00003223
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003224 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003225 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003226 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003227
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003228 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003229 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003230 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003231
3232 // If any of our property implementations have associated getters or
3233 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003234 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3235 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003236 Prop != PropEnd; ++Prop) {
3237 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3238 continue;
3239 if (!(*Prop)->getPropertyIvarDecl())
3240 continue;
3241 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3242 if (!PD)
3243 continue;
3244 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3245 InstanceMethods.push_back(Getter);
3246 if (PD->isReadOnly())
3247 continue;
3248 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3249 InstanceMethods.push_back(Setter);
3250 }
3251 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003252 true, "CATEGORY_", FullCategoryName.c_str(),
3253 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003254
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003255 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003256 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003257 false, "CATEGORY_", FullCategoryName.c_str(),
3258 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003259
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003260 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003261 // Null CDecl is case of a category implementation with no category interface
3262 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003263 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3264 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003265 /* struct _objc_category {
3266 char *category_name;
3267 char *class_name;
3268 struct _objc_method_list *instance_methods;
3269 struct _objc_method_list *class_methods;
3270 struct _objc_protocol_list *protocols;
3271 // Objective-C 1.0 extensions
3272 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003273 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003274 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003275 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003276 */
Mike Stump11289f42009-09-09 15:08:12 +00003277
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003278 static bool objc_category = false;
3279 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003280 Result += "\nstruct _objc_category {\n";
3281 Result += "\tchar *category_name;\n";
3282 Result += "\tchar *class_name;\n";
3283 Result += "\tstruct _objc_method_list *instance_methods;\n";
3284 Result += "\tstruct _objc_method_list *class_methods;\n";
3285 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003286 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003287 Result += "\tstruct _objc_property_list *instance_properties;\n";
3288 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003289 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003290 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003291 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3292 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003293 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003294 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003295 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003296 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003297 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003298
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003299 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003300 Result += "\t, (struct _objc_method_list *)"
3301 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3302 Result += FullCategoryName;
3303 Result += "\n";
3304 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003305 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003306 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003307 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003308 Result += "\t, (struct _objc_method_list *)"
3309 "&_OBJC_CATEGORY_CLASS_METHODS_";
3310 Result += FullCategoryName;
3311 Result += "\n";
3312 }
3313 else
3314 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003315
Chris Lattnerf5b77512009-02-20 18:18:36 +00003316 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003317 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003318 Result += FullCategoryName;
3319 Result += "\n";
3320 }
3321 else
3322 Result += "\t, 0\n";
3323 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003324}
3325
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003326/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3327/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003328void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3329 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003330 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003331 if (ivar->isBitField()) {
3332 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3333 // place all bitfields at offset 0.
3334 Result += "0";
3335 } else {
3336 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003337 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003338 if (LangOpts.Microsoft)
3339 Result += "_IMPL";
3340 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003341 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003342 Result += ")";
3343 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003344}
3345
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003346//===----------------------------------------------------------------------===//
3347// Meta Data Emission
3348//===----------------------------------------------------------------------===//
3349
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003350void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003351 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003352 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003353
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003354 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003355 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003356 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003357 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003358 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003359 }
Mike Stump11289f42009-09-09 15:08:12 +00003360
Chris Lattner30d23e82007-12-12 07:56:42 +00003361 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003362 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003363 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003364 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003365 if (NumIvars > 0) {
3366 static bool objc_ivar = false;
3367 if (!objc_ivar) {
3368 /* struct _objc_ivar {
3369 char *ivar_name;
3370 char *ivar_type;
3371 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003372 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003373 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003374 Result += "\nstruct _objc_ivar {\n";
3375 Result += "\tchar *ivar_name;\n";
3376 Result += "\tchar *ivar_type;\n";
3377 Result += "\tint ivar_offset;\n";
3378 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003379
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003380 objc_ivar = true;
3381 }
3382
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003383 /* struct {
3384 int ivar_count;
3385 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003386 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003387 */
Mike Stump11289f42009-09-09 15:08:12 +00003388 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003389 Result += "\tint ivar_count;\n";
3390 Result += "\tstruct _objc_ivar ivar_list[";
3391 Result += utostr(NumIvars);
3392 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003393 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003394 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003395 "{\n\t";
3396 Result += utostr(NumIvars);
3397 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003398
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003399 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003400 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003401 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003402 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003403 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003404 IV != IVEnd; ++IV)
3405 IVars.push_back(*IV);
3406 IVI = IVars.begin();
3407 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003408 } else {
3409 IVI = CDecl->ivar_begin();
3410 IVE = CDecl->ivar_end();
3411 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003412 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003413 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003414 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003415 std::string TmpString, StrEncoding;
3416 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3417 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003418 Result += StrEncoding;
3419 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003420 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003421 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003422 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003423 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003424 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003425 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003426 std::string TmpString, StrEncoding;
3427 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3428 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003429 Result += StrEncoding;
3430 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003431 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003432 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003433 }
Mike Stump11289f42009-09-09 15:08:12 +00003434
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003435 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003436 }
Mike Stump11289f42009-09-09 15:08:12 +00003437
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003438 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003439 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003440 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003441
3442 // If any of our property implementations have associated getters or
3443 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003444 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3445 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003446 Prop != PropEnd; ++Prop) {
3447 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3448 continue;
3449 if (!(*Prop)->getPropertyIvarDecl())
3450 continue;
3451 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3452 if (!PD)
3453 continue;
3454 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3455 InstanceMethods.push_back(Getter);
3456 if (PD->isReadOnly())
3457 continue;
3458 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3459 InstanceMethods.push_back(Setter);
3460 }
3461 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003462 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003463
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003464 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003465 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003466 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003467
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003468 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003469 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3470 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003471
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003472 // Declaration of class/meta-class metadata
3473 /* struct _objc_class {
3474 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003475 const char *super_class_name;
3476 char *name;
3477 long version;
3478 long info;
3479 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003480 struct _objc_ivar_list *ivars;
3481 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003482 struct objc_cache *cache;
3483 struct objc_protocol_list *protocols;
3484 const char *ivar_layout;
3485 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003486 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003487 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003488 static bool objc_class = false;
3489 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003490 Result += "\nstruct _objc_class {\n";
3491 Result += "\tstruct _objc_class *isa;\n";
3492 Result += "\tconst char *super_class_name;\n";
3493 Result += "\tchar *name;\n";
3494 Result += "\tlong version;\n";
3495 Result += "\tlong info;\n";
3496 Result += "\tlong instance_size;\n";
3497 Result += "\tstruct _objc_ivar_list *ivars;\n";
3498 Result += "\tstruct _objc_method_list *methods;\n";
3499 Result += "\tstruct objc_cache *cache;\n";
3500 Result += "\tstruct _objc_protocol_list *protocols;\n";
3501 Result += "\tconst char *ivar_layout;\n";
3502 Result += "\tstruct _objc_class_ext *ext;\n";
3503 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003504 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003505 }
Mike Stump11289f42009-09-09 15:08:12 +00003506
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003507 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003508 ObjCInterfaceDecl *RootClass = 0;
3509 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003510 while (SuperClass) {
3511 RootClass = SuperClass;
3512 SuperClass = SuperClass->getSuperClass();
3513 }
3514 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003515
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003516 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003517 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003518 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003519 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003520 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003521 Result += "\"";
3522
3523 if (SuperClass) {
3524 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003525 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003526 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003527 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003528 Result += "\"";
3529 }
3530 else {
3531 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003532 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003533 Result += "\"";
3534 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003535 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003536 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003537 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003538 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003539 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003540 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003541 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003542 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003543 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003544 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003545 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003546 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003547 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003548 Result += ",0,0\n";
3549 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003550 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 Result += "\t,0,0,0,0\n";
3552 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003553
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003554 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003555 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003556 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003557 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003558 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003559 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003560 if (SuperClass) {
3561 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003562 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003563 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003564 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003565 Result += "\"";
3566 }
3567 else {
3568 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003569 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003570 Result += "\"";
3571 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003572 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003573 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003574 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003575 Result += ",0";
3576 else {
3577 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003578 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003579 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003580 if (LangOpts.Microsoft)
3581 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003582 Result += ")";
3583 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003584 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003585 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003586 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003587 Result += "\n\t";
3588 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003589 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003590 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003591 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003592 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003593 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003594 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003595 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003596 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003597 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003598 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003599 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003600 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003601 Result += ", 0,0\n";
3602 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003603 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003604 Result += ",0,0,0\n";
3605 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003606}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003607
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003608/// RewriteImplementations - This routine rewrites all method implementations
3609/// and emits meta-data.
3610
Steve Narofff8cfd162008-11-13 20:07:04 +00003611void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003612 int ClsDefCount = ClassImplementation.size();
3613 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003614
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003615 // Rewrite implemented methods
3616 for (int i = 0; i < ClsDefCount; i++)
3617 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003618
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003619 for (int i = 0; i < CatDefCount; i++)
3620 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003621}
Mike Stump11289f42009-09-09 15:08:12 +00003622
Steve Narofff8cfd162008-11-13 20:07:04 +00003623void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3624 int ClsDefCount = ClassImplementation.size();
3625 int CatDefCount = CategoryImplementation.size();
3626
Steve Naroff30ac2222008-05-07 21:23:49 +00003627 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003628 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003629 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003630 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003631 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003632
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003633 // For each implemented category, write out all its meta data.
3634 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003635 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003636
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003637 // Write objc_symtab metadata
3638 /*
3639 struct _objc_symtab
3640 {
3641 long sel_ref_cnt;
3642 SEL *refs;
3643 short cls_def_cnt;
3644 short cat_def_cnt;
3645 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003646 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003647 */
Mike Stump11289f42009-09-09 15:08:12 +00003648
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003649 Result += "\nstruct _objc_symtab {\n";
3650 Result += "\tlong sel_ref_cnt;\n";
3651 Result += "\tSEL *refs;\n";
3652 Result += "\tshort cls_def_cnt;\n";
3653 Result += "\tshort cat_def_cnt;\n";
3654 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3655 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003656
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003657 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003658 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003659 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003660 + ", " + utostr(CatDefCount) + "\n";
3661 for (int i = 0; i < ClsDefCount; i++) {
3662 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003663 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003664 Result += "\n";
3665 }
Mike Stump11289f42009-09-09 15:08:12 +00003666
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003667 for (int i = 0; i < CatDefCount; i++) {
3668 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003669 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003670 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003671 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003672 Result += "\n";
3673 }
Mike Stump11289f42009-09-09 15:08:12 +00003674
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003675 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003676
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003677 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003678
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003679 /*
3680 struct _objc_module {
3681 long version;
3682 long size;
3683 const char *name;
3684 struct _objc_symtab *symtab;
3685 }
3686 */
Mike Stump11289f42009-09-09 15:08:12 +00003687
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003688 Result += "\nstruct _objc_module {\n";
3689 Result += "\tlong version;\n";
3690 Result += "\tlong size;\n";
3691 Result += "\tconst char *name;\n";
3692 Result += "\tstruct _objc_symtab *symtab;\n";
3693 Result += "};\n\n";
3694 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003695 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003696 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003697 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003698 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003699
3700 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003701 if (ProtocolExprDecls.size()) {
3702 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3703 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003704 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003705 E = ProtocolExprDecls.end(); I != E; ++I) {
3706 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3707 Result += (*I)->getNameAsString();
3708 Result += " = &_OBJC_PROTOCOL_";
3709 Result += (*I)->getNameAsString();
3710 Result += ";\n";
3711 }
3712 Result += "#pragma data_seg(pop)\n\n";
3713 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003714 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003715 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003716 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3717 Result += "&_OBJC_MODULES;\n";
3718 Result += "#pragma data_seg(pop)\n\n";
3719 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003720}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003721
Steve Naroff677ab3a2008-10-27 17:20:55 +00003722std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3723 const char *funcName,
3724 std::string Tag) {
3725 const FunctionType *AFT = CE->getFunctionType();
3726 QualType RT = AFT->getResultType();
3727 std::string StructRef = "struct " + Tag;
3728 std::string S = "static " + RT.getAsString() + " __" +
3729 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003730
Steve Naroff677ab3a2008-10-27 17:20:55 +00003731 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003732
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003733 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003734 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003735 // block (to reference imported block decl refs).
3736 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003737 } else if (BD->param_empty()) {
3738 S += "(" + StructRef + " *__cself)";
3739 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003740 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003741 assert(FT && "SynthesizeBlockFunc: No function proto");
3742 S += '(';
3743 // first add the implicit argument.
3744 S += StructRef + " *__cself, ";
3745 std::string ParamStr;
3746 for (BlockDecl::param_iterator AI = BD->param_begin(),
3747 E = BD->param_end(); AI != E; ++AI) {
3748 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003749 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003750 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003751 S += ParamStr;
3752 }
3753 if (FT->isVariadic()) {
3754 if (!BD->param_empty()) S += ", ";
3755 S += "...";
3756 }
3757 S += ')';
3758 }
3759 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003760
Steve Naroff677ab3a2008-10-27 17:20:55 +00003761 // Create local declarations to avoid rewriting all closure decl ref exprs.
3762 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003763 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003764 E = BlockByRefDecls.end(); I != E; ++I) {
3765 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003766 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003767 std::string TypeString = "struct __Block_byref_" + Name + " *";
3768 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003769 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003770 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003771 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003772 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003773 E = BlockByCopyDecls.end(); I != E; ++I) {
3774 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003775 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003776 // Handle nested closure invocation. For example:
3777 //
3778 // void (^myImportedClosure)(void);
3779 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003780 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003781 // void (^anotherClosure)(void);
3782 // anotherClosure = ^(void) {
3783 // myImportedClosure(); // import and invoke the closure
3784 // };
3785 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003786 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003787 S += "struct __block_impl *";
3788 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003789 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003790 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003791 }
3792 std::string RewrittenStr = RewrittenBlockExprs[CE];
3793 const char *cstr = RewrittenStr.c_str();
3794 while (*cstr++ != '{') ;
3795 S += cstr;
3796 S += "\n";
3797 return S;
3798}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003799
Steve Naroff677ab3a2008-10-27 17:20:55 +00003800std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3801 const char *funcName,
3802 std::string Tag) {
3803 std::string StructRef = "struct " + Tag;
3804 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003805
Steve Naroff677ab3a2008-10-27 17:20:55 +00003806 S += funcName;
3807 S += "_block_copy_" + utostr(i);
3808 S += "(" + StructRef;
3809 S += "*dst, " + StructRef;
3810 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003811 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003812 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003813 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003814 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003815 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003816 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003817 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003818 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003819 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003820 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003821 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003822 S += "}\n";
3823
Steve Naroff677ab3a2008-10-27 17:20:55 +00003824 S += "\nstatic void __";
3825 S += funcName;
3826 S += "_block_dispose_" + utostr(i);
3827 S += "(" + StructRef;
3828 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003829 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003830 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003831 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003832 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003833 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003834 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003835 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003836 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003837 }
Mike Stump11289f42009-09-09 15:08:12 +00003838 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003839 return S;
3840}
3841
Steve Naroff30484702009-12-06 21:14:13 +00003842std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3843 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003844 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003845 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003846
Steve Naroff677ab3a2008-10-27 17:20:55 +00003847 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003848 S += " struct " + Desc;
3849 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003850
Steve Naroff30484702009-12-06 21:14:13 +00003851 Constructor += "(void *fp, "; // Invoke function pointer.
3852 Constructor += "struct " + Desc; // Descriptor pointer.
3853 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003854
Steve Naroff677ab3a2008-10-27 17:20:55 +00003855 if (BlockDeclRefs.size()) {
3856 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003857 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003858 E = BlockByCopyDecls.end(); I != E; ++I) {
3859 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003860 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003861 std::string ArgName = "_" + FieldName;
3862 // Handle nested closure invocation. For example:
3863 //
3864 // void (^myImportedBlock)(void);
3865 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003866 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003867 // void (^anotherBlock)(void);
3868 // anotherBlock = ^(void) {
3869 // myImportedBlock(); // import and invoke the closure
3870 // };
3871 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003872 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003873 S += "struct __block_impl *";
3874 Constructor += ", void *" + ArgName;
3875 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003876 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3877 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003878 Constructor += ", " + ArgName;
3879 }
3880 S += FieldName + ";\n";
3881 }
3882 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003883 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003884 E = BlockByRefDecls.end(); I != E; ++I) {
3885 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003886 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003887 std::string ArgName = "_" + FieldName;
3888 // Handle nested closure invocation. For example:
3889 //
3890 // void (^myImportedBlock)(void);
3891 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003892 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003893 // void (^anotherBlock)(void);
3894 // anotherBlock = ^(void) {
3895 // myImportedBlock(); // import and invoke the closure
3896 // };
3897 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003898 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003899 S += "struct __block_impl *";
3900 Constructor += ", void *" + ArgName;
3901 } else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003902 std::string TypeString = "struct __Block_byref_" + FieldName;
3903 TypeString += " *";
3904 FieldName = TypeString + FieldName;
3905 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003906 Constructor += ", " + ArgName;
3907 }
3908 S += FieldName + "; // by ref\n";
3909 }
3910 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003911 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003912 if (GlobalVarDecl)
3913 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3914 else
3915 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003916 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003917
Steve Naroff30484702009-12-06 21:14:13 +00003918 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003919
Steve Naroff677ab3a2008-10-27 17:20:55 +00003920 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003921 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003922 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003923 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003924 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003925 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003926 Constructor += Name + " = (struct __block_impl *)_";
3927 else
3928 Constructor += Name + " = _";
3929 Constructor += Name + ";\n";
3930 }
3931 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003932 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003933 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003934 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003935 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003936 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 Constructor += Name + " = (struct __block_impl *)_";
3938 else
3939 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003940 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003941 }
3942 } else {
3943 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003944 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003945 if (GlobalVarDecl)
3946 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3947 else
3948 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003949 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3950 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003951 }
3952 Constructor += " ";
3953 Constructor += "}\n";
3954 S += Constructor;
3955 S += "};\n";
3956 return S;
3957}
3958
Steve Naroff30484702009-12-06 21:14:13 +00003959std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3960 std::string ImplTag, int i,
3961 const char *FunName,
3962 unsigned hasCopy) {
3963 std::string S = "\nstatic struct " + DescTag;
3964
3965 S += " {\n unsigned long reserved;\n";
3966 S += " unsigned long Block_size;\n";
3967 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003968 S += " void (*copy)(struct ";
3969 S += ImplTag; S += "*, struct ";
3970 S += ImplTag; S += "*);\n";
3971
3972 S += " void (*dispose)(struct ";
3973 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003974 }
3975 S += "} ";
3976
3977 S += DescTag + "_DATA = { 0, sizeof(struct ";
3978 S += ImplTag + ")";
3979 if (hasCopy) {
3980 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3981 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3982 }
3983 S += "};\n";
3984 return S;
3985}
3986
Steve Naroff677ab3a2008-10-27 17:20:55 +00003987void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3988 const char *FunName) {
3989 // Insert closures that were part of the function.
3990 for (unsigned i = 0; i < Blocks.size(); i++) {
3991
3992 CollectBlockDeclRefInfo(Blocks[i]);
3993
Steve Naroff30484702009-12-06 21:14:13 +00003994 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3995 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003996
Steve Naroff30484702009-12-06 21:14:13 +00003997 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003998
3999 InsertText(FunLocStart, CI.c_str(), CI.size());
4000
Steve Naroff30484702009-12-06 21:14:13 +00004001 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004002
Steve Naroff677ab3a2008-10-27 17:20:55 +00004003 InsertText(FunLocStart, CF.c_str(), CF.size());
4004
4005 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004006 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004007 InsertText(FunLocStart, HF.c_str(), HF.size());
4008 }
Steve Naroff30484702009-12-06 21:14:13 +00004009 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4010 ImportedBlockDecls.size() > 0);
4011 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004012
Steve Naroff677ab3a2008-10-27 17:20:55 +00004013 BlockDeclRefs.clear();
4014 BlockByRefDecls.clear();
4015 BlockByCopyDecls.clear();
4016 BlockCallExprs.clear();
4017 ImportedBlockDecls.clear();
4018 }
4019 Blocks.clear();
4020 RewrittenBlockExprs.clear();
4021}
4022
4023void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4024 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004025 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004026
Steve Naroff677ab3a2008-10-27 17:20:55 +00004027 SynthesizeBlockLiterals(FunLocStart, FuncName);
4028}
4029
4030void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004031 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4032 //SourceLocation FunLocStart = MD->getLocStart();
4033 // FIXME: This hack works around a bug in Rewrite.InsertText().
4034 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004035 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004036 // Convert colons to underscores.
4037 std::string::size_type loc = 0;
4038 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4039 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004040
Steve Naroff677ab3a2008-10-27 17:20:55 +00004041 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4042}
4043
4044void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4045 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4046 CI != E; ++CI)
4047 if (*CI) {
4048 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4049 GetBlockDeclRefExprs(CBE->getBody());
4050 else
4051 GetBlockDeclRefExprs(*CI);
4052 }
4053 // Handle specific things.
4054 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4055 // FIXME: Handle enums.
4056 if (!isa<FunctionDecl>(CDRE->getDecl()))
4057 BlockDeclRefs.push_back(CDRE);
4058 return;
4059}
4060
4061void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4062 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4063 CI != E; ++CI)
4064 if (*CI) {
4065 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4066 GetBlockCallExprs(CBE->getBody());
4067 else
4068 GetBlockCallExprs(*CI);
4069 }
Mike Stump11289f42009-09-09 15:08:12 +00004070
Steve Naroff677ab3a2008-10-27 17:20:55 +00004071 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4072 if (CE->getCallee()->getType()->isBlockPointerType()) {
4073 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4074 }
4075 }
4076 return;
4077}
4078
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004079Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004080 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004081 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004082
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004083 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004084 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004085 } else if (const BlockDeclRefExpr *CDRE =
4086 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004087 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004088 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004089 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004090 }
4091 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4092 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4093 }
4094 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4095 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4096 else if (const ConditionalOperator *CEXPR =
4097 dyn_cast<ConditionalOperator>(BlockExp)) {
4098 Expr *LHSExp = CEXPR->getLHS();
4099 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4100 Expr *RHSExp = CEXPR->getRHS();
4101 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4102 Expr *CONDExp = CEXPR->getCond();
4103 ConditionalOperator *CondExpr =
4104 new (Context) ConditionalOperator(CONDExp,
4105 SourceLocation(), cast<Expr>(LHSStmt),
4106 SourceLocation(), cast<Expr>(RHSStmt),
4107 Exp->getType());
4108 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004109 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4110 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004111 } else {
4112 assert(1 && "RewriteBlockClass: Bad type");
4113 }
4114 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004115 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004116 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004117 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004118 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004119
Steve Naroff350b6652008-10-30 10:07:53 +00004120 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4121 SourceLocation(),
4122 &Context->Idents.get("__block_impl"));
4123 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004124
Steve Naroff350b6652008-10-30 10:07:53 +00004125 // Generate a funky cast.
4126 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004127
Steve Naroff350b6652008-10-30 10:07:53 +00004128 // Push the block argument type.
4129 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004130 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004131 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004132 E = FTP->arg_type_end(); I && (I != E); ++I) {
4133 QualType t = *I;
4134 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004135 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004136 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004137 t = Context->getPointerType(BPT->getPointeeType());
4138 }
4139 ArgTypes.push_back(t);
4140 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004141 }
Steve Naroff350b6652008-10-30 10:07:53 +00004142 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004143 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004144 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004145
Steve Naroff350b6652008-10-30 10:07:53 +00004146 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004147
4148 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004149 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004150 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004151 PtrBlock, SourceLocation(),
4152 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004153 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004154 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4155 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004156 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004157
Douglas Gregor91f84212008-12-11 16:49:14 +00004158 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004159 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004160 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004161 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4162 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004163
Anders Carlssona2615922009-07-31 00:48:10 +00004164 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4165 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004166 PtrToFuncCastType,
4167 SourceLocation(),
4168 SourceLocation());
4169 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004170
Steve Naroff350b6652008-10-30 10:07:53 +00004171 llvm::SmallVector<Expr*, 8> BlkExprs;
4172 // Add the implicit argument.
4173 BlkExprs.push_back(BlkCast);
4174 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004175 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004176 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004177 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004178 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004179 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4180 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004181 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004182 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004183}
4184
4185void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004186 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004187 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004188}
4189
Steve Naroffd9803712009-04-29 16:37:50 +00004190// We need to return the rewritten expression to handle cases where the
4191// BlockDeclRefExpr is embedded in another expression being rewritten.
4192// For example:
4193//
4194// int main() {
4195// __block Foo *f;
4196// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004197//
Steve Naroffd9803712009-04-29 16:37:50 +00004198// void (^myblock)() = ^() {
4199// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4200// i = 77;
4201// };
4202//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004203Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004204 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004205 // for each DeclRefExp where BYREFVAR is name of the variable.
4206 ValueDecl *VD;
4207 bool isArrow = true;
4208 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4209 VD = BDRE->getDecl();
4210 else {
4211 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4212 isArrow = false;
4213 }
4214
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004215 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4216 &Context->Idents.get("__forwarding"),
4217 Context->VoidPtrTy, 0,
4218 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004219 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4220 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004221 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004222
4223 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004224 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4225 &Context->Idents.get(Name),
4226 Context->VoidPtrTy, 0,
4227 /*BitWidth=*/0, /*Mutable=*/true);
4228 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004229 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004230
4231
4232
Steve Narofff26a1d42009-02-02 17:19:26 +00004233 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004234 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4235 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004236 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004237 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004238}
4239
Steve Naroffc989a7b2008-11-03 23:29:32 +00004240void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4241 SourceLocation LocStart = CE->getLParenLoc();
4242 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004243
4244 // Need to avoid trying to rewrite synthesized casts.
4245 if (LocStart.isInvalid())
4246 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004247 // Need to avoid trying to rewrite casts contained in macros.
4248 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4249 return;
Mike Stump11289f42009-09-09 15:08:12 +00004250
Steve Naroff677ab3a2008-10-27 17:20:55 +00004251 const char *startBuf = SM->getCharacterData(LocStart);
4252 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004253
Steve Naroff677ab3a2008-10-27 17:20:55 +00004254 // advance the location to startArgList.
4255 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004256
Steve Naroff677ab3a2008-10-27 17:20:55 +00004257 while (*argPtr++ && (argPtr < endBuf)) {
4258 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004259 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004260 // Replace the '^' with '*'.
4261 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4262 ReplaceText(LocStart, 1, "*", 1);
4263 break;
4264 }
4265 }
4266 return;
4267}
4268
4269void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4270 SourceLocation DeclLoc = FD->getLocation();
4271 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004272
Steve Naroff677ab3a2008-10-27 17:20:55 +00004273 // We have 1 or more arguments that have closure pointers.
4274 const char *startBuf = SM->getCharacterData(DeclLoc);
4275 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004276
Steve Naroff677ab3a2008-10-27 17:20:55 +00004277 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004278
Steve Naroff677ab3a2008-10-27 17:20:55 +00004279 parenCount++;
4280 // advance the location to startArgList.
4281 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4282 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004283
Steve Naroff677ab3a2008-10-27 17:20:55 +00004284 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004285
Steve Naroff677ab3a2008-10-27 17:20:55 +00004286 while (*argPtr++ && parenCount) {
4287 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004288 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004289 // Replace the '^' with '*'.
4290 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4291 ReplaceText(DeclLoc, 1, "*", 1);
4292 break;
Mike Stump11289f42009-09-09 15:08:12 +00004293 case '(':
4294 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004295 break;
Mike Stump11289f42009-09-09 15:08:12 +00004296 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004297 parenCount--;
4298 break;
4299 }
4300 }
4301 return;
4302}
4303
4304bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004305 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004306 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004307 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004308 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004309 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004310 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004312 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004313 }
4314 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004315 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004316 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004317 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004318 return true;
4319 }
4320 return false;
4321}
4322
Ted Kremenek5a201952009-02-07 01:47:29 +00004323void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4324 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004325 const char *argPtr = strchr(Name, '(');
4326 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004327
Steve Naroff677ab3a2008-10-27 17:20:55 +00004328 LParen = argPtr; // output the start.
4329 argPtr++; // skip past the left paren.
4330 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004331
Steve Naroff677ab3a2008-10-27 17:20:55 +00004332 while (*argPtr && parenCount) {
4333 switch (*argPtr) {
4334 case '(': parenCount++; break;
4335 case ')': parenCount--; break;
4336 default: break;
4337 }
4338 if (parenCount) argPtr++;
4339 }
4340 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4341 RParen = argPtr; // output the end
4342}
4343
4344void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4346 RewriteBlockPointerFunctionArgs(FD);
4347 return;
Mike Stump11289f42009-09-09 15:08:12 +00004348 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004349 // Handle Variables and Typedefs.
4350 SourceLocation DeclLoc = ND->getLocation();
4351 QualType DeclT;
4352 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4353 DeclT = VD->getType();
4354 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4355 DeclT = TDD->getUnderlyingType();
4356 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4357 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004358 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004359 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004360
Steve Naroff677ab3a2008-10-27 17:20:55 +00004361 const char *startBuf = SM->getCharacterData(DeclLoc);
4362 const char *endBuf = startBuf;
4363 // scan backward (from the decl location) for the end of the previous decl.
4364 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4365 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004366
Steve Naroff677ab3a2008-10-27 17:20:55 +00004367 // *startBuf != '^' if we are dealing with a pointer to function that
4368 // may take block argument types (which will be handled below).
4369 if (*startBuf == '^') {
4370 // Replace the '^' with '*', computing a negative offset.
4371 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4372 ReplaceText(DeclLoc, 1, "*", 1);
4373 }
4374 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4375 // Replace the '^' with '*' for arguments.
4376 DeclLoc = ND->getLocation();
4377 startBuf = SM->getCharacterData(DeclLoc);
4378 const char *argListBegin, *argListEnd;
4379 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4380 while (argListBegin < argListEnd) {
4381 if (*argListBegin == '^') {
4382 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4383 ReplaceText(CaretLoc, 1, "*", 1);
4384 }
4385 argListBegin++;
4386 }
4387 }
4388 return;
4389}
4390
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004391
4392/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4393/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4394/// struct Block_byref_id_object *src) {
4395/// _Block_object_assign (&_dest->object, _src->object,
4396/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4397/// [|BLOCK_FIELD_IS_WEAK]) // object
4398/// _Block_object_assign(&_dest->object, _src->object,
4399/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4400/// [|BLOCK_FIELD_IS_WEAK]) // block
4401/// }
4402/// And:
4403/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4404/// _Block_object_dispose(_src->object,
4405/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4406/// [|BLOCK_FIELD_IS_WEAK]) // object
4407/// _Block_object_dispose(_src->object,
4408/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4409/// [|BLOCK_FIELD_IS_WEAK]) // block
4410/// }
4411
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004412std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4413 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004414 std::string S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004415 if (CopyDestroyCache.count(flag) > 0)
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004416 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004417 CopyDestroyCache.insert(flag);
4418 S = "static void __Block_byref_id_object_copy_";
4419 S += utostr(flag);
4420 S += "(void *dst, void *src) {\n";
4421
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004422 // offset into the object pointer is computed as:
4423 // void * + void* + int + int + void* + void *
4424 unsigned IntSize =
4425 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4426 unsigned VoidPtrSize =
4427 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4428
4429 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4430 S += " _Block_object_assign((char*)dst + ";
4431 S += utostr(offset);
4432 S += ", *(void * *) ((char*)src + ";
4433 S += utostr(offset);
4434 S += "), ";
4435 S += utostr(flag);
4436 S += ");\n}\n";
4437
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004438 S += "static void __Block_byref_id_object_dispose_";
4439 S += utostr(flag);
4440 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004441 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4442 S += utostr(offset);
4443 S += "), ";
4444 S += utostr(flag);
4445 S += ");\n}\n";
4446 return S;
4447}
4448
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004449/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4450/// the declaration into:
4451/// struct __Block_byref_ND {
4452/// void *__isa; // NULL for everything except __weak pointers
4453/// struct __Block_byref_ND *__forwarding;
4454/// int32_t __flags;
4455/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004456/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4457/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004458/// typex ND;
4459/// };
4460///
4461/// It then replaces declaration of ND variable with:
4462/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4463/// __size=sizeof(struct __Block_byref_ND),
4464/// ND=initializer-if-any};
4465///
4466///
4467void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004468 int flag = 0;
4469 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004470 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4471 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004472 SourceLocation X = ND->getLocEnd();
4473 X = SM->getInstantiationLoc(X);
4474 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004475 std::string Name(ND->getNameAsString());
4476 std::string ByrefType = "struct __Block_byref_";
4477 ByrefType += Name;
4478 ByrefType += " {\n";
4479 ByrefType += " void *__isa;\n";
4480 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4481 ByrefType += " int __flags;\n";
4482 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004483 // Add void *__Block_byref_id_object_copy;
4484 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004485 QualType Ty = ND->getType();
4486 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4487 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004488 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4489 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004490 }
4491
4492 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004493 ByrefType += " " + Name + ";\n";
4494 ByrefType += "};\n";
4495 // Insert this type in global scope. It is needed by helper function.
4496 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4497 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4498 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004499 if (Ty.isObjCGCWeak()) {
4500 flag |= BLOCK_FIELD_IS_WEAK;
4501 isa = 1;
4502 }
4503
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004504 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004505 flag = BLOCK_BYREF_CALLER;
4506 QualType Ty = ND->getType();
4507 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4508 if (Ty->isBlockPointerType())
4509 flag |= BLOCK_FIELD_IS_BLOCK;
4510 else
4511 flag |= BLOCK_FIELD_IS_OBJECT;
4512 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004513 if (!HF.empty())
4514 InsertText(FunLocStart, HF.c_str(), HF.size());
4515 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004516
4517 // struct __Block_byref_ND ND =
4518 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4519 // initializer-if-any};
4520 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004521 unsigned flags = 0;
4522 if (HasCopyAndDispose)
4523 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004524 Name = ND->getNameAsString();
4525 ByrefType = "struct __Block_byref_" + Name;
4526 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004527 ByrefType += " " + Name + " = {(void*)";
4528 ByrefType += utostr(isa);
4529 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004530 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004531 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004532 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004533 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004534 ByrefType += ", __Block_byref_id_object_copy_";
4535 ByrefType += utostr(flag);
4536 ByrefType += ", __Block_byref_id_object_dispose_";
4537 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004538 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004539 ByrefType += "};\n";
4540 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4541 ByrefType.c_str(), ByrefType.size());
4542 }
4543 else {
4544 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004545 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004546 ByrefType += " " + Name;
4547 ReplaceText(DeclLoc, endBuf-startBuf,
4548 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004549 ByrefType = " = {(void*)";
4550 ByrefType += utostr(isa);
4551 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004552 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004553 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004554 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004555 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004556 ByrefType += "__Block_byref_id_object_copy_";
4557 ByrefType += utostr(flag);
4558 ByrefType += ", __Block_byref_id_object_dispose_";
4559 ByrefType += utostr(flag);
4560 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004561 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004562 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004563
4564 // Complete the newly synthesized compound expression by inserting a right
4565 // curly brace before the end of the declaration.
4566 // FIXME: This approach avoids rewriting the initializer expression. It
4567 // also assumes there is only one declarator. For example, the following
4568 // isn't currently supported by this routine (in general):
4569 //
4570 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4571 //
4572 const char *startBuf = SM->getCharacterData(startLoc);
4573 const char *semiBuf = strchr(startBuf, ';');
4574 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4575 SourceLocation semiLoc =
4576 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4577
4578 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004579 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004580 return;
4581}
4582
Mike Stump11289f42009-09-09 15:08:12 +00004583void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004584 // Add initializers for any closure decl refs.
4585 GetBlockDeclRefExprs(Exp->getBody());
4586 if (BlockDeclRefs.size()) {
4587 // Unique all "by copy" declarations.
4588 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4589 if (!BlockDeclRefs[i]->isByRef())
4590 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4591 // Unique all "by ref" declarations.
4592 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4593 if (BlockDeclRefs[i]->isByRef()) {
4594 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4595 }
4596 // Find any imported blocks...they will need special attention.
4597 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004598 if (BlockDeclRefs[i]->isByRef() ||
4599 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4600 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004601 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004602 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4603 }
4604 }
4605}
4606
Steve Narofff4b992a2008-10-28 20:29:00 +00004607FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4608 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004609 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004610 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004611 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004612 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004613}
4614
Steve Naroffd8907b72008-10-29 18:15:37 +00004615Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004616 Blocks.push_back(Exp);
4617
4618 CollectBlockDeclRefInfo(Exp);
4619 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004620
Steve Narofff4b992a2008-10-28 20:29:00 +00004621 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004622 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004623 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004624 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004625 // Convert colons to underscores.
4626 std::string::size_type loc = 0;
4627 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4628 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004629 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004630 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004631
Steve Narofff4b992a2008-10-28 20:29:00 +00004632 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004633
Steve Narofff4b992a2008-10-28 20:29:00 +00004634 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4635 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004636
Steve Narofff4b992a2008-10-28 20:29:00 +00004637 // Get a pointer to the function type so we can cast appropriately.
4638 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4639
4640 FunctionDecl *FD;
4641 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004642
Steve Narofff4b992a2008-10-28 20:29:00 +00004643 // Simulate a contructor call...
4644 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004645 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004646
Steve Narofff4b992a2008-10-28 20:29:00 +00004647 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004648
Steve Naroffe2514232008-10-29 21:23:59 +00004649 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004650 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004651 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4652 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004653 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4654 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004655 Context->VoidPtrTy, SourceLocation(),
4656 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004657 InitExprs.push_back(castExpr);
4658
Steve Naroff30484702009-12-06 21:14:13 +00004659 // Initialize the block descriptor.
4660 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004661
Steve Naroff30484702009-12-06 21:14:13 +00004662 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4663 &Context->Idents.get(DescData.c_str()),
4664 Context->VoidPtrTy, 0,
4665 VarDecl::Static);
4666 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4667 new (Context) DeclRefExpr(NewVD,
4668 Context->VoidPtrTy, SourceLocation()),
4669 UnaryOperator::AddrOf,
4670 Context->getPointerType(Context->VoidPtrTy),
4671 SourceLocation());
4672 InitExprs.push_back(DescRefExpr);
4673
Steve Narofff4b992a2008-10-28 20:29:00 +00004674 // Add initializers for any closure decl refs.
4675 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004676 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004677 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004678 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004679 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004680 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004681 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004682 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004683 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004684 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004685 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004686 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004687 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4688 CastExpr::CK_Unknown, Arg,
4689 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004690 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004691 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004693 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004694 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004695 }
Mike Stump11289f42009-09-09 15:08:12 +00004696 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004697 }
4698 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004699 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004700 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004701 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004702 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4703 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004704 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004705 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004706 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004707 }
4708 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004709 if (ImportedBlockDecls.size()) {
4710 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4711 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004712 unsigned IntSize =
4713 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004714 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4715 Context->IntTy, SourceLocation());
4716 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004717 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004718 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4719 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004720 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004721 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004722 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004723 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004724 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004725 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004726 BlockDeclRefs.clear();
4727 BlockByRefDecls.clear();
4728 BlockByCopyDecls.clear();
4729 ImportedBlockDecls.clear();
4730 return NewRep;
4731}
4732
4733//===----------------------------------------------------------------------===//
4734// Function Body / Expression rewriting
4735//===----------------------------------------------------------------------===//
4736
Steve Naroff4588d0f2008-12-04 16:24:46 +00004737// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4738// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4739// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4740// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4741// Since the rewriter isn't capable of rewriting rewritten code, it's important
4742// we get this right.
4743void RewriteObjC::CollectPropertySetters(Stmt *S) {
4744 // Perform a bottom up traversal of all children.
4745 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4746 CI != E; ++CI)
4747 if (*CI)
4748 CollectPropertySetters(*CI);
4749
4750 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4751 if (BinOp->isAssignmentOp()) {
4752 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4753 PropSetters[PRE] = BinOp;
4754 }
4755 }
4756}
4757
Steve Narofff4b992a2008-10-28 20:29:00 +00004758Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004759 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004760 isa<DoStmt>(S) || isa<ForStmt>(S))
4761 Stmts.push_back(S);
4762 else if (isa<ObjCForCollectionStmt>(S)) {
4763 Stmts.push_back(S);
Anders Carlsson3caa2b42009-12-22 06:13:42 +00004764 ++BcLabelCount;
4765 ObjCBcLabelNo.push_back(BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004766 }
Mike Stump11289f42009-09-09 15:08:12 +00004767
Steve Narofff4b992a2008-10-28 20:29:00 +00004768 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004769
Steve Narofff4b992a2008-10-28 20:29:00 +00004770 // Perform a bottom up rewrite of all children.
4771 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4772 CI != E; ++CI)
4773 if (*CI) {
4774 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004775 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004776 *CI = newStmt;
4777 }
Mike Stump11289f42009-09-09 15:08:12 +00004778
Steve Narofff4b992a2008-10-28 20:29:00 +00004779 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4780 // Rewrite the block body in place.
4781 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004782
Steve Narofff4b992a2008-10-28 20:29:00 +00004783 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004784 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004785 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004786
Steve Narofff4b992a2008-10-28 20:29:00 +00004787 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4788 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004789 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004790 return blockTranscribed;
4791 }
4792 // Handle specific things.
4793 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4794 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004795
Steve Narofff4b992a2008-10-28 20:29:00 +00004796 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4797 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4798
Steve Naroff4588d0f2008-12-04 16:24:46 +00004799 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4800 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4801 if (BinOp) {
4802 // Because the rewriter doesn't allow us to rewrite rewritten code,
4803 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004804 DisableReplaceStmt = true;
4805 // Save the source range. Even if we disable the replacement, the
4806 // rewritten node will have been inserted into the tree. If the synthesized
4807 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004808 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004809 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4810 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004811 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004812 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004813 //
4814 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4815 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4816 // to see the original expression). Consider this example:
4817 //
4818 // Foo *obj1, *obj2;
4819 //
4820 // obj1.i = [obj2 rrrr];
4821 //
4822 // 'BinOp' for the previous expression looks like:
4823 //
4824 // (BinaryOperator 0x231ccf0 'int' '='
4825 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4826 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4827 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4828 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4829 //
4830 // 'newStmt' represents the rewritten message expression. For example:
4831 //
4832 // (CallExpr 0x231d300 'id':'struct objc_object *'
4833 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4834 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4835 // (CStyleCastExpr 0x231d220 'void *'
4836 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4837 //
4838 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4839 // can be used as the setter argument. ReplaceStmt() will still 'see'
4840 // the original RHS (since we haven't altered BinOp).
4841 //
Mike Stump11289f42009-09-09 15:08:12 +00004842 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004843 // node. As a result, we now leak the original AST nodes.
4844 //
Steve Naroff08628db2008-12-09 12:56:34 +00004845 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004846 } else {
4847 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004848 }
4849 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004850 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4851 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004852
Steve Narofff4b992a2008-10-28 20:29:00 +00004853 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4854 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004855
Steve Narofff4b992a2008-10-28 20:29:00 +00004856 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004857#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004858 // Before we rewrite it, put the original message expression in a comment.
4859 SourceLocation startLoc = MessExpr->getLocStart();
4860 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004861
Steve Narofff4b992a2008-10-28 20:29:00 +00004862 const char *startBuf = SM->getCharacterData(startLoc);
4863 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004864
Steve Narofff4b992a2008-10-28 20:29:00 +00004865 std::string messString;
4866 messString += "// ";
4867 messString.append(startBuf, endBuf-startBuf+1);
4868 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004869
4870 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004871 // InsertText(clang::SourceLocation, char const*, unsigned int).
4872 // InsertText(startLoc, messString.c_str(), messString.size());
4873 // Tried this, but it didn't work either...
4874 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004875#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004876 return RewriteMessageExpr(MessExpr);
4877 }
Mike Stump11289f42009-09-09 15:08:12 +00004878
Steve Narofff4b992a2008-10-28 20:29:00 +00004879 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4880 return RewriteObjCTryStmt(StmtTry);
4881
4882 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4883 return RewriteObjCSynchronizedStmt(StmtTry);
4884
4885 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4886 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004887
Steve Narofff4b992a2008-10-28 20:29:00 +00004888 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4889 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004890
4891 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004892 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004893 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004894 OrigStmtRange.getEnd());
4895 if (BreakStmt *StmtBreakStmt =
4896 dyn_cast<BreakStmt>(S))
4897 return RewriteBreakStmt(StmtBreakStmt);
4898 if (ContinueStmt *StmtContinueStmt =
4899 dyn_cast<ContinueStmt>(S))
4900 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004901
4902 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004903 // and cast exprs.
4904 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4905 // FIXME: What we're doing here is modifying the type-specifier that
4906 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004907 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004908 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4909 // the context of an ObjCForCollectionStmt. For example:
4910 // NSArray *someArray;
4911 // for (id <FooProtocol> index in someArray) ;
4912 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4913 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004914 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004915 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004916
Steve Narofff4b992a2008-10-28 20:29:00 +00004917 // Blocks rewrite rules.
4918 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4919 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004920 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004921 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004922 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004923 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004924 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004925 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004926 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4927 if (VD->hasAttr<BlocksAttr>())
4928 RewriteByRefVar(VD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004929 }
4930 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004931 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004932 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004933 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004934 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4935 }
4936 }
4937 }
Mike Stump11289f42009-09-09 15:08:12 +00004938
Steve Narofff4b992a2008-10-28 20:29:00 +00004939 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4940 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004941
4942 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004943 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4944 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004945 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4946 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004947 && "Statement stack mismatch");
4948 Stmts.pop_back();
4949 }
4950 // Handle blocks rewriting.
4951 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4952 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004953 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004954 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004955 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4956 ValueDecl *VD = DRE->getDecl();
4957 if (VD->hasAttr<BlocksAttr>())
4958 return RewriteBlockDeclRefExpr(DRE);
4959 }
4960
Steve Narofff4b992a2008-10-28 20:29:00 +00004961 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004962 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004963 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004964 ReplaceStmt(S, BlockCall);
4965 return BlockCall;
4966 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004967 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004968 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004969 RewriteCastExpr(CE);
4970 }
4971#if 0
4972 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004973 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004974 // Get the new text.
4975 std::string SStr;
4976 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004977 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004978 const std::string &Str = Buf.str();
4979
4980 printf("CAST = %s\n", &Str[0]);
4981 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4982 delete S;
4983 return Replacement;
4984 }
4985#endif
4986 // Return this stmt unmodified.
4987 return S;
4988}
4989
Steve Naroffe70a52a2009-12-05 15:55:59 +00004990void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4991 for (RecordDecl::field_iterator i = RD->field_begin(),
4992 e = RD->field_end(); i != e; ++i) {
4993 FieldDecl *FD = *i;
4994 if (isTopLevelBlockPointerType(FD->getType()))
4995 RewriteBlockPointerDecl(FD);
4996 if (FD->getType()->isObjCQualifiedIdType() ||
4997 FD->getType()->isObjCQualifiedInterfaceType())
4998 RewriteObjCQualifiedInterfaceTypes(FD);
4999 }
5000}
5001
Steve Narofff4b992a2008-10-28 20:29:00 +00005002/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5003/// main file of the input.
5004void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5005 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005006 if (FD->isOverloadedOperator())
5007 return;
Mike Stump11289f42009-09-09 15:08:12 +00005008
Steve Narofff4b992a2008-10-28 20:29:00 +00005009 // Since function prototypes don't have ParmDecl's, we check the function
5010 // prototype. This enables us to rewrite function declarations and
5011 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005012 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005013
Sebastian Redla7b98a72009-04-26 20:35:05 +00005014 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005015 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005016 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005017 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005018 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005019 Body =
5020 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5021 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005022 CurrentBody = 0;
5023 if (PropParentMap) {
5024 delete PropParentMap;
5025 PropParentMap = 0;
5026 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005027 // This synthesizes and inserts the block "impl" struct, invoke function,
5028 // and any copy/dispose helper functions.
5029 InsertBlockLiteralsWithinFunction(FD);
5030 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005031 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005032 return;
5033 }
5034 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005035 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005036 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005037 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005038 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005039 Body =
5040 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5041 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005042 CurrentBody = 0;
5043 if (PropParentMap) {
5044 delete PropParentMap;
5045 PropParentMap = 0;
5046 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005047 InsertBlockLiteralsWithinMethod(MD);
5048 CurMethodDef = 0;
5049 }
5050 }
5051 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5052 ClassImplementation.push_back(CI);
5053 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5054 CategoryImplementation.push_back(CI);
5055 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5056 RewriteForwardClassDecl(CD);
5057 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5058 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005059 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005060 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005061 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005062 CheckFunctionPointerDecl(VD->getType(), VD);
5063 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005064 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005065 RewriteCastExpr(CE);
5066 }
5067 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005068 } else if (VD->getType()->isRecordType()) {
5069 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5070 if (RD->isDefinition())
5071 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005072 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005073 if (VD->getInit()) {
5074 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005075 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005076 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005077 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005078 CurrentBody = 0;
5079 if (PropParentMap) {
5080 delete PropParentMap;
5081 PropParentMap = 0;
5082 }
Mike Stump11289f42009-09-09 15:08:12 +00005083 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005084 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005085 GlobalVarDecl = 0;
5086
5087 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005088 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005089 RewriteCastExpr(CE);
5090 }
5091 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005092 return;
5093 }
5094 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005095 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005096 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005097 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005098 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005099 else if (TD->getUnderlyingType()->isRecordType()) {
5100 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5101 if (RD->isDefinition())
5102 RewriteRecordBody(RD);
5103 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005104 return;
5105 }
5106 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005107 if (RD->isDefinition())
5108 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005109 return;
5110 }
5111 // Nothing yet.
5112}
5113
Chris Lattnercf169832009-03-28 04:11:33 +00005114void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005115 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005116
Steve Narofff4b992a2008-10-28 20:29:00 +00005117 // Rewrite tabs if we care.
5118 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005119
Steve Narofff4b992a2008-10-28 20:29:00 +00005120 if (Diags.hasErrorOccurred())
5121 return;
Mike Stump11289f42009-09-09 15:08:12 +00005122
Steve Narofff4b992a2008-10-28 20:29:00 +00005123 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005124
Steve Naroffd9803712009-04-29 16:37:50 +00005125 // Here's a great place to add any extra declarations that may be needed.
5126 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005127 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005128 E = ProtocolExprDecls.end(); I != E; ++I)
5129 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5130
Mike Stump11289f42009-09-09 15:08:12 +00005131 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005132 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005133 if (ClassImplementation.size() || CategoryImplementation.size())
5134 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005135
Steve Narofff4b992a2008-10-28 20:29:00 +00005136 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5137 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005138 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005139 Rewrite.getRewriteBufferFor(MainFileID)) {
5140 //printf("Changed:\n");
5141 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5142 } else {
5143 fprintf(stderr, "No changes\n");
5144 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005145
Steve Naroffd9803712009-04-29 16:37:50 +00005146 if (ClassImplementation.size() || CategoryImplementation.size() ||
5147 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005148 // Rewrite Objective-c meta data*
5149 std::string ResultStr;
5150 SynthesizeMetaDataIntoBuffer(ResultStr);
5151 // Emit metadata.
5152 *OutFile << ResultStr;
5153 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005154 OutFile->flush();
5155}
5156