blob: e9072d62e76d135fad96b3e9b8a8055c05d73a3e [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;
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000790 typedefString += "// @class ";
791 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
792 I != E; ++I) {
793 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
794 typedefString += ForwardDecl->getNameAsString();
795 if (I+1 != E)
796 typedefString += ", ";
797 else
798 typedefString += ";\n";
799 }
800
Chris Lattner9ee23b72009-02-20 18:04:31 +0000801 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
802 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000803 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000804 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000805 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000806 typedefString += "\n";
807 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000808 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000809 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000810 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000811 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000812 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000813 }
Mike Stump11289f42009-09-09 15:08:12 +0000814
Steve Naroff574440f2007-10-24 22:48:43 +0000815 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000816 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000817 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000818}
819
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000820void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000821 SourceLocation LocStart = Method->getLocStart();
822 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000823
Chris Lattner88ea93e2009-02-04 01:06:56 +0000824 if (SM->getInstantiationLineNumber(LocEnd) >
825 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000826 InsertText(LocStart, "#if 0\n", 6);
827 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000828 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000829 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000830 }
831}
832
Mike Stump11289f42009-09-09 15:08:12 +0000833void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000834 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000835
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000836 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000837
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000838 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000839}
840
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000841void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000842 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000843
Steve Naroff5448cf62007-10-30 13:30:57 +0000844 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000845 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000846
847 for (ObjCCategoryDecl::instmeth_iterator
848 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000849 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000850 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000851 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000852 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000853 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000854 RewriteMethodDeclaration(*I);
855
Steve Naroff5448cf62007-10-30 13:30:57 +0000856 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000857 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000858}
859
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000860void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000861 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000862
Steve Narofff921385f2007-10-30 16:42:30 +0000863 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000864
Steve Narofff921385f2007-10-30 16:42:30 +0000865 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000866 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000867
868 for (ObjCProtocolDecl::instmeth_iterator
869 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000870 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000871 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000872 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000873 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000874 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000875 RewriteMethodDeclaration(*I);
876
Steve Narofff921385f2007-10-30 16:42:30 +0000877 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +0000878 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000879 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000880
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000881 // Must comment out @optional/@required
882 const char *startBuf = SM->getCharacterData(LocStart);
883 const char *endBuf = SM->getCharacterData(LocEnd);
884 for (const char *p = startBuf; p < endBuf; p++) {
885 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
886 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000887 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000888 ReplaceText(OptionalLoc, strlen("@optional"),
889 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000890
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000891 }
892 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
893 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000894 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000895 ReplaceText(OptionalLoc, strlen("@required"),
896 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000897
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000898 }
899 }
Steve Narofff921385f2007-10-30 16:42:30 +0000900}
901
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000902void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000903 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000904 if (LocStart.isInvalid())
905 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000906 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000907 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000908}
909
Mike Stump11289f42009-09-09 15:08:12 +0000910void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000911 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000912 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000913 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000914 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000915 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000916 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000917 else if (OMD->getResultType()->isFunctionPointerType() ||
918 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000919 // needs special handling, since pointer-to-functions have special
920 // syntax (where a decaration models use).
921 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000922 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000923 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000924 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000925 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000926 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000927 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000928 ResultStr += FPRetType->getResultType().getAsString();
929 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000930 }
931 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000932 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000933 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000934
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000935 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000936 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000937
Douglas Gregorffca3a22009-01-09 17:18:27 +0000938 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000939 NameStr += "_I_";
940 else
941 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000942
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000943 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000944 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000945
946 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000947 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000948 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000949 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000950 }
Mike Stump11289f42009-09-09 15:08:12 +0000951 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000952 {
953 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000954 int len = selString.size();
955 for (int i = 0; i < len; i++)
956 if (selString[i] == ':')
957 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000958 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000959 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000960 // Remember this name for metadata emission
961 MethodInternalNames[OMD] = NameStr;
962 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000963
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000964 // Rewrite arguments
965 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000966
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000967 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000968 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000969 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000970 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000971 if (!LangOpts.Microsoft) {
972 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
973 ResultStr += "struct ";
974 }
975 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000976 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000977 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000978 }
979 else
Steve Naroffd9803712009-04-29 16:37:50 +0000980 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000981
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000982 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000983 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000984 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000985
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000986 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000987 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
988 E = OMD->param_end(); PI != E; ++PI) {
989 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000990 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000991 if (PDecl->getType()->isObjCQualifiedIdType()) {
992 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000993 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000994 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000995 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000996 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000997 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000998 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000999 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1000 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +00001001 } else
Douglas Gregor7de59662009-05-29 20:38:28 +00001002 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001003 ResultStr += Name;
1004 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001005 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001006 if (OMD->isVariadic())
1007 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001008 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001009
Steve Naroffb067bbd2008-07-16 14:40:40 +00001010 if (FPRetType) {
1011 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001012
Steve Naroffb067bbd2008-07-16 14:40:40 +00001013 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001014 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001015 ResultStr += "(";
1016 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1017 if (i) ResultStr += ", ";
1018 std::string ParamStr = FT->getArgType(i).getAsString();
1019 ResultStr += ParamStr;
1020 }
1021 if (FT->isVariadic()) {
1022 if (FT->getNumArgs()) ResultStr += ", ";
1023 ResultStr += "...";
1024 }
1025 ResultStr += ")";
1026 } else {
1027 ResultStr += "()";
1028 }
1029 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001030}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001031void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001032 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1033 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001034
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001035 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001036 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001037 else
Chris Lattner1780a852008-01-31 19:42:41 +00001038 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001039
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001040 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001041 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1042 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001043 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001044 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001045 ObjCMethodDecl *OMD = *I;
1046 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001047 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001048 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001049
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001050 const char *startBuf = SM->getCharacterData(LocStart);
1051 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001052 ReplaceText(LocStart, endBuf-startBuf,
1053 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001054 }
Mike Stump11289f42009-09-09 15:08:12 +00001055
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001056 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001057 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1058 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001059 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001060 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001061 ObjCMethodDecl *OMD = *I;
1062 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001063 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001064 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001065
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001066 const char *startBuf = SM->getCharacterData(LocStart);
1067 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001068 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001069 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001070 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001071 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001072 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001073 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001074 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001075 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001076 }
1077
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001078 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001079 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001080 else
Mike Stump11289f42009-09-09 15:08:12 +00001081 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001082}
1083
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001084void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001085 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001086 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001087 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001088 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001089 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001090 ResultStr += "\n";
1091 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001092 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001093 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001094 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001095 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001096 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001097 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001098 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001099 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001100 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001101
1102 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001103 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001104 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001105 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001106 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001107 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001108 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001109 for (ObjCInterfaceDecl::classmeth_iterator
1110 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001111 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001112 RewriteMethodDeclaration(*I);
1113
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001114 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001115 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001116}
1117
Steve Naroff08628db2008-12-09 12:56:34 +00001118Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1119 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001120 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1121 // This allows us to reuse all the fun and games in SynthMessageExpr().
1122 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1123 ObjCMessageExpr *MsgExpr;
1124 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1125 llvm::SmallVector<Expr *, 1> ExprVec;
1126 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001127
Steve Naroff1042ff32008-12-08 16:43:47 +00001128 Stmt *Receiver = PropRefExpr->getBase();
1129 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1130 if (PRE && PropGetters[PRE]) {
1131 // This allows us to handle chain/nested property getters.
1132 Receiver = PropGetters[PRE];
1133 }
Mike Stump11289f42009-09-09 15:08:12 +00001134 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1135 PDecl->getSetterName(), PDecl->getType(),
1136 PDecl->getSetterMethodDecl(),
1137 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001138 &ExprVec[0], 1);
1139 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001140
Steve Naroff4588d0f2008-12-04 16:24:46 +00001141 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001142 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001143 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001144 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1145 // to things that stay around.
1146 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001147 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001148}
1149
Steve Naroff4588d0f2008-12-04 16:24:46 +00001150Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001151 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1152 // This allows us to reuse all the fun and games in SynthMessageExpr().
1153 ObjCMessageExpr *MsgExpr;
1154 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001155
Steve Naroff1042ff32008-12-08 16:43:47 +00001156 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001157
Steve Naroff1042ff32008-12-08 16:43:47 +00001158 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1159 if (PRE && PropGetters[PRE]) {
1160 // This allows us to handle chain/nested property getters.
1161 Receiver = PropGetters[PRE];
1162 }
Mike Stump11289f42009-09-09 15:08:12 +00001163 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1164 PDecl->getGetterName(), PDecl->getType(),
1165 PDecl->getGetterMethodDecl(),
1166 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001167 0, 0);
1168
Steve Naroff22216db2008-12-04 23:50:32 +00001169 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001170
1171 if (!PropParentMap)
1172 PropParentMap = new ParentMap(CurrentBody);
1173
1174 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1175 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1176 // We stash away the ReplacingStmt since actually doing the
1177 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1178 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001179 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1180 // to things that stay around.
1181 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001182 return PropRefExpr; // return the original...
1183 } else {
1184 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001185 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001186 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1187 // to things that stay around.
1188 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001189 return ReplacingStmt;
1190 }
Steve Narofff326f402008-12-03 00:56:33 +00001191}
1192
Mike Stump11289f42009-09-09 15:08:12 +00001193Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001194 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001195 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001196 const Expr *BaseExpr = IV->getBase();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001197 if (CurMethodDef) {
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001198 if (BaseExpr->getType()->isObjCObjectPointerType() &&
1199 isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001200 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian0f3aecf2010-01-07 18:18:32 +00001201 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001202 // lookup which class implements the instance variable.
1203 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001204 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001205 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001206 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001207
Steve Naroffb1c02372008-05-08 17:52:16 +00001208 // Synthesize an explicit cast to gain access to the ivar.
1209 std::string RecName = clsDeclared->getIdentifier()->getName();
1210 RecName += "_IMPL";
1211 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001212 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001213 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001214 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1215 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001216 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001217 CastExpr::CK_Unknown,
1218 IV->getBase(),
1219 castT,SourceLocation(),
1220 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001221 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001222 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1223 IV->getBase()->getLocEnd(),
1224 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001225 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001226 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001227 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1228 IV->getLocation(),
1229 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001230 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001231 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001232 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001233 }
Mike Stump11289f42009-09-09 15:08:12 +00001234
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001235 ReplaceStmt(IV->getBase(), PE);
1236 // Cannot delete IV->getBase(), since PE points to it.
1237 // Replace the old base with the cast. This is important when doing
1238 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001239 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001240 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001241 }
Steve Naroff24840f62008-04-18 21:55:08 +00001242 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001243 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001244
Steve Naroff29ce4e52008-05-06 23:20:07 +00001245 // Explicit ivar refs need to have a cast inserted.
1246 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian12e2e862010-01-12 17:31:23 +00001247 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanian9146e442010-01-11 17:50:35 +00001248 ObjCInterfaceType *iFaceDecl =
1249 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001250 // lookup which class implements the instance variable.
1251 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001252 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001253 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001254 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001255
Steve Naroff29ce4e52008-05-06 23:20:07 +00001256 // Synthesize an explicit cast to gain access to the ivar.
1257 std::string RecName = clsDeclared->getIdentifier()->getName();
1258 RecName += "_IMPL";
1259 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001260 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001261 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001262 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1263 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001264 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001265 CastExpr::CK_Unknown,
1266 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001267 castT, SourceLocation(),
1268 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001269 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001270 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001271 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001272 ReplaceStmt(IV->getBase(), PE);
1273 // Cannot delete IV->getBase(), since PE points to it.
1274 // Replace the old base with the cast. This is important when doing
1275 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001276 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001277 return IV;
1278 }
Steve Naroff05caa482007-11-15 11:33:00 +00001279 }
Steve Naroff24840f62008-04-18 21:55:08 +00001280 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001281}
1282
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001283/// SynthCountByEnumWithState - To print:
1284/// ((unsigned int (*)
1285/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001286/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001287/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001288/// "countByEnumeratingWithState:objects:count:"),
1289/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001290/// (id *)items, (unsigned int)16)
1291///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001292void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001293 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1294 "id *, unsigned int))(void *)objc_msgSend)";
1295 buf += "\n\t\t";
1296 buf += "((id)l_collection,\n\t\t";
1297 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1298 buf += "\n\t\t";
1299 buf += "&enumState, "
1300 "(id *)items, (unsigned int)16)";
1301}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001302
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001303/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1304/// statement to exit to its outer synthesized loop.
1305///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001306Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001307 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1308 return S;
1309 // replace break with goto __break_label
1310 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001311
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001312 SourceLocation startLoc = S->getLocStart();
1313 buf = "goto __break_label_";
1314 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001315 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001316
1317 return 0;
1318}
1319
1320/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1321/// statement to continue with its inner synthesized loop.
1322///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001323Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001324 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1325 return S;
1326 // replace continue with goto __continue_label
1327 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001328
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001329 SourceLocation startLoc = S->getLocStart();
1330 buf = "goto __continue_label_";
1331 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001332 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001333
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001334 return 0;
1335}
1336
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001337/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001338/// It rewrites:
1339/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001341/// Into:
1342/// {
Mike Stump11289f42009-09-09 15:08:12 +00001343/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001344/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001345/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001346/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001347/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001348/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001349/// if (limit) {
1350/// unsigned long startMutations = *enumState.mutationsPtr;
1351/// do {
1352/// unsigned long counter = 0;
1353/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001354/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001355/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001356/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001357/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001358/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001359/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001360/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001361/// objects:items count:16]);
1362/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001363/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001364/// }
1365/// else
1366/// elem = nil;
1367/// }
1368///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001369Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001370 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001371 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001372 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001373 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001374 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001375 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001376
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001377 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001378 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001379 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001380 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001381 std::string buf;
1382 buf = "\n{\n\t";
1383 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1384 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001385 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001386 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001387 if (ElementType->isObjCQualifiedIdType() ||
1388 ElementType->isObjCQualifiedInterfaceType())
1389 // Simply use 'id' for all qualified types.
1390 elementTypeAsString = "id";
1391 else
1392 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001393 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001394 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001395 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001396 buf += elementName;
1397 buf += ";\n\t";
1398 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001399 else {
1400 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001401 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001402 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1403 if (VD->getType()->isObjCQualifiedIdType() ||
1404 VD->getType()->isObjCQualifiedInterfaceType())
1405 // Simply use 'id' for all qualified types.
1406 elementTypeAsString = "id";
1407 else
1408 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001411 // struct __objcFastEnumerationState enumState = { 0 };
1412 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1413 // id items[16];
1414 buf += "id items[16];\n\t";
1415 // id l_collection = (id)
1416 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001417 // Find start location of 'collection' the hard way!
1418 const char *startCollectionBuf = startBuf;
1419 startCollectionBuf += 3; // skip 'for'
1420 startCollectionBuf = strchr(startCollectionBuf, '(');
1421 startCollectionBuf++; // skip '('
1422 // find 'in' and skip it.
1423 while (*startCollectionBuf != ' ' ||
1424 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1425 (*(startCollectionBuf+3) != ' ' &&
1426 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1427 startCollectionBuf++;
1428 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001429
1430 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001431 ReplaceText(startLoc, startCollectionBuf - startBuf,
1432 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001433 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001434 SourceLocation rightParenLoc = S->getRParenLoc();
1435 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1436 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001437 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001438
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001439 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1440 // objects:items count:16];
1441 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001442 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001443 // ((unsigned int (*)
1444 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001445 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001446 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001447 // "countByEnumeratingWithState:objects:count:"),
1448 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001449 // (id *)items, (unsigned int)16);
1450 buf += "unsigned long limit =\n\t\t";
1451 SynthCountByEnumWithState(buf);
1452 buf += ";\n\t";
1453 /// if (limit) {
1454 /// unsigned long startMutations = *enumState.mutationsPtr;
1455 /// do {
1456 /// unsigned long counter = 0;
1457 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001458 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001459 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001460 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001461 buf += "if (limit) {\n\t";
1462 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1463 buf += "do {\n\t\t";
1464 buf += "unsigned long counter = 0;\n\t\t";
1465 buf += "do {\n\t\t\t";
1466 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1467 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1468 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001469 buf += " = (";
1470 buf += elementTypeAsString;
1471 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001472 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001473 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001474
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001475 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001476 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001477 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001478 /// objects:items count:16]);
1479 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001480 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481 /// }
1482 /// else
1483 /// elem = nil;
1484 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001485 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001486 buf = ";\n\t";
1487 buf += "__continue_label_";
1488 buf += utostr(ObjCBcLabelNo.back());
1489 buf += ": ;";
1490 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001491 buf += "} while (counter < limit);\n\t";
1492 buf += "} while (limit = ";
1493 SynthCountByEnumWithState(buf);
1494 buf += ");\n\t";
1495 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001496 buf += " = ((";
1497 buf += elementTypeAsString;
1498 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001499 buf += "__break_label_";
1500 buf += utostr(ObjCBcLabelNo.back());
1501 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001502 buf += "}\n\t";
1503 buf += "else\n\t\t";
1504 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001505 buf += " = ((";
1506 buf += elementTypeAsString;
1507 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001508 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001509
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001510 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001511 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001512 if (isa<CompoundStmt>(S->getBody())) {
1513 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1514 InsertText(endBodyLoc, buf.c_str(), buf.size());
1515 } else {
1516 /* Need to treat single statements specially. For example:
1517 *
1518 * for (A *a in b) if (stuff()) break;
1519 * for (A *a in b) xxxyy;
1520 *
1521 * The following code simply scans ahead to the semi to find the actual end.
1522 */
1523 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1524 const char *semiBuf = strchr(stmtBuf, ';');
1525 assert(semiBuf && "Can't find ';'");
1526 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1527 InsertText(endBodyLoc, buf.c_str(), buf.size());
1528 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001529 Stmts.pop_back();
1530 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001531 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001532}
1533
Mike Stump11289f42009-09-09 15:08:12 +00001534/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001535/// This routine rewrites @synchronized(expr) stmt;
1536/// into:
1537/// objc_sync_enter(expr);
1538/// @try stmt @finally { objc_sync_exit(expr); }
1539///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001540Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001541 // Get the start location and compute the semi location.
1542 SourceLocation startLoc = S->getLocStart();
1543 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001544
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001545 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001546
1547 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001548 buf = "objc_sync_enter((id)";
1549 const char *lparenBuf = startBuf;
1550 while (*lparenBuf != '(') lparenBuf++;
1551 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001552 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1553 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001554 // been rewritten! (which implies the SourceLocation's are invalid).
1555 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001556 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001557 while (*endBuf != ')') endBuf--;
1558 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001559 buf = ");\n";
1560 // declare a new scope with two variables, _stack and _rethrow.
1561 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1562 buf += "int buf[18/*32-bit i386*/];\n";
1563 buf += "char *pointers[4];} _stack;\n";
1564 buf += "id volatile _rethrow = 0;\n";
1565 buf += "objc_exception_try_enter(&_stack);\n";
1566 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001567 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001568 startLoc = S->getSynchBody()->getLocEnd();
1569 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001570
Steve Naroffad7013b2008-08-19 13:04:19 +00001571 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001572 SourceLocation lastCurlyLoc = startLoc;
1573 buf = "}\nelse {\n";
1574 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001575 buf += "}\n";
1576 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001577 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001578
1579 std::string syncBuf;
1580 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001581 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001582 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001583 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001584 Context->getObjCIdType(),
1585 SourceLocation(),
1586 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001587 std::string syncExprBufS;
1588 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001589 syncExpr->printPretty(syncExprBuf, *Context, 0,
1590 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001591 syncBuf += syncExprBuf.str();
1592 syncBuf += ");";
1593
1594 buf += syncBuf;
1595 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001596 buf += "}\n";
1597 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001598
Chris Lattner9cc55f52008-01-31 19:51:04 +00001599 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001600
1601 bool hasReturns = false;
1602 HasReturnStmts(S->getSynchBody(), hasReturns);
1603 if (hasReturns)
1604 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1605
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001606 return 0;
1607}
1608
Steve Naroffec60b432009-12-05 21:43:12 +00001609void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1610{
Steve Naroff6d6da252008-12-05 17:03:39 +00001611 // Perform a bottom up traversal of all children.
1612 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1613 CI != E; ++CI)
1614 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001615 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001616
Steve Naroffec60b432009-12-05 21:43:12 +00001617 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001618 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001619 TryFinallyContainsReturnDiag);
1620 }
1621 return;
1622}
1623
Steve Naroffec60b432009-12-05 21:43:12 +00001624void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1625{
1626 // Perform a bottom up traversal of all children.
1627 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1628 CI != E; ++CI)
1629 if (*CI)
1630 HasReturnStmts(*CI, hasReturns);
1631
1632 if (isa<ReturnStmt>(S))
1633 hasReturns = true;
1634 return;
1635}
1636
1637void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1638 // Perform a bottom up traversal of all children.
1639 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1640 CI != E; ++CI)
1641 if (*CI) {
1642 RewriteTryReturnStmts(*CI);
1643 }
1644 if (isa<ReturnStmt>(S)) {
1645 SourceLocation startLoc = S->getLocStart();
1646 const char *startBuf = SM->getCharacterData(startLoc);
1647
1648 const char *semiBuf = strchr(startBuf, ';');
1649 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1650 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1651
1652 std::string buf;
1653 buf = "{ objc_exception_try_exit(&_stack); return";
1654
1655 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1656 InsertText(onePastSemiLoc, "}", 1);
1657 }
1658 return;
1659}
1660
1661void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1662 // Perform a bottom up traversal of all children.
1663 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1664 CI != E; ++CI)
1665 if (*CI) {
1666 RewriteSyncReturnStmts(*CI, syncExitBuf);
1667 }
1668 if (isa<ReturnStmt>(S)) {
1669 SourceLocation startLoc = S->getLocStart();
1670 const char *startBuf = SM->getCharacterData(startLoc);
1671
1672 const char *semiBuf = strchr(startBuf, ';');
1673 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1674 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1675
1676 std::string buf;
1677 buf = "{ objc_exception_try_exit(&_stack);";
1678 buf += syncExitBuf;
1679 buf += " return";
1680
1681 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1682 InsertText(onePastSemiLoc, "}", 1);
1683 }
1684 return;
1685}
1686
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001687Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001688 // Get the start location and compute the semi location.
1689 SourceLocation startLoc = S->getLocStart();
1690 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Steve Naroffbf478ec2007-11-07 04:08:17 +00001692 assert((*startBuf == '@') && "bogus @try location");
1693
1694 std::string buf;
1695 // declare a new scope with two variables, _stack and _rethrow.
1696 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1697 buf += "int buf[18/*32-bit i386*/];\n";
1698 buf += "char *pointers[4];} _stack;\n";
1699 buf += "id volatile _rethrow = 0;\n";
1700 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001701 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001702
Chris Lattner9cc55f52008-01-31 19:51:04 +00001703 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001704
Steve Naroffbf478ec2007-11-07 04:08:17 +00001705 startLoc = S->getTryBody()->getLocEnd();
1706 startBuf = SM->getCharacterData(startLoc);
1707
1708 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001709
Steve Naroffbf478ec2007-11-07 04:08:17 +00001710 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001711 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1712 if (catchList) {
1713 startLoc = startLoc.getFileLocWithOffset(1);
1714 buf = " /* @catch begin */ else {\n";
1715 buf += " id _caught = objc_exception_extract(&_stack);\n";
1716 buf += " objc_exception_try_enter (&_stack);\n";
1717 buf += " if (_setjmp(_stack.buf))\n";
1718 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1719 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001720
Steve Naroffce2dca12008-07-16 15:31:30 +00001721 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001722 } else { /* no catch list */
1723 buf = "}\nelse {\n";
1724 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1725 buf += "}";
1726 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001727 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001728 bool sawIdTypedCatch = false;
1729 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001730 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001731 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001732
Mike Stump11289f42009-09-09 15:08:12 +00001733 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001734 buf = "if ("; // we are generating code for the first catch clause
1735 else
1736 buf = "else if (";
1737 startLoc = catchList->getLocStart();
1738 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001739
Steve Naroffbf478ec2007-11-07 04:08:17 +00001740 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001741
Steve Naroffbf478ec2007-11-07 04:08:17 +00001742 const char *lParenLoc = strchr(startBuf, '(');
1743
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001744 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001745 // Now rewrite the body...
1746 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001747 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1748 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001749 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1750 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001751 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001752
Steve Naroffedb5bc62008-02-01 20:02:07 +00001753 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001754 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001755 } else if (catchDecl) {
1756 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001757 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001758 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001759 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001760 sawIdTypedCatch = true;
Fariborz Jahanian59516092010-01-12 01:22:23 +00001761 } else if (t->isObjCObjectPointerType()) {
1762 QualType InterfaceTy = t->getPointeeType();
1763 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1764 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001765 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001766 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001767 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001768 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001769 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001770 }
1771 }
1772 // Now rewrite the body...
1773 lastCatchBody = catchList->getCatchBody();
1774 SourceLocation rParenLoc = catchList->getRParenLoc();
1775 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1776 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1777 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1778 assert((*rParenBuf == ')') && "bogus @catch paren location");
1779 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001780
Steve Naroffbf478ec2007-11-07 04:08:17 +00001781 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001782 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001783 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001784 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001785 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001786 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001787 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001788 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001789 catchList = catchList->getNextCatchStmt();
1790 }
1791 // Complete the catch list...
1792 if (lastCatchBody) {
1793 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001794 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1795 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001796
Steve Naroff4adbe312008-09-11 15:29:03 +00001797 // Insert the last (implicit) else clause *before* the right curly brace.
1798 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1799 buf = "} /* last catch end */\n";
1800 buf += "else {\n";
1801 buf += " _rethrow = _caught;\n";
1802 buf += " objc_exception_try_exit(&_stack);\n";
1803 buf += "} } /* @catch end */\n";
1804 if (!S->getFinallyStmt())
1805 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001806 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001807
Steve Naroffbf478ec2007-11-07 04:08:17 +00001808 // Set lastCurlyLoc
1809 lastCurlyLoc = lastCatchBody->getLocEnd();
1810 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001811 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001812 startLoc = finalStmt->getLocStart();
1813 startBuf = SM->getCharacterData(startLoc);
1814 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001815
Steve Naroffbf478ec2007-11-07 04:08:17 +00001816 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001817 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001818
Steve Naroffbf478ec2007-11-07 04:08:17 +00001819 Stmt *body = finalStmt->getFinallyBody();
1820 SourceLocation startLoc = body->getLocStart();
1821 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001822 assert(*SM->getCharacterData(startLoc) == '{' &&
1823 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001824 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001825 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001826
Steve Naroffbf478ec2007-11-07 04:08:17 +00001827 startLoc = startLoc.getFileLocWithOffset(1);
1828 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001829 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001830 endLoc = endLoc.getFileLocWithOffset(-1);
1831 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001832 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001833
Steve Naroffbf478ec2007-11-07 04:08:17 +00001834 // Set lastCurlyLoc
1835 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001836
Steve Naroff6d6da252008-12-05 17:03:39 +00001837 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001838 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001839 } else { /* no finally clause - make sure we synthesize an implicit one */
1840 buf = "{ /* implicit finally clause */\n";
1841 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1842 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1843 buf += "}";
1844 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001845
1846 // Now check for any return/continue/go statements within the @try.
1847 // The implicit finally clause won't called if the @try contains any
1848 // jump statements.
1849 bool hasReturns = false;
1850 HasReturnStmts(S->getTryBody(), hasReturns);
1851 if (hasReturns)
1852 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001853 }
1854 // Now emit the final closing curly brace...
1855 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1856 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001857 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001858 return 0;
1859}
1860
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001861Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001862 return 0;
1863}
1864
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001865Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001866 return 0;
1867}
1868
Mike Stump11289f42009-09-09 15:08:12 +00001869// This can't be done with ReplaceStmt(S, ThrowExpr), since
1870// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001871// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001872Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001873 // Get the start location and compute the semi location.
1874 SourceLocation startLoc = S->getLocStart();
1875 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001876
Steve Naroffa733c7f2007-11-07 15:32:26 +00001877 assert((*startBuf == '@') && "bogus @throw location");
1878
1879 std::string buf;
1880 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001881 if (S->getThrowExpr())
1882 buf = "objc_exception_throw(";
1883 else // add an implicit argument
1884 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001885
Steve Naroff29788342008-07-25 15:41:30 +00001886 // handle "@ throw" correctly.
1887 const char *wBuf = strchr(startBuf, 'w');
1888 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1889 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001890
Steve Naroffa733c7f2007-11-07 15:32:26 +00001891 const char *semiBuf = strchr(startBuf, ';');
1892 assert((*semiBuf == ';') && "@throw: can't find ';'");
1893 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1894 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001895 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001896 return 0;
1897}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001898
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001899Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001900 // Create a new string expression.
1901 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001902 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001903 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001904 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1905 StrEncoding.length(), false,StrType,
1906 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001907 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001908
Chris Lattner4431a1b2007-11-30 22:53:43 +00001909 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001910 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001911 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001912}
1913
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001914Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001915 if (!SelGetUidFunctionDecl)
1916 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001917 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1918 // Create a call to sel_registerName("selName").
1919 llvm::SmallVector<Expr*, 8> SelExprs;
1920 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001921 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001922 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001923 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001924 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001925 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1926 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001927 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001928 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001929 return SelExp;
1930}
1931
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001932CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001933 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001934 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001935 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001936
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001937 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001938 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001939
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001940 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001941 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001942 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001943 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001944 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001945 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001946
John McCall9dd450b2009-09-21 23:43:11 +00001947 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001948
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001949 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1950 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001951}
1952
Steve Naroff50d42052007-11-01 13:24:47 +00001953static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1954 const char *&startRef, const char *&endRef) {
1955 while (startBuf < endBuf) {
1956 if (*startBuf == '<')
1957 startRef = startBuf; // mark the start.
1958 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001959 if (startRef && *startRef == '<') {
1960 endRef = startBuf; // mark the end.
1961 return true;
1962 }
1963 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001964 }
1965 startBuf++;
1966 }
1967 return false;
1968}
1969
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001970static void scanToNextArgument(const char *&argRef) {
1971 int angle = 0;
1972 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1973 if (*argRef == '<')
1974 angle++;
1975 else if (*argRef == '>')
1976 angle--;
1977 argRef++;
1978 }
1979 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1980}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001981
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001982bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001983 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001984}
1985
Steve Naroff873bd842008-07-29 18:15:38 +00001986void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1987 QualType Type = E->getType();
1988 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001989 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001990
Steve Naroffdbfc6932008-11-19 21:15:47 +00001991 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1992 Loc = ECE->getLParenLoc();
1993 EndLoc = ECE->getRParenLoc();
1994 } else {
1995 Loc = E->getLocStart();
1996 EndLoc = E->getLocEnd();
1997 }
1998 // This will defend against trying to rewrite synthesized expressions.
1999 if (Loc.isInvalid() || EndLoc.isInvalid())
2000 return;
2001
Steve Naroff873bd842008-07-29 18:15:38 +00002002 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002003 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002004 const char *startRef = 0, *endRef = 0;
2005 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2006 // Get the locations of the startRef, endRef.
2007 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2008 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2009 // Comment out the protocol references.
2010 InsertText(LessLoc, "/*", 2);
2011 InsertText(GreaterLoc, "*/", 2);
2012 }
2013 }
2014}
2015
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002016void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002017 SourceLocation Loc;
2018 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002019 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002020 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2021 Loc = VD->getLocation();
2022 Type = VD->getType();
2023 }
2024 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2025 Loc = FD->getLocation();
2026 // Check for ObjC 'id' and class types that have been adorned with protocol
2027 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002028 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002029 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002030 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002031 if (!proto)
2032 return;
2033 Type = proto->getResultType();
2034 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002035 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2036 Loc = FD->getLocation();
2037 Type = FD->getType();
2038 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002039 else
2040 return;
Mike Stump11289f42009-09-09 15:08:12 +00002041
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002042 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002043 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002044
Steve Naroff50d42052007-11-01 13:24:47 +00002045 const char *endBuf = SM->getCharacterData(Loc);
2046 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002047 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002048 startBuf--; // scan backward (from the decl location) for return type.
2049 const char *startRef = 0, *endRef = 0;
2050 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2051 // Get the locations of the startRef, endRef.
2052 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2053 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2054 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002055 InsertText(LessLoc, "/*", 2);
2056 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002057 }
2058 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002059 if (!proto)
2060 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002061 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002062 const char *startBuf = SM->getCharacterData(Loc);
2063 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002064 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2065 if (needToScanForQualifiers(proto->getArgType(i))) {
2066 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002067
Steve Naroff50d42052007-11-01 13:24:47 +00002068 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002069 // scan forward (from the decl location) for argument types.
2070 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002071 const char *startRef = 0, *endRef = 0;
2072 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2073 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002074 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002075 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002076 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002077 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002078 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002079 InsertText(LessLoc, "/*", 2);
2080 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002081 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002082 startBuf = ++endBuf;
2083 }
2084 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002085 // If the function name is derived from a macro expansion, then the
2086 // argument buffer will not follow the name. Need to speak with Chris.
2087 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002088 startBuf++; // scan forward (from the decl location) for argument types.
2089 startBuf++;
2090 }
Steve Naroff50d42052007-11-01 13:24:47 +00002091 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002092}
2093
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002094// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002095void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002096 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2097 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002098 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002099 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002100 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002101 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002102 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002103 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002104 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002105 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002106}
2107
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002108void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002109 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002110 if (FD->getIdentifier() &&
2111 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002112 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002113 return;
2114 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002115 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002116}
2117
Steve Naroff17978c42008-03-11 17:37:02 +00002118// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002119void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002120 if (SuperContructorFunctionDecl)
2121 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002122 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002123 llvm::SmallVector<QualType, 16> ArgTys;
2124 QualType argT = Context->getObjCIdType();
2125 assert(!argT.isNull() && "Can't find 'id' type");
2126 ArgTys.push_back(argT);
2127 ArgTys.push_back(argT);
2128 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2129 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002130 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002131 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002132 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002133 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002134 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002135}
2136
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002137// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002138void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002139 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2140 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002141 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002142 assert(!argT.isNull() && "Can't find 'id' type");
2143 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002144 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002145 assert(!argT.isNull() && "Can't find 'SEL' type");
2146 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002147 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002148 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002149 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002150 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002151 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002152 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002153 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002154}
2155
Steve Naroff7fa2f042007-11-15 10:28:18 +00002156// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002157void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002158 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2159 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002160 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002161 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002162 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002163 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2164 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2165 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002166 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002167 assert(!argT.isNull() && "Can't find 'SEL' type");
2168 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002169 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002170 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002171 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002172 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002173 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002174 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002175 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002176}
2177
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002178// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002179void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002180 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2181 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002182 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002183 assert(!argT.isNull() && "Can't find 'id' type");
2184 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002185 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002186 assert(!argT.isNull() && "Can't find 'SEL' type");
2187 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002188 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002189 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002190 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002191 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002192 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002193 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002194 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002195}
2196
Mike Stump11289f42009-09-09 15:08:12 +00002197// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002198// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002199void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002200 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002201 &Context->Idents.get("objc_msgSendSuper_stret");
2202 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002203 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002204 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002205 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002206 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2207 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2208 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002209 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002210 assert(!argT.isNull() && "Can't find 'SEL' type");
2211 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002212 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002213 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002214 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002215 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002216 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002217 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002218 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002219}
2220
Steve Naroff2e4e3852008-05-08 22:02:18 +00002221// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002222void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002223 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2224 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002225 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002226 assert(!argT.isNull() && "Can't find 'id' type");
2227 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002228 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002229 assert(!argT.isNull() && "Can't find 'SEL' type");
2230 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002231 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002232 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002233 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002234 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002235 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002236 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002237 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002238}
2239
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002240// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002241void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002242 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
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 Naroff5cdcd9b2007-10-30 23:14:51 +00002246 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002247 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002248 GetClassFunctionDecl = 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 Naroff5cdcd9b2007-10-30 23:14:51 +00002252}
2253
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002254// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002255void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002256 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2257 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002258 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002259 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002260 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002261 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002262 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002263 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002264 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002265 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002266}
2267
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002268Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002269 QualType strType = getConstantStringStructType();
2270
2271 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002272
2273 std::string tmpName = InFileName;
2274 unsigned i;
2275 for (i=0; i < tmpName.length(); i++) {
2276 char c = tmpName.at(i);
2277 // replace any non alphanumeric characters with '_'.
2278 if (!isalpha(c) && (c < '0' || c > '9'))
2279 tmpName[i] = '_';
2280 }
2281 S += tmpName;
2282 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002283 S += utostr(NumObjCStringLiterals++);
2284
Steve Naroff00a31762008-03-27 22:29:16 +00002285 Preamble += "static __NSConstantStringImpl " + S;
2286 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2287 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002288 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002289 std::string prettyBufS;
2290 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002291 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2292 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002293 Preamble += prettyBuf.str();
2294 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002295 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002296
2297 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2298 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002299 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002300 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2301 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002302 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002303 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002304 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002305 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002306 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002307 Unop, Exp->getType(),
2308 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002309 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002310 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002311 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002312 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002313}
2314
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002315ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002316 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002317 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002318
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002319 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002320 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002321 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002322 assert(OPT);
2323 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002324 return IT->getDecl();
2325 }
2326 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002327}
2328
2329// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002330QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002331 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002332 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002333 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002334 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002335 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002336
Steve Naroff7fa2f042007-11-15 10:28:18 +00002337 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002338 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002339 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002340 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002341
Steve Naroff7fa2f042007-11-15 10:28:18 +00002342 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002343 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002344 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2345 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002346 FieldTypes[i], 0,
2347 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002348 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002349 }
Mike Stump11289f42009-09-09 15:08:12 +00002350
Douglas Gregor91f84212008-12-11 16:49:14 +00002351 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002352 }
2353 return Context->getTagDeclType(SuperStructDecl);
2354}
2355
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002356QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002357 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002358 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002359 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002360 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002361 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002362
Steve Naroffce8e8862008-03-15 00:55:56 +00002363 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002364 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002365 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002366 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002367 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002368 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002369 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002370 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002371
Steve Naroffce8e8862008-03-15 00:55:56 +00002372 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002373 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002374 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2375 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002376 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002377 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002378 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002379 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002380 }
2381
2382 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002383 }
2384 return Context->getTagDeclType(ConstantStringDecl);
2385}
2386
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002387Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002388 if (!SelGetUidFunctionDecl)
2389 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002390 if (!MsgSendFunctionDecl)
2391 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002392 if (!MsgSendSuperFunctionDecl)
2393 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002394 if (!MsgSendStretFunctionDecl)
2395 SynthMsgSendStretFunctionDecl();
2396 if (!MsgSendSuperStretFunctionDecl)
2397 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002398 if (!MsgSendFpretFunctionDecl)
2399 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002400 if (!GetClassFunctionDecl)
2401 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002402 if (!GetMetaClassFunctionDecl)
2403 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002404
Steve Naroff7fa2f042007-11-15 10:28:18 +00002405 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002406 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2407 // May need to use objc_msgSend_stret() as well.
2408 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002409 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2410 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002411 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002412 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002413 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002414 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002415 }
Mike Stump11289f42009-09-09 15:08:12 +00002416
Steve Naroff574440f2007-10-24 22:48:43 +00002417 // Synthesize a call to objc_msgSend().
2418 llvm::SmallVector<Expr*, 8> MsgExprs;
2419 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002420
Steve Naroff574440f2007-10-24 22:48:43 +00002421 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2422 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002423 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2424 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002425 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002426 MsgSendFlavor = MsgSendSuperFunctionDecl;
2427 if (MsgSendStretFlavor)
2428 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2429 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002430
2431 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002432 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002433
2434 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002435
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002436 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002437 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002438 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002439 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002440 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002441 Context->getObjCIdType(),
2442 SourceLocation()),
2443 Context->getObjCIdType(),
2444 SourceLocation(), SourceLocation())); // set the 'receiver'.
2445
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002446 llvm::SmallVector<Expr*, 8> ClsExprs;
2447 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002448 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002449 SuperDecl->getIdentifier()->getNameStart(),
2450 SuperDecl->getIdentifier()->getLength(),
2451 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002452 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002453 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002454 ClsExprs.size());
2455 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002456 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002457 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002458 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002459 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002460 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002461 // struct objc_super
2462 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002463 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002464
Steve Naroff0b844f02008-03-11 18:14:26 +00002465 if (LangOpts.Microsoft) {
2466 SynthSuperContructorFunctionDecl();
2467 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002468 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002469 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002470 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002471 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002472 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002473 // The code for super is a little tricky to prevent collision with
2474 // the structure definition in the header. The rewriter has it's own
2475 // internal definition (__rw_objc_super) that is uses. This is why
2476 // we need the cast below. For example:
2477 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2478 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002479 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002480 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002481 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002482 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2483 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002484 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002485 SourceLocation(), SourceLocation());
2486 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002487 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002488 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2489 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002490 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002491 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002492 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002493 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002494 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002495 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002496 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002497 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002498 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002499 } else {
2500 llvm::SmallVector<Expr*, 8> ClsExprs;
2501 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002502 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002503 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002504 clsName->getLength(),
2505 false, argType,
2506 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002507 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002508 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002509 ClsExprs.size());
2510 MsgExprs.push_back(Cls);
2511 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002512 } else { // instance message.
2513 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002514
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002515 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002516 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002517 if (MsgSendStretFlavor)
2518 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002519 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002520
Steve Naroff7fa2f042007-11-15 10:28:18 +00002521 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002522
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002523 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002524 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002525 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002526 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002527 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002528 SourceLocation()),
2529 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002530 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002531
Steve Naroff7fa2f042007-11-15 10:28:18 +00002532 llvm::SmallVector<Expr*, 8> ClsExprs;
2533 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002534 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002535 SuperDecl->getIdentifier()->getNameStart(),
2536 SuperDecl->getIdentifier()->getLength(),
2537 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002538 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002539 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002540 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002541 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002542 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002543 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002544 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002545 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002546 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002547 // struct objc_super
2548 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002549 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002550
Steve Naroff17978c42008-03-11 17:37:02 +00002551 if (LangOpts.Microsoft) {
2552 SynthSuperContructorFunctionDecl();
2553 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002554 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002555 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002556 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002557 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002558 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002559 // The code for super is a little tricky to prevent collision with
2560 // the structure definition in the header. The rewriter has it's own
2561 // internal definition (__rw_objc_super) that is uses. This is why
2562 // we need the cast below. For example:
2563 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2564 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002565 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002566 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002567 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002568 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002569 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002570 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002571 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002572 } else {
2573 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002574 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2575 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002576 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002577 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002578 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002579 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002580 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002581 // Remove all type-casts because it may contain objc-style types; e.g.
2582 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002583 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002584 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002585 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002586 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002587 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002588 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002589 MsgExprs.push_back(recExpr);
2590 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002591 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002592 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002593 llvm::SmallVector<Expr*, 8> SelExprs;
2594 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002595 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002596 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002597 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002598 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002599 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2600 &SelExprs[0], SelExprs.size());
2601 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002602
Steve Naroff574440f2007-10-24 22:48:43 +00002603 // Now push any user supplied arguments.
2604 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002605 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002606 // Make all implicit casts explicit...ICE comes in handy:-)
2607 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2608 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002609 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002610 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002611 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002612 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002613 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002614 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002615 }
2616 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002617 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002618 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002619 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002620 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002621 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002622 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002623 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002624 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002625 }
Mike Stump11289f42009-09-09 15:08:12 +00002626 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002627 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002628 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2629 // out the argument in the original expression (since we aren't deleting
2630 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2631 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002632 }
Steve Narofff36987c2007-11-04 22:37:50 +00002633 // Generate the funky cast.
2634 CastExpr *cast;
2635 llvm::SmallVector<QualType, 8> ArgTypes;
2636 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002637
Steve Narofff36987c2007-11-04 22:37:50 +00002638 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002639 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2640 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2641 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002642 ArgTypes.push_back(Context->getObjCIdType());
2643 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002644 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002645 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002646 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2647 E = OMD->param_end(); PI != E; ++PI) {
2648 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002649 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002650 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002651 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002652 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002653 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002654 t = Context->getPointerType(BPT->getPointeeType());
2655 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002656 ArgTypes.push_back(t);
2657 }
Chris Lattnera4997152009-02-20 18:43:26 +00002658 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2659 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002660 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002661 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002662 }
2663 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002664 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002665
Steve Narofff36987c2007-11-04 22:37:50 +00002666 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002667 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002668 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002669
Mike Stump11289f42009-09-09 15:08:12 +00002670 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002671 // If we don't do this cast, we get the following bizarre warning/note:
2672 // xx.m:13: warning: function called through a non-compatible type
2673 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002674 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2675 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002676 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002677 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002678
Steve Narofff36987c2007-11-04 22:37:50 +00002679 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002680 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002681 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002682 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002683 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002684 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002685 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2686 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002687 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002688
2689 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002690 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002691
John McCall9dd450b2009-09-21 23:43:11 +00002692 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002693 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002694 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002695 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002696 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002697 if (MsgSendStretFlavor) {
2698 // We have the method which returns a struct/union. Must also generate
2699 // call to objc_msgSend_stret and hang both varieties on a conditional
2700 // expression which dictate which one to envoke depending on size of
2701 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002702
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002703 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002704 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002705 SourceLocation());
2706 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002707 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2708 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002709 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002710 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002711 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002712 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002713 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002714 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002715 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002716 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2717 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002718
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002719 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002720 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002721
John McCall9dd450b2009-09-21 23:43:11 +00002722 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002723 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002724 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002725 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002726
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002727 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002728 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002729 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002730 Context->getSizeType(),
2731 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002732 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2733 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2734 // For X86 it is more complicated and some kind of target specific routine
2735 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002736 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002737 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002738 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002739 Context->IntTy,
2740 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002741 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2742 BinaryOperator::LE,
2743 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002744 SourceLocation());
2745 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002746 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002747 new (Context) ConditionalOperator(lessThanExpr,
2748 SourceLocation(), CE,
2749 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002750 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002751 }
Mike Stump11289f42009-09-09 15:08:12 +00002752 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002753 return ReplacingStmt;
2754}
2755
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002756Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002757 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002758
Steve Naroff574440f2007-10-24 22:48:43 +00002759 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002760 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002761
2762 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002763 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002764}
2765
Steve Naroffd9803712009-04-29 16:37:50 +00002766// typedef struct objc_object Protocol;
2767QualType RewriteObjC::getProtocolType() {
2768 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002769 TypeSourceInfo *TInfo
2770 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002771 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002772 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002773 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002774 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002775 }
2776 return Context->getTypeDeclType(ProtocolTypeDecl);
2777}
2778
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002779/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002780/// a synthesized/forward data reference (to the protocol's metadata).
2781/// The forward references (and metadata) are generated in
2782/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002783Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002784 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2785 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002786 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002787 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002788 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2789 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2790 Context->getPointerType(DRE->getType()),
2791 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002792 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2793 CastExpr::CK_Unknown,
2794 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002795 SourceLocation(), SourceLocation());
2796 ReplaceStmt(Exp, castExpr);
2797 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002798 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002799 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002800
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002801}
2802
Mike Stump11289f42009-09-09 15:08:12 +00002803bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002804 const char *endBuf) {
2805 while (startBuf < endBuf) {
2806 if (*startBuf == '#') {
2807 // Skip whitespace.
2808 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2809 ;
2810 if (!strncmp(startBuf, "if", strlen("if")) ||
2811 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2812 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2813 !strncmp(startBuf, "define", strlen("define")) ||
2814 !strncmp(startBuf, "undef", strlen("undef")) ||
2815 !strncmp(startBuf, "else", strlen("else")) ||
2816 !strncmp(startBuf, "elif", strlen("elif")) ||
2817 !strncmp(startBuf, "endif", strlen("endif")) ||
2818 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2819 !strncmp(startBuf, "include", strlen("include")) ||
2820 !strncmp(startBuf, "import", strlen("import")) ||
2821 !strncmp(startBuf, "include_next", strlen("include_next")))
2822 return true;
2823 }
2824 startBuf++;
2825 }
2826 return false;
2827}
2828
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002829/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002830/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002831void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002832 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002833 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002834 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002835 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002836 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002837 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002838 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002839 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002840 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002841 SourceLocation LocStart = CDecl->getLocStart();
2842 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002843
Steve Naroffdde78982007-11-14 19:25:57 +00002844 const char *startBuf = SM->getCharacterData(LocStart);
2845 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002846
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002847 // If no ivars and no root or if its root, directly or indirectly,
2848 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002849 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2850 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002851 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002852 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002853 return;
2854 }
Mike Stump11289f42009-09-09 15:08:12 +00002855
2856 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002857 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002858 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002859 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002860 if (LangOpts.Microsoft)
2861 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002862
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002863 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002864 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002865 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002866 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002867 // If the buffer contains preprocessor directives, we do more fine-grained
2868 // rewrites. This is intended to fix code that looks like (which occurs in
2869 // NSURL.h, for example):
2870 //
2871 // #ifdef XYZ
2872 // @interface Foo : NSObject
2873 // #else
2874 // @interface FooBar : NSObject
2875 // #endif
2876 // {
2877 // int i;
2878 // }
2879 // @end
2880 //
2881 // This clause is segregated to avoid breaking the common case.
2882 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002883 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002884 CDecl->getClassLoc();
2885 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002886 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002887
Chris Lattnerf5b77512009-02-20 18:18:36 +00002888 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002889 // advance to the end of the referenced protocols.
2890 while (endHeader < cursor && *endHeader != '>') endHeader++;
2891 endHeader++;
2892 }
2893 // rewrite the original header
2894 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2895 } else {
2896 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002897 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002898 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002899 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002900 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002901 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002902 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002903 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002904 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002905
Steve Naroffdde78982007-11-14 19:25:57 +00002906 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002907 SourceLocation OnePastCurly =
2908 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2909 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002910 }
2911 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002912
Steve Naroffdde78982007-11-14 19:25:57 +00002913 // Now comment out any visibility specifiers.
2914 while (cursor < endBuf) {
2915 if (*cursor == '@') {
2916 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002917 // Skip whitespace.
2918 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2919 /*scan*/;
2920
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002921 // FIXME: presence of @public, etc. inside comment results in
2922 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002923 if (!strncmp(cursor, "public", strlen("public")) ||
2924 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002925 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002926 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002927 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002928 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002929 // FIXME: If there are cases where '<' is used in ivar declaration part
2930 // of user code, then scan the ivar list and use needToScanForQualifiers
2931 // for type checking.
2932 else if (*cursor == '<') {
2933 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002934 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002935 cursor = strchr(cursor, '>');
2936 cursor++;
2937 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002938 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002939 } else if (*cursor == '^') { // rewrite block specifier.
2940 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2941 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002942 }
Steve Naroffdde78982007-11-14 19:25:57 +00002943 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002944 }
Steve Naroffdde78982007-11-14 19:25:57 +00002945 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002946 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002947 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002948 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002949 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002950 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002951 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002952 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002953 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002954 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002955 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002956 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002957 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002958 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002959}
2960
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002961// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002962/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002963template<typename MethodIterator>
2964void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2965 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002966 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002967 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002968 const char *ClassName,
2969 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002970 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002971
Chris Lattner31bc07e2007-12-12 07:46:12 +00002972 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002973 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002974 SEL _cmd;
2975 char *method_types;
2976 void *_imp;
2977 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002978 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002979 Result += "\nstruct _objc_method {\n";
2980 Result += "\tSEL _cmd;\n";
2981 Result += "\tchar *method_types;\n";
2982 Result += "\tvoid *_imp;\n";
2983 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002984
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002985 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002986 }
Mike Stump11289f42009-09-09 15:08:12 +00002987
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002988 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002989
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002990 /* struct {
2991 struct _objc_method_list *next_method;
2992 int method_count;
2993 struct _objc_method method_list[];
2994 }
2995 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002996 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002997 Result += "\nstatic struct {\n";
2998 Result += "\tstruct _objc_method_list *next_method;\n";
2999 Result += "\tint method_count;\n";
3000 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003001 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003002 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003003 Result += prefix;
3004 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3005 Result += "_METHODS_";
3006 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00003007 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003008 Result += IsInstanceMethod ? "inst" : "cls";
3009 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003010 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003011
Chris Lattner31bc07e2007-12-12 07:46:12 +00003012 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003013 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00003014 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003015 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00003016 Result += "\", \"";
3017 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003018 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003019 Result += MethodInternalNames[*MethodBegin];
3020 Result += "}\n";
3021 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3022 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003023 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003024 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003025 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003026 Result += "\", \"";
3027 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003028 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003029 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003030 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003031 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003032 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003033}
3034
Steve Naroffd9803712009-04-29 16:37:50 +00003035/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003036void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003037RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3038 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003039 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003040
3041 // Output struct protocol_methods holder of method selector and type.
3042 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3043 /* struct protocol_methods {
3044 SEL _cmd;
3045 char *method_types;
3046 }
3047 */
3048 Result += "\nstruct _protocol_methods {\n";
3049 Result += "\tstruct objc_selector *_cmd;\n";
3050 Result += "\tchar *method_types;\n";
3051 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003052
Steve Naroffd9803712009-04-29 16:37:50 +00003053 objc_protocol_methods = true;
3054 }
3055 // Do not synthesize the protocol more than once.
3056 if (ObjCSynthesizedProtocols.count(PDecl))
3057 return;
Mike Stump11289f42009-09-09 15:08:12 +00003058
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003059 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3060 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3061 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003062 /* struct _objc_protocol_method_list {
3063 int protocol_method_count;
3064 struct protocol_methods protocols[];
3065 }
Steve Naroff251084d2008-03-12 01:06:30 +00003066 */
Steve Naroffd9803712009-04-29 16:37:50 +00003067 Result += "\nstatic struct {\n";
3068 Result += "\tint protocol_method_count;\n";
3069 Result += "\tstruct _protocol_methods protocol_methods[";
3070 Result += utostr(NumMethods);
3071 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3072 Result += PDecl->getNameAsString();
3073 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3074 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003075
Steve Naroffd9803712009-04-29 16:37:50 +00003076 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003077 for (ObjCProtocolDecl::instmeth_iterator
3078 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003079 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003080 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003081 Result += "\t ,{{(struct objc_selector *)\"";
3082 else
3083 Result += "\t ,{(struct objc_selector *)\"";
3084 Result += (*I)->getSelector().getAsString().c_str();
3085 std::string MethodTypeString;
3086 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3087 Result += "\", \"";
3088 Result += MethodTypeString;
3089 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003090 }
Steve Naroffd9803712009-04-29 16:37:50 +00003091 Result += "\t }\n};\n";
3092 }
Mike Stump11289f42009-09-09 15:08:12 +00003093
Steve Naroffd9803712009-04-29 16:37:50 +00003094 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003095 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3096 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003097 if (NumMethods > 0) {
3098 /* struct _objc_protocol_method_list {
3099 int protocol_method_count;
3100 struct protocol_methods protocols[];
3101 }
3102 */
3103 Result += "\nstatic struct {\n";
3104 Result += "\tint protocol_method_count;\n";
3105 Result += "\tstruct _protocol_methods protocol_methods[";
3106 Result += utostr(NumMethods);
3107 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3108 Result += PDecl->getNameAsString();
3109 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3110 "{\n\t";
3111 Result += utostr(NumMethods);
3112 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003113
Steve Naroffd9803712009-04-29 16:37:50 +00003114 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003115 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003116 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003117 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003118 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003119 Result += "\t ,{{(struct objc_selector *)\"";
3120 else
3121 Result += "\t ,{(struct objc_selector *)\"";
3122 Result += (*I)->getSelector().getAsString().c_str();
3123 std::string MethodTypeString;
3124 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3125 Result += "\", \"";
3126 Result += MethodTypeString;
3127 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003128 }
Steve Naroffd9803712009-04-29 16:37:50 +00003129 Result += "\t }\n};\n";
3130 }
3131
3132 // Output:
3133 /* struct _objc_protocol {
3134 // Objective-C 1.0 extensions
3135 struct _objc_protocol_extension *isa;
3136 char *protocol_name;
3137 struct _objc_protocol **protocol_list;
3138 struct _objc_protocol_method_list *instance_methods;
3139 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003140 };
Steve Naroffd9803712009-04-29 16:37:50 +00003141 */
3142 static bool objc_protocol = false;
3143 if (!objc_protocol) {
3144 Result += "\nstruct _objc_protocol {\n";
3145 Result += "\tstruct _objc_protocol_extension *isa;\n";
3146 Result += "\tchar *protocol_name;\n";
3147 Result += "\tstruct _objc_protocol **protocol_list;\n";
3148 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3149 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003150 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003151
Steve Naroffd9803712009-04-29 16:37:50 +00003152 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003153 }
Mike Stump11289f42009-09-09 15:08:12 +00003154
Steve Naroffd9803712009-04-29 16:37:50 +00003155 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3156 Result += PDecl->getNameAsString();
3157 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3158 "{\n\t0, \"";
3159 Result += PDecl->getNameAsString();
3160 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003161 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003162 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3163 Result += PDecl->getNameAsString();
3164 Result += ", ";
3165 }
3166 else
3167 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003168 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003169 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3170 Result += PDecl->getNameAsString();
3171 Result += "\n";
3172 }
3173 else
3174 Result += "0\n";
3175 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003176
Steve Naroffd9803712009-04-29 16:37:50 +00003177 // Mark this protocol as having been generated.
3178 if (!ObjCSynthesizedProtocols.insert(PDecl))
3179 assert(false && "protocol already synthesized");
3180
3181}
3182
3183void RewriteObjC::
3184RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3185 const char *prefix, const char *ClassName,
3186 std::string &Result) {
3187 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003188
Steve Naroffd9803712009-04-29 16:37:50 +00003189 for (unsigned i = 0; i != Protocols.size(); i++)
3190 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3191
Chris Lattner388f6e92008-07-21 21:33:21 +00003192 // Output the top lovel protocol meta-data for the class.
3193 /* struct _objc_protocol_list {
3194 struct _objc_protocol_list *next;
3195 int protocol_count;
3196 struct _objc_protocol *class_protocols[];
3197 }
3198 */
3199 Result += "\nstatic struct {\n";
3200 Result += "\tstruct _objc_protocol_list *next;\n";
3201 Result += "\tint protocol_count;\n";
3202 Result += "\tstruct _objc_protocol *class_protocols[";
3203 Result += utostr(Protocols.size());
3204 Result += "];\n} _OBJC_";
3205 Result += prefix;
3206 Result += "_PROTOCOLS_";
3207 Result += ClassName;
3208 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3209 "{\n\t0, ";
3210 Result += utostr(Protocols.size());
3211 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003212
Chris Lattner388f6e92008-07-21 21:33:21 +00003213 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003214 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003215 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003216
Chris Lattner388f6e92008-07-21 21:33:21 +00003217 for (unsigned i = 1; i != Protocols.size(); i++) {
3218 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003219 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003220 Result += "\n";
3221 }
3222 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003223}
3224
Steve Naroffd9803712009-04-29 16:37:50 +00003225
Mike Stump11289f42009-09-09 15:08:12 +00003226/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003227/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003228void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003229 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003230 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003231 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003232 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003233 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003234 CDecl = CDecl->getNextClassCategory())
3235 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3236 break;
Mike Stump11289f42009-09-09 15:08:12 +00003237
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003238 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003239 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003240 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003241
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003242 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003243 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003244 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003245
3246 // If any of our property implementations have associated getters or
3247 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003248 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3249 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003250 Prop != PropEnd; ++Prop) {
3251 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3252 continue;
3253 if (!(*Prop)->getPropertyIvarDecl())
3254 continue;
3255 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3256 if (!PD)
3257 continue;
3258 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3259 InstanceMethods.push_back(Getter);
3260 if (PD->isReadOnly())
3261 continue;
3262 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3263 InstanceMethods.push_back(Setter);
3264 }
3265 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003266 true, "CATEGORY_", FullCategoryName.c_str(),
3267 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003268
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003269 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003270 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003271 false, "CATEGORY_", FullCategoryName.c_str(),
3272 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003273
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003274 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003275 // Null CDecl is case of a category implementation with no category interface
3276 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003277 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3278 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003279 /* struct _objc_category {
3280 char *category_name;
3281 char *class_name;
3282 struct _objc_method_list *instance_methods;
3283 struct _objc_method_list *class_methods;
3284 struct _objc_protocol_list *protocols;
3285 // Objective-C 1.0 extensions
3286 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003287 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003288 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003289 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003290 */
Mike Stump11289f42009-09-09 15:08:12 +00003291
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003292 static bool objc_category = false;
3293 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003294 Result += "\nstruct _objc_category {\n";
3295 Result += "\tchar *category_name;\n";
3296 Result += "\tchar *class_name;\n";
3297 Result += "\tstruct _objc_method_list *instance_methods;\n";
3298 Result += "\tstruct _objc_method_list *class_methods;\n";
3299 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003300 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003301 Result += "\tstruct _objc_property_list *instance_properties;\n";
3302 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003303 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003304 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003305 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3306 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003307 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003308 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003309 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003310 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003311 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003312
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003313 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003314 Result += "\t, (struct _objc_method_list *)"
3315 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3316 Result += FullCategoryName;
3317 Result += "\n";
3318 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003319 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003320 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003321 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003322 Result += "\t, (struct _objc_method_list *)"
3323 "&_OBJC_CATEGORY_CLASS_METHODS_";
3324 Result += FullCategoryName;
3325 Result += "\n";
3326 }
3327 else
3328 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003329
Chris Lattnerf5b77512009-02-20 18:18:36 +00003330 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003331 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003332 Result += FullCategoryName;
3333 Result += "\n";
3334 }
3335 else
3336 Result += "\t, 0\n";
3337 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003338}
3339
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003340/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3341/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003342void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3343 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003344 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003345 if (ivar->isBitField()) {
3346 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3347 // place all bitfields at offset 0.
3348 Result += "0";
3349 } else {
3350 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003351 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003352 if (LangOpts.Microsoft)
3353 Result += "_IMPL";
3354 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003355 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003356 Result += ")";
3357 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003358}
3359
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003360//===----------------------------------------------------------------------===//
3361// Meta Data Emission
3362//===----------------------------------------------------------------------===//
3363
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003364void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003365 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003366 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003367
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003368 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003369 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003370 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003371 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003372 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003373 }
Mike Stump11289f42009-09-09 15:08:12 +00003374
Chris Lattner30d23e82007-12-12 07:56:42 +00003375 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003376 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003377 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003378 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003379 if (NumIvars > 0) {
3380 static bool objc_ivar = false;
3381 if (!objc_ivar) {
3382 /* struct _objc_ivar {
3383 char *ivar_name;
3384 char *ivar_type;
3385 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003386 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003387 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003388 Result += "\nstruct _objc_ivar {\n";
3389 Result += "\tchar *ivar_name;\n";
3390 Result += "\tchar *ivar_type;\n";
3391 Result += "\tint ivar_offset;\n";
3392 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003393
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003394 objc_ivar = true;
3395 }
3396
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003397 /* struct {
3398 int ivar_count;
3399 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003400 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003401 */
Mike Stump11289f42009-09-09 15:08:12 +00003402 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003403 Result += "\tint ivar_count;\n";
3404 Result += "\tstruct _objc_ivar ivar_list[";
3405 Result += utostr(NumIvars);
3406 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003407 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003408 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003409 "{\n\t";
3410 Result += utostr(NumIvars);
3411 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003412
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003413 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003414 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003415 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003416 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003417 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003418 IV != IVEnd; ++IV)
3419 IVars.push_back(*IV);
3420 IVI = IVars.begin();
3421 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003422 } else {
3423 IVI = CDecl->ivar_begin();
3424 IVE = CDecl->ivar_end();
3425 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003426 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003427 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003428 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003429 std::string TmpString, StrEncoding;
3430 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3431 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003432 Result += StrEncoding;
3433 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003434 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003435 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003436 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003437 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003438 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003439 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003440 std::string TmpString, StrEncoding;
3441 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3442 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003443 Result += StrEncoding;
3444 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003445 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003446 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003447 }
Mike Stump11289f42009-09-09 15:08:12 +00003448
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003449 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003450 }
Mike Stump11289f42009-09-09 15:08:12 +00003451
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003452 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003453 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003454 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003455
3456 // If any of our property implementations have associated getters or
3457 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003458 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3459 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003460 Prop != PropEnd; ++Prop) {
3461 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3462 continue;
3463 if (!(*Prop)->getPropertyIvarDecl())
3464 continue;
3465 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3466 if (!PD)
3467 continue;
3468 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3469 InstanceMethods.push_back(Getter);
3470 if (PD->isReadOnly())
3471 continue;
3472 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3473 InstanceMethods.push_back(Setter);
3474 }
3475 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003476 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003477
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003478 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003479 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003480 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003481
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003482 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003483 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3484 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003485
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003486 // Declaration of class/meta-class metadata
3487 /* struct _objc_class {
3488 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003489 const char *super_class_name;
3490 char *name;
3491 long version;
3492 long info;
3493 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003494 struct _objc_ivar_list *ivars;
3495 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003496 struct objc_cache *cache;
3497 struct objc_protocol_list *protocols;
3498 const char *ivar_layout;
3499 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003500 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003501 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003502 static bool objc_class = false;
3503 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003504 Result += "\nstruct _objc_class {\n";
3505 Result += "\tstruct _objc_class *isa;\n";
3506 Result += "\tconst char *super_class_name;\n";
3507 Result += "\tchar *name;\n";
3508 Result += "\tlong version;\n";
3509 Result += "\tlong info;\n";
3510 Result += "\tlong instance_size;\n";
3511 Result += "\tstruct _objc_ivar_list *ivars;\n";
3512 Result += "\tstruct _objc_method_list *methods;\n";
3513 Result += "\tstruct objc_cache *cache;\n";
3514 Result += "\tstruct _objc_protocol_list *protocols;\n";
3515 Result += "\tconst char *ivar_layout;\n";
3516 Result += "\tstruct _objc_class_ext *ext;\n";
3517 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003518 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003519 }
Mike Stump11289f42009-09-09 15:08:12 +00003520
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003521 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003522 ObjCInterfaceDecl *RootClass = 0;
3523 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003524 while (SuperClass) {
3525 RootClass = SuperClass;
3526 SuperClass = SuperClass->getSuperClass();
3527 }
3528 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003529
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003530 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003531 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003532 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003533 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003534 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003535 Result += "\"";
3536
3537 if (SuperClass) {
3538 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003539 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003540 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003541 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003542 Result += "\"";
3543 }
3544 else {
3545 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003546 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003547 Result += "\"";
3548 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003549 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003550 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003552 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003553 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003554 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003555 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003556 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003557 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003558 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003559 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003560 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003561 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003562 Result += ",0,0\n";
3563 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003564 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003565 Result += "\t,0,0,0,0\n";
3566 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003567
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003568 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003569 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003570 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003571 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003572 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003573 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003574 if (SuperClass) {
3575 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003576 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003577 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003578 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003579 Result += "\"";
3580 }
3581 else {
3582 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003583 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003584 Result += "\"";
3585 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003586 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003587 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003588 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003589 Result += ",0";
3590 else {
3591 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003592 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003593 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003594 if (LangOpts.Microsoft)
3595 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003596 Result += ")";
3597 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003598 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003599 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003600 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003601 Result += "\n\t";
3602 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003603 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003604 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003605 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003606 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003607 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003608 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003609 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003610 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003611 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003612 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003613 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003614 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003615 Result += ", 0,0\n";
3616 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003617 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003618 Result += ",0,0,0\n";
3619 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003620}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003621
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003622/// RewriteImplementations - This routine rewrites all method implementations
3623/// and emits meta-data.
3624
Steve Narofff8cfd162008-11-13 20:07:04 +00003625void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003626 int ClsDefCount = ClassImplementation.size();
3627 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003628
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003629 // Rewrite implemented methods
3630 for (int i = 0; i < ClsDefCount; i++)
3631 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003632
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003633 for (int i = 0; i < CatDefCount; i++)
3634 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003635}
Mike Stump11289f42009-09-09 15:08:12 +00003636
Steve Narofff8cfd162008-11-13 20:07:04 +00003637void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3638 int ClsDefCount = ClassImplementation.size();
3639 int CatDefCount = CategoryImplementation.size();
3640
Steve Naroff30ac2222008-05-07 21:23:49 +00003641 // This is needed for determining instance variable offsets.
Fariborz Jahanian9ab63492010-01-07 18:31:42 +00003642 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003643 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003644 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003645 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003646
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003647 // For each implemented category, write out all its meta data.
3648 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003649 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003650
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003651 // Write objc_symtab metadata
3652 /*
3653 struct _objc_symtab
3654 {
3655 long sel_ref_cnt;
3656 SEL *refs;
3657 short cls_def_cnt;
3658 short cat_def_cnt;
3659 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003660 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003661 */
Mike Stump11289f42009-09-09 15:08:12 +00003662
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003663 Result += "\nstruct _objc_symtab {\n";
3664 Result += "\tlong sel_ref_cnt;\n";
3665 Result += "\tSEL *refs;\n";
3666 Result += "\tshort cls_def_cnt;\n";
3667 Result += "\tshort cat_def_cnt;\n";
3668 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3669 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003670
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003671 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003672 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003673 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003674 + ", " + utostr(CatDefCount) + "\n";
3675 for (int i = 0; i < ClsDefCount; i++) {
3676 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003677 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003678 Result += "\n";
3679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003681 for (int i = 0; i < CatDefCount; i++) {
3682 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003683 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003684 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003685 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003686 Result += "\n";
3687 }
Mike Stump11289f42009-09-09 15:08:12 +00003688
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003689 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003690
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003691 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003692
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003693 /*
3694 struct _objc_module {
3695 long version;
3696 long size;
3697 const char *name;
3698 struct _objc_symtab *symtab;
3699 }
3700 */
Mike Stump11289f42009-09-09 15:08:12 +00003701
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003702 Result += "\nstruct _objc_module {\n";
3703 Result += "\tlong version;\n";
3704 Result += "\tlong size;\n";
3705 Result += "\tconst char *name;\n";
3706 Result += "\tstruct _objc_symtab *symtab;\n";
3707 Result += "};\n\n";
3708 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003709 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003710 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003711 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003712 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003713
3714 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003715 if (ProtocolExprDecls.size()) {
3716 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3717 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003718 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003719 E = ProtocolExprDecls.end(); I != E; ++I) {
3720 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3721 Result += (*I)->getNameAsString();
3722 Result += " = &_OBJC_PROTOCOL_";
3723 Result += (*I)->getNameAsString();
3724 Result += ";\n";
3725 }
3726 Result += "#pragma data_seg(pop)\n\n";
3727 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003728 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003729 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003730 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3731 Result += "&_OBJC_MODULES;\n";
3732 Result += "#pragma data_seg(pop)\n\n";
3733 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003734}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003735
Steve Naroff677ab3a2008-10-27 17:20:55 +00003736std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3737 const char *funcName,
3738 std::string Tag) {
3739 const FunctionType *AFT = CE->getFunctionType();
3740 QualType RT = AFT->getResultType();
3741 std::string StructRef = "struct " + Tag;
3742 std::string S = "static " + RT.getAsString() + " __" +
3743 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003744
Steve Naroff677ab3a2008-10-27 17:20:55 +00003745 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003746
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003747 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003748 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003749 // block (to reference imported block decl refs).
3750 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003751 } else if (BD->param_empty()) {
3752 S += "(" + StructRef + " *__cself)";
3753 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003754 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003755 assert(FT && "SynthesizeBlockFunc: No function proto");
3756 S += '(';
3757 // first add the implicit argument.
3758 S += StructRef + " *__cself, ";
3759 std::string ParamStr;
3760 for (BlockDecl::param_iterator AI = BD->param_begin(),
3761 E = BD->param_end(); AI != E; ++AI) {
3762 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003763 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003764 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003765 S += ParamStr;
3766 }
3767 if (FT->isVariadic()) {
3768 if (!BD->param_empty()) S += ", ";
3769 S += "...";
3770 }
3771 S += ')';
3772 }
3773 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003774
Steve Naroff677ab3a2008-10-27 17:20:55 +00003775 // Create local declarations to avoid rewriting all closure decl ref exprs.
3776 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003777 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003778 E = BlockByRefDecls.end(); I != E; ++I) {
3779 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003780 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003781 std::string TypeString = "struct __Block_byref_" + Name + " *";
3782 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003783 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003784 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003785 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003786 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003787 E = BlockByCopyDecls.end(); I != E; ++I) {
3788 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003789 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003790 // Handle nested closure invocation. For example:
3791 //
3792 // void (^myImportedClosure)(void);
3793 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003794 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003795 // void (^anotherClosure)(void);
3796 // anotherClosure = ^(void) {
3797 // myImportedClosure(); // import and invoke the closure
3798 // };
3799 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003800 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003801 S += "struct __block_impl *";
3802 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003803 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003804 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003805 }
3806 std::string RewrittenStr = RewrittenBlockExprs[CE];
3807 const char *cstr = RewrittenStr.c_str();
3808 while (*cstr++ != '{') ;
3809 S += cstr;
3810 S += "\n";
3811 return S;
3812}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003813
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3815 const char *funcName,
3816 std::string Tag) {
3817 std::string StructRef = "struct " + Tag;
3818 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003819
Steve Naroff677ab3a2008-10-27 17:20:55 +00003820 S += funcName;
3821 S += "_block_copy_" + utostr(i);
3822 S += "(" + StructRef;
3823 S += "*dst, " + StructRef;
3824 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003825 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003826 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003827 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003828 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003829 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003830 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003831 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003832 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003833 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003834 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003835 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003836 S += "}\n";
3837
Steve Naroff677ab3a2008-10-27 17:20:55 +00003838 S += "\nstatic void __";
3839 S += funcName;
3840 S += "_block_dispose_" + utostr(i);
3841 S += "(" + StructRef;
3842 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003843 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003844 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003845 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003846 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003847 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003848 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003849 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003850 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003851 }
Mike Stump11289f42009-09-09 15:08:12 +00003852 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003853 return S;
3854}
3855
Steve Naroff30484702009-12-06 21:14:13 +00003856std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3857 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003858 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003859 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003860
Steve Naroff677ab3a2008-10-27 17:20:55 +00003861 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003862 S += " struct " + Desc;
3863 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003864
Steve Naroff30484702009-12-06 21:14:13 +00003865 Constructor += "(void *fp, "; // Invoke function pointer.
3866 Constructor += "struct " + Desc; // Descriptor pointer.
3867 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003868
Steve Naroff677ab3a2008-10-27 17:20:55 +00003869 if (BlockDeclRefs.size()) {
3870 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003871 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003872 E = BlockByCopyDecls.end(); I != E; ++I) {
3873 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003874 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003875 std::string ArgName = "_" + FieldName;
3876 // Handle nested closure invocation. For example:
3877 //
3878 // void (^myImportedBlock)(void);
3879 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003880 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003881 // void (^anotherBlock)(void);
3882 // anotherBlock = ^(void) {
3883 // myImportedBlock(); // import and invoke the closure
3884 // };
3885 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003886 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003887 S += "struct __block_impl *";
3888 Constructor += ", void *" + ArgName;
3889 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003890 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3891 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003892 Constructor += ", " + ArgName;
3893 }
3894 S += FieldName + ";\n";
3895 }
3896 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003897 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003898 E = BlockByRefDecls.end(); I != E; ++I) {
3899 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003900 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003901 std::string ArgName = "_" + FieldName;
3902 // Handle nested closure invocation. For example:
3903 //
3904 // void (^myImportedBlock)(void);
3905 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003906 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003907 // void (^anotherBlock)(void);
3908 // anotherBlock = ^(void) {
3909 // myImportedBlock(); // import and invoke the closure
3910 // };
3911 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003912 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003913 S += "struct __block_impl *";
3914 Constructor += ", void *" + ArgName;
3915 } else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003916 std::string TypeString = "struct __Block_byref_" + FieldName;
3917 TypeString += " *";
3918 FieldName = TypeString + FieldName;
3919 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003920 Constructor += ", " + ArgName;
3921 }
3922 S += FieldName + "; // by ref\n";
3923 }
3924 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003925 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003926 if (GlobalVarDecl)
3927 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3928 else
3929 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003930 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003931
Steve Naroff30484702009-12-06 21:14:13 +00003932 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003933
Steve Naroff677ab3a2008-10-27 17:20:55 +00003934 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003935 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003936 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003937 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003938 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003939 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003940 Constructor += Name + " = (struct __block_impl *)_";
3941 else
3942 Constructor += Name + " = _";
3943 Constructor += Name + ";\n";
3944 }
3945 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003946 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003947 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003948 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003949 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003950 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003951 Constructor += Name + " = (struct __block_impl *)_";
3952 else
3953 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003954 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003955 }
3956 } else {
3957 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003958 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003959 if (GlobalVarDecl)
3960 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3961 else
3962 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003963 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3964 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003965 }
3966 Constructor += " ";
3967 Constructor += "}\n";
3968 S += Constructor;
3969 S += "};\n";
3970 return S;
3971}
3972
Steve Naroff30484702009-12-06 21:14:13 +00003973std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3974 std::string ImplTag, int i,
3975 const char *FunName,
3976 unsigned hasCopy) {
3977 std::string S = "\nstatic struct " + DescTag;
3978
3979 S += " {\n unsigned long reserved;\n";
3980 S += " unsigned long Block_size;\n";
3981 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003982 S += " void (*copy)(struct ";
3983 S += ImplTag; S += "*, struct ";
3984 S += ImplTag; S += "*);\n";
3985
3986 S += " void (*dispose)(struct ";
3987 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003988 }
3989 S += "} ";
3990
3991 S += DescTag + "_DATA = { 0, sizeof(struct ";
3992 S += ImplTag + ")";
3993 if (hasCopy) {
3994 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3995 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3996 }
3997 S += "};\n";
3998 return S;
3999}
4000
Steve Naroff677ab3a2008-10-27 17:20:55 +00004001void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4002 const char *FunName) {
4003 // Insert closures that were part of the function.
4004 for (unsigned i = 0; i < Blocks.size(); i++) {
4005
4006 CollectBlockDeclRefInfo(Blocks[i]);
4007
Steve Naroff30484702009-12-06 21:14:13 +00004008 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4009 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00004010
Steve Naroff30484702009-12-06 21:14:13 +00004011 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004012
4013 InsertText(FunLocStart, CI.c_str(), CI.size());
4014
Steve Naroff30484702009-12-06 21:14:13 +00004015 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00004016
Steve Naroff677ab3a2008-10-27 17:20:55 +00004017 InsertText(FunLocStart, CF.c_str(), CF.size());
4018
4019 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00004020 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004021 InsertText(FunLocStart, HF.c_str(), HF.size());
4022 }
Steve Naroff30484702009-12-06 21:14:13 +00004023 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4024 ImportedBlockDecls.size() > 0);
4025 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004026
Steve Naroff677ab3a2008-10-27 17:20:55 +00004027 BlockDeclRefs.clear();
4028 BlockByRefDecls.clear();
4029 BlockByCopyDecls.clear();
4030 BlockCallExprs.clear();
4031 ImportedBlockDecls.clear();
4032 }
4033 Blocks.clear();
4034 RewrittenBlockExprs.clear();
4035}
4036
4037void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4038 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004039 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004040
Steve Naroff677ab3a2008-10-27 17:20:55 +00004041 SynthesizeBlockLiterals(FunLocStart, FuncName);
4042}
4043
4044void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004045 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4046 //SourceLocation FunLocStart = MD->getLocStart();
4047 // FIXME: This hack works around a bug in Rewrite.InsertText().
4048 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004049 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004050 // Convert colons to underscores.
4051 std::string::size_type loc = 0;
4052 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4053 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004054
Steve Naroff677ab3a2008-10-27 17:20:55 +00004055 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4056}
4057
4058void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4059 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4060 CI != E; ++CI)
4061 if (*CI) {
4062 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4063 GetBlockDeclRefExprs(CBE->getBody());
4064 else
4065 GetBlockDeclRefExprs(*CI);
4066 }
4067 // Handle specific things.
4068 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4069 // FIXME: Handle enums.
4070 if (!isa<FunctionDecl>(CDRE->getDecl()))
4071 BlockDeclRefs.push_back(CDRE);
4072 return;
4073}
4074
4075void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4076 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4077 CI != E; ++CI)
4078 if (*CI) {
4079 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4080 GetBlockCallExprs(CBE->getBody());
4081 else
4082 GetBlockCallExprs(*CI);
4083 }
Mike Stump11289f42009-09-09 15:08:12 +00004084
Steve Naroff677ab3a2008-10-27 17:20:55 +00004085 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4086 if (CE->getCallee()->getType()->isBlockPointerType()) {
4087 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4088 }
4089 }
4090 return;
4091}
4092
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004093Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004094 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004095 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004096
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004097 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004098 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004099 } else if (const BlockDeclRefExpr *CDRE =
4100 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004101 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004102 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004103 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004104 }
4105 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4106 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4107 }
4108 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4109 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4110 else if (const ConditionalOperator *CEXPR =
4111 dyn_cast<ConditionalOperator>(BlockExp)) {
4112 Expr *LHSExp = CEXPR->getLHS();
4113 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4114 Expr *RHSExp = CEXPR->getRHS();
4115 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4116 Expr *CONDExp = CEXPR->getCond();
4117 ConditionalOperator *CondExpr =
4118 new (Context) ConditionalOperator(CONDExp,
4119 SourceLocation(), cast<Expr>(LHSStmt),
4120 SourceLocation(), cast<Expr>(RHSStmt),
4121 Exp->getType());
4122 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004123 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4124 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004125 } else {
4126 assert(1 && "RewriteBlockClass: Bad type");
4127 }
4128 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004129 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004130 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004131 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004132 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004133
Steve Naroff350b6652008-10-30 10:07:53 +00004134 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4135 SourceLocation(),
4136 &Context->Idents.get("__block_impl"));
4137 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004138
Steve Naroff350b6652008-10-30 10:07:53 +00004139 // Generate a funky cast.
4140 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004141
Steve Naroff350b6652008-10-30 10:07:53 +00004142 // Push the block argument type.
4143 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004144 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004145 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004146 E = FTP->arg_type_end(); I && (I != E); ++I) {
4147 QualType t = *I;
4148 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004149 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004150 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004151 t = Context->getPointerType(BPT->getPointeeType());
4152 }
4153 ArgTypes.push_back(t);
4154 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004155 }
Steve Naroff350b6652008-10-30 10:07:53 +00004156 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004157 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004158 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004159
Steve Naroff350b6652008-10-30 10:07:53 +00004160 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004161
4162 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004163 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004164 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004165 PtrBlock, SourceLocation(),
4166 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004167 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004168 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4169 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004170 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004171
Douglas Gregor91f84212008-12-11 16:49:14 +00004172 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004173 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004174 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004175 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4176 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004177
Anders Carlssona2615922009-07-31 00:48:10 +00004178 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4179 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004180 PtrToFuncCastType,
4181 SourceLocation(),
4182 SourceLocation());
4183 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004184
Steve Naroff350b6652008-10-30 10:07:53 +00004185 llvm::SmallVector<Expr*, 8> BlkExprs;
4186 // Add the implicit argument.
4187 BlkExprs.push_back(BlkCast);
4188 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004189 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004190 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004191 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004192 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004193 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4194 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004195 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004196 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004197}
4198
4199void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004200 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004201 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004202}
4203
Steve Naroffd9803712009-04-29 16:37:50 +00004204// We need to return the rewritten expression to handle cases where the
4205// BlockDeclRefExpr is embedded in another expression being rewritten.
4206// For example:
4207//
4208// int main() {
4209// __block Foo *f;
4210// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004211//
Steve Naroffd9803712009-04-29 16:37:50 +00004212// void (^myblock)() = ^() {
4213// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4214// i = 77;
4215// };
4216//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004217Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004218 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004219 // for each DeclRefExp where BYREFVAR is name of the variable.
4220 ValueDecl *VD;
4221 bool isArrow = true;
4222 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4223 VD = BDRE->getDecl();
4224 else {
4225 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4226 isArrow = false;
4227 }
4228
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004229 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4230 &Context->Idents.get("__forwarding"),
4231 Context->VoidPtrTy, 0,
4232 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004233 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4234 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004235 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004236
4237 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004238 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4239 &Context->Idents.get(Name),
4240 Context->VoidPtrTy, 0,
4241 /*BitWidth=*/0, /*Mutable=*/true);
4242 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004243 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004244
4245
4246
Steve Narofff26a1d42009-02-02 17:19:26 +00004247 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004248 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4249 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004250 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004251 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004252}
4253
Steve Naroffc989a7b2008-11-03 23:29:32 +00004254void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4255 SourceLocation LocStart = CE->getLParenLoc();
4256 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004257
4258 // Need to avoid trying to rewrite synthesized casts.
4259 if (LocStart.isInvalid())
4260 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004261 // Need to avoid trying to rewrite casts contained in macros.
4262 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4263 return;
Mike Stump11289f42009-09-09 15:08:12 +00004264
Steve Naroff677ab3a2008-10-27 17:20:55 +00004265 const char *startBuf = SM->getCharacterData(LocStart);
4266 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004267
Steve Naroff677ab3a2008-10-27 17:20:55 +00004268 // advance the location to startArgList.
4269 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004270
Steve Naroff677ab3a2008-10-27 17:20:55 +00004271 while (*argPtr++ && (argPtr < endBuf)) {
4272 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004273 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004274 // Replace the '^' with '*'.
4275 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4276 ReplaceText(LocStart, 1, "*", 1);
4277 break;
4278 }
4279 }
4280 return;
4281}
4282
4283void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4284 SourceLocation DeclLoc = FD->getLocation();
4285 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004286
Steve Naroff677ab3a2008-10-27 17:20:55 +00004287 // We have 1 or more arguments that have closure pointers.
4288 const char *startBuf = SM->getCharacterData(DeclLoc);
4289 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004290
Steve Naroff677ab3a2008-10-27 17:20:55 +00004291 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004292
Steve Naroff677ab3a2008-10-27 17:20:55 +00004293 parenCount++;
4294 // advance the location to startArgList.
4295 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4296 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004297
Steve Naroff677ab3a2008-10-27 17:20:55 +00004298 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004299
Steve Naroff677ab3a2008-10-27 17:20:55 +00004300 while (*argPtr++ && parenCount) {
4301 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004302 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004303 // Replace the '^' with '*'.
4304 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4305 ReplaceText(DeclLoc, 1, "*", 1);
4306 break;
Mike Stump11289f42009-09-09 15:08:12 +00004307 case '(':
4308 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004309 break;
Mike Stump11289f42009-09-09 15:08:12 +00004310 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311 parenCount--;
4312 break;
4313 }
4314 }
4315 return;
4316}
4317
4318bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004319 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004320 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004321 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004322 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004323 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004324 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004325 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004326 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004327 }
4328 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004329 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004330 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004331 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004332 return true;
4333 }
4334 return false;
4335}
4336
Ted Kremenek5a201952009-02-07 01:47:29 +00004337void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4338 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004339 const char *argPtr = strchr(Name, '(');
4340 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004341
Steve Naroff677ab3a2008-10-27 17:20:55 +00004342 LParen = argPtr; // output the start.
4343 argPtr++; // skip past the left paren.
4344 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004345
Steve Naroff677ab3a2008-10-27 17:20:55 +00004346 while (*argPtr && parenCount) {
4347 switch (*argPtr) {
4348 case '(': parenCount++; break;
4349 case ')': parenCount--; break;
4350 default: break;
4351 }
4352 if (parenCount) argPtr++;
4353 }
4354 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4355 RParen = argPtr; // output the end
4356}
4357
4358void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4359 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4360 RewriteBlockPointerFunctionArgs(FD);
4361 return;
Mike Stump11289f42009-09-09 15:08:12 +00004362 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004363 // Handle Variables and Typedefs.
4364 SourceLocation DeclLoc = ND->getLocation();
4365 QualType DeclT;
4366 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4367 DeclT = VD->getType();
4368 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4369 DeclT = TDD->getUnderlyingType();
4370 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4371 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004372 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004373 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004374
Steve Naroff677ab3a2008-10-27 17:20:55 +00004375 const char *startBuf = SM->getCharacterData(DeclLoc);
4376 const char *endBuf = startBuf;
4377 // scan backward (from the decl location) for the end of the previous decl.
4378 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4379 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004380
Steve Naroff677ab3a2008-10-27 17:20:55 +00004381 // *startBuf != '^' if we are dealing with a pointer to function that
4382 // may take block argument types (which will be handled below).
4383 if (*startBuf == '^') {
4384 // Replace the '^' with '*', computing a negative offset.
4385 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4386 ReplaceText(DeclLoc, 1, "*", 1);
4387 }
4388 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4389 // Replace the '^' with '*' for arguments.
4390 DeclLoc = ND->getLocation();
4391 startBuf = SM->getCharacterData(DeclLoc);
4392 const char *argListBegin, *argListEnd;
4393 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4394 while (argListBegin < argListEnd) {
4395 if (*argListBegin == '^') {
4396 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4397 ReplaceText(CaretLoc, 1, "*", 1);
4398 }
4399 argListBegin++;
4400 }
4401 }
4402 return;
4403}
4404
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004405
4406/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4407/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4408/// struct Block_byref_id_object *src) {
4409/// _Block_object_assign (&_dest->object, _src->object,
4410/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4411/// [|BLOCK_FIELD_IS_WEAK]) // object
4412/// _Block_object_assign(&_dest->object, _src->object,
4413/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4414/// [|BLOCK_FIELD_IS_WEAK]) // block
4415/// }
4416/// And:
4417/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4418/// _Block_object_dispose(_src->object,
4419/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4420/// [|BLOCK_FIELD_IS_WEAK]) // object
4421/// _Block_object_dispose(_src->object,
4422/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4423/// [|BLOCK_FIELD_IS_WEAK]) // block
4424/// }
4425
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004426std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4427 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004428 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004429 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004430 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004431 CopyDestroyCache.insert(flag);
4432 S = "static void __Block_byref_id_object_copy_";
4433 S += utostr(flag);
4434 S += "(void *dst, void *src) {\n";
4435
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004436 // offset into the object pointer is computed as:
4437 // void * + void* + int + int + void* + void *
4438 unsigned IntSize =
4439 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4440 unsigned VoidPtrSize =
4441 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4442
4443 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4444 S += " _Block_object_assign((char*)dst + ";
4445 S += utostr(offset);
4446 S += ", *(void * *) ((char*)src + ";
4447 S += utostr(offset);
4448 S += "), ";
4449 S += utostr(flag);
4450 S += ");\n}\n";
4451
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004452 S += "static void __Block_byref_id_object_dispose_";
4453 S += utostr(flag);
4454 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004455 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4456 S += utostr(offset);
4457 S += "), ";
4458 S += utostr(flag);
4459 S += ");\n}\n";
4460 return S;
4461}
4462
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004463/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4464/// the declaration into:
4465/// struct __Block_byref_ND {
4466/// void *__isa; // NULL for everything except __weak pointers
4467/// struct __Block_byref_ND *__forwarding;
4468/// int32_t __flags;
4469/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004470/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4471/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004472/// typex ND;
4473/// };
4474///
4475/// It then replaces declaration of ND variable with:
4476/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4477/// __size=sizeof(struct __Block_byref_ND),
4478/// ND=initializer-if-any};
4479///
4480///
4481void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004482 int flag = 0;
4483 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004484 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4485 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004486 SourceLocation X = ND->getLocEnd();
4487 X = SM->getInstantiationLoc(X);
4488 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004489 std::string Name(ND->getNameAsString());
4490 std::string ByrefType = "struct __Block_byref_";
4491 ByrefType += Name;
4492 ByrefType += " {\n";
4493 ByrefType += " void *__isa;\n";
4494 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4495 ByrefType += " int __flags;\n";
4496 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004497 // Add void *__Block_byref_id_object_copy;
4498 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004499 QualType Ty = ND->getType();
4500 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4501 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004502 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4503 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004504 }
4505
4506 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004507 ByrefType += " " + Name + ";\n";
4508 ByrefType += "};\n";
4509 // Insert this type in global scope. It is needed by helper function.
4510 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4511 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4512 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004513 if (Ty.isObjCGCWeak()) {
4514 flag |= BLOCK_FIELD_IS_WEAK;
4515 isa = 1;
4516 }
4517
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004518 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004519 flag = BLOCK_BYREF_CALLER;
4520 QualType Ty = ND->getType();
4521 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4522 if (Ty->isBlockPointerType())
4523 flag |= BLOCK_FIELD_IS_BLOCK;
4524 else
4525 flag |= BLOCK_FIELD_IS_OBJECT;
4526 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004527 if (!HF.empty())
4528 InsertText(FunLocStart, HF.c_str(), HF.size());
4529 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004530
4531 // struct __Block_byref_ND ND =
4532 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4533 // initializer-if-any};
4534 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004535 unsigned flags = 0;
4536 if (HasCopyAndDispose)
4537 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004538 Name = ND->getNameAsString();
4539 ByrefType = "struct __Block_byref_" + Name;
4540 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004541 ByrefType += " " + Name + " = {(void*)";
4542 ByrefType += utostr(isa);
4543 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004544 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004545 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004546 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004547 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004548 ByrefType += ", __Block_byref_id_object_copy_";
4549 ByrefType += utostr(flag);
4550 ByrefType += ", __Block_byref_id_object_dispose_";
4551 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004552 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004553 ByrefType += "};\n";
4554 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4555 ByrefType.c_str(), ByrefType.size());
4556 }
4557 else {
4558 SourceLocation startLoc = ND->getInit()->getLocStart();
Fariborz Jahanianb8646ed2010-01-05 23:06:29 +00004559 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004560 ByrefType += " " + Name;
4561 ReplaceText(DeclLoc, endBuf-startBuf,
4562 ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004563 ByrefType = " = {(void*)";
4564 ByrefType += utostr(isa);
4565 ByrefType += ", &" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004566 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004567 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004568 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004569 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004570 ByrefType += "__Block_byref_id_object_copy_";
4571 ByrefType += utostr(flag);
4572 ByrefType += ", __Block_byref_id_object_dispose_";
4573 ByrefType += utostr(flag);
4574 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004575 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004576 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004577
4578 // Complete the newly synthesized compound expression by inserting a right
4579 // curly brace before the end of the declaration.
4580 // FIXME: This approach avoids rewriting the initializer expression. It
4581 // also assumes there is only one declarator. For example, the following
4582 // isn't currently supported by this routine (in general):
4583 //
4584 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4585 //
4586 const char *startBuf = SM->getCharacterData(startLoc);
4587 const char *semiBuf = strchr(startBuf, ';');
4588 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4589 SourceLocation semiLoc =
4590 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4591
4592 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004593 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004594 return;
4595}
4596
Mike Stump11289f42009-09-09 15:08:12 +00004597void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004598 // Add initializers for any closure decl refs.
4599 GetBlockDeclRefExprs(Exp->getBody());
4600 if (BlockDeclRefs.size()) {
4601 // Unique all "by copy" declarations.
4602 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4603 if (!BlockDeclRefs[i]->isByRef())
4604 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4605 // Unique all "by ref" declarations.
4606 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4607 if (BlockDeclRefs[i]->isByRef()) {
4608 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4609 }
4610 // Find any imported blocks...they will need special attention.
4611 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004612 if (BlockDeclRefs[i]->isByRef() ||
4613 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4614 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004615 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004616 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4617 }
4618 }
4619}
4620
Steve Narofff4b992a2008-10-28 20:29:00 +00004621FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4622 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004623 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004624 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004625 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004626 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004627}
4628
Steve Naroffd8907b72008-10-29 18:15:37 +00004629Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004630 Blocks.push_back(Exp);
4631
4632 CollectBlockDeclRefInfo(Exp);
4633 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004634
Steve Narofff4b992a2008-10-28 20:29:00 +00004635 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004636 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004637 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004638 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004639 // Convert colons to underscores.
4640 std::string::size_type loc = 0;
4641 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4642 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004643 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004644 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004645
Steve Narofff4b992a2008-10-28 20:29:00 +00004646 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004647
Steve Narofff4b992a2008-10-28 20:29:00 +00004648 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4649 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004650
Steve Narofff4b992a2008-10-28 20:29:00 +00004651 // Get a pointer to the function type so we can cast appropriately.
4652 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4653
4654 FunctionDecl *FD;
4655 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004656
Steve Narofff4b992a2008-10-28 20:29:00 +00004657 // Simulate a contructor call...
4658 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004659 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004660
Steve Narofff4b992a2008-10-28 20:29:00 +00004661 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004662
Steve Naroffe2514232008-10-29 21:23:59 +00004663 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004664 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004665 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4666 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004667 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4668 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004669 Context->VoidPtrTy, SourceLocation(),
4670 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004671 InitExprs.push_back(castExpr);
4672
Steve Naroff30484702009-12-06 21:14:13 +00004673 // Initialize the block descriptor.
4674 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004675
Steve Naroff30484702009-12-06 21:14:13 +00004676 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4677 &Context->Idents.get(DescData.c_str()),
4678 Context->VoidPtrTy, 0,
4679 VarDecl::Static);
4680 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4681 new (Context) DeclRefExpr(NewVD,
4682 Context->VoidPtrTy, SourceLocation()),
4683 UnaryOperator::AddrOf,
4684 Context->getPointerType(Context->VoidPtrTy),
4685 SourceLocation());
4686 InitExprs.push_back(DescRefExpr);
4687
Steve Narofff4b992a2008-10-28 20:29:00 +00004688 // Add initializers for any closure decl refs.
4689 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004690 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004691 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004692 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004693 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004694 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004695 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004696 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004697 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004698 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004699 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004700 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004701 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4702 CastExpr::CK_Unknown, Arg,
4703 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004704 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004705 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004706 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004707 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004708 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004709 }
Mike Stump11289f42009-09-09 15:08:12 +00004710 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004711 }
4712 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004713 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004714 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004715 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004716 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4717 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004718 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004719 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004720 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004721 }
4722 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004723 if (ImportedBlockDecls.size()) {
4724 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4725 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004726 unsigned IntSize =
4727 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004728 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4729 Context->IntTy, SourceLocation());
4730 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004731 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004732 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4733 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004734 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004735 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004736 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004737 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004738 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004739 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004740 BlockDeclRefs.clear();
4741 BlockByRefDecls.clear();
4742 BlockByCopyDecls.clear();
4743 ImportedBlockDecls.clear();
4744 return NewRep;
4745}
4746
4747//===----------------------------------------------------------------------===//
4748// Function Body / Expression rewriting
4749//===----------------------------------------------------------------------===//
4750
Steve Naroff4588d0f2008-12-04 16:24:46 +00004751// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4752// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4753// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4754// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4755// Since the rewriter isn't capable of rewriting rewritten code, it's important
4756// we get this right.
4757void RewriteObjC::CollectPropertySetters(Stmt *S) {
4758 // Perform a bottom up traversal of all children.
4759 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4760 CI != E; ++CI)
4761 if (*CI)
4762 CollectPropertySetters(*CI);
4763
4764 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4765 if (BinOp->isAssignmentOp()) {
4766 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4767 PropSetters[PRE] = BinOp;
4768 }
4769 }
4770}
4771
Steve Narofff4b992a2008-10-28 20:29:00 +00004772Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004773 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004774 isa<DoStmt>(S) || isa<ForStmt>(S))
4775 Stmts.push_back(S);
4776 else if (isa<ObjCForCollectionStmt>(S)) {
4777 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004778 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004779 }
Mike Stump11289f42009-09-09 15:08:12 +00004780
Steve Narofff4b992a2008-10-28 20:29:00 +00004781 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004782
Steve Narofff4b992a2008-10-28 20:29:00 +00004783 // Perform a bottom up rewrite of all children.
4784 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4785 CI != E; ++CI)
4786 if (*CI) {
4787 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004788 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004789 *CI = newStmt;
4790 }
Mike Stump11289f42009-09-09 15:08:12 +00004791
Steve Narofff4b992a2008-10-28 20:29:00 +00004792 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4793 // Rewrite the block body in place.
4794 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004795
Steve Narofff4b992a2008-10-28 20:29:00 +00004796 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenekdb2ef372010-01-07 18:00:35 +00004797 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004798 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004799
Steve Narofff4b992a2008-10-28 20:29:00 +00004800 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4801 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004802 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004803 return blockTranscribed;
4804 }
4805 // Handle specific things.
4806 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4807 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004808
Steve Narofff4b992a2008-10-28 20:29:00 +00004809 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4810 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4811
Steve Naroff4588d0f2008-12-04 16:24:46 +00004812 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4813 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4814 if (BinOp) {
4815 // Because the rewriter doesn't allow us to rewrite rewritten code,
4816 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004817 DisableReplaceStmt = true;
4818 // Save the source range. Even if we disable the replacement, the
4819 // rewritten node will have been inserted into the tree. If the synthesized
4820 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004821 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004822 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4823 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004824 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004825 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004826 //
4827 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4828 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4829 // to see the original expression). Consider this example:
4830 //
4831 // Foo *obj1, *obj2;
4832 //
4833 // obj1.i = [obj2 rrrr];
4834 //
4835 // 'BinOp' for the previous expression looks like:
4836 //
4837 // (BinaryOperator 0x231ccf0 'int' '='
4838 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4839 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4840 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4841 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4842 //
4843 // 'newStmt' represents the rewritten message expression. For example:
4844 //
4845 // (CallExpr 0x231d300 'id':'struct objc_object *'
4846 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4847 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4848 // (CStyleCastExpr 0x231d220 'void *'
4849 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4850 //
4851 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4852 // can be used as the setter argument. ReplaceStmt() will still 'see'
4853 // the original RHS (since we haven't altered BinOp).
4854 //
Mike Stump11289f42009-09-09 15:08:12 +00004855 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004856 // node. As a result, we now leak the original AST nodes.
4857 //
Steve Naroff08628db2008-12-09 12:56:34 +00004858 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004859 } else {
4860 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004861 }
4862 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004863 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4864 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004865
Steve Narofff4b992a2008-10-28 20:29:00 +00004866 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4867 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004868
Steve Narofff4b992a2008-10-28 20:29:00 +00004869 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004870#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004871 // Before we rewrite it, put the original message expression in a comment.
4872 SourceLocation startLoc = MessExpr->getLocStart();
4873 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004874
Steve Narofff4b992a2008-10-28 20:29:00 +00004875 const char *startBuf = SM->getCharacterData(startLoc);
4876 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004877
Steve Narofff4b992a2008-10-28 20:29:00 +00004878 std::string messString;
4879 messString += "// ";
4880 messString.append(startBuf, endBuf-startBuf+1);
4881 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004882
4883 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004884 // InsertText(clang::SourceLocation, char const*, unsigned int).
4885 // InsertText(startLoc, messString.c_str(), messString.size());
4886 // Tried this, but it didn't work either...
4887 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004888#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004889 return RewriteMessageExpr(MessExpr);
4890 }
Mike Stump11289f42009-09-09 15:08:12 +00004891
Steve Narofff4b992a2008-10-28 20:29:00 +00004892 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4893 return RewriteObjCTryStmt(StmtTry);
4894
4895 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4896 return RewriteObjCSynchronizedStmt(StmtTry);
4897
4898 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4899 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004900
Steve Narofff4b992a2008-10-28 20:29:00 +00004901 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4902 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004903
4904 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004905 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004906 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004907 OrigStmtRange.getEnd());
4908 if (BreakStmt *StmtBreakStmt =
4909 dyn_cast<BreakStmt>(S))
4910 return RewriteBreakStmt(StmtBreakStmt);
4911 if (ContinueStmt *StmtContinueStmt =
4912 dyn_cast<ContinueStmt>(S))
4913 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004914
4915 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004916 // and cast exprs.
4917 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4918 // FIXME: What we're doing here is modifying the type-specifier that
4919 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004920 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004921 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4922 // the context of an ObjCForCollectionStmt. For example:
4923 // NSArray *someArray;
4924 // for (id <FooProtocol> index in someArray) ;
4925 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4926 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004927 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004928 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004929
Steve Narofff4b992a2008-10-28 20:29:00 +00004930 // Blocks rewrite rules.
4931 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4932 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004933 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004934 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004935 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004936 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004937 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004938 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004939 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4940 if (VD->hasAttr<BlocksAttr>())
4941 RewriteByRefVar(VD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004942 }
4943 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004944 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004945 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004946 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004947 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4948 }
4949 }
4950 }
Mike Stump11289f42009-09-09 15:08:12 +00004951
Steve Narofff4b992a2008-10-28 20:29:00 +00004952 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4953 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004954
4955 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004956 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4957 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004958 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4959 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004960 && "Statement stack mismatch");
4961 Stmts.pop_back();
4962 }
4963 // Handle blocks rewriting.
4964 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4965 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004966 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004967 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004968 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4969 ValueDecl *VD = DRE->getDecl();
4970 if (VD->hasAttr<BlocksAttr>())
4971 return RewriteBlockDeclRefExpr(DRE);
4972 }
4973
Steve Narofff4b992a2008-10-28 20:29:00 +00004974 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004975 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004976 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004977 ReplaceStmt(S, BlockCall);
4978 return BlockCall;
4979 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004980 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004981 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004982 RewriteCastExpr(CE);
4983 }
4984#if 0
4985 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004986 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004987 // Get the new text.
4988 std::string SStr;
4989 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004990 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004991 const std::string &Str = Buf.str();
4992
4993 printf("CAST = %s\n", &Str[0]);
4994 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4995 delete S;
4996 return Replacement;
4997 }
4998#endif
4999 // Return this stmt unmodified.
5000 return S;
5001}
5002
Steve Naroffe70a52a2009-12-05 15:55:59 +00005003void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5004 for (RecordDecl::field_iterator i = RD->field_begin(),
5005 e = RD->field_end(); i != e; ++i) {
5006 FieldDecl *FD = *i;
5007 if (isTopLevelBlockPointerType(FD->getType()))
5008 RewriteBlockPointerDecl(FD);
5009 if (FD->getType()->isObjCQualifiedIdType() ||
5010 FD->getType()->isObjCQualifiedInterfaceType())
5011 RewriteObjCQualifiedInterfaceTypes(FD);
5012 }
5013}
5014
Steve Narofff4b992a2008-10-28 20:29:00 +00005015/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5016/// main file of the input.
5017void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5018 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00005019 if (FD->isOverloadedOperator())
5020 return;
Mike Stump11289f42009-09-09 15:08:12 +00005021
Steve Narofff4b992a2008-10-28 20:29:00 +00005022 // Since function prototypes don't have ParmDecl's, we check the function
5023 // prototype. This enables us to rewrite function declarations and
5024 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005025 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005026
Sebastian Redla7b98a72009-04-26 20:35:05 +00005027 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005028 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005029 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005030 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005031 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005032 Body =
5033 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5034 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005035 CurrentBody = 0;
5036 if (PropParentMap) {
5037 delete PropParentMap;
5038 PropParentMap = 0;
5039 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005040 // This synthesizes and inserts the block "impl" struct, invoke function,
5041 // and any copy/dispose helper functions.
5042 InsertBlockLiteralsWithinFunction(FD);
5043 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005044 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005045 return;
5046 }
5047 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005048 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005049 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005050 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005051 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005052 Body =
5053 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5054 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005055 CurrentBody = 0;
5056 if (PropParentMap) {
5057 delete PropParentMap;
5058 PropParentMap = 0;
5059 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005060 InsertBlockLiteralsWithinMethod(MD);
5061 CurMethodDef = 0;
5062 }
5063 }
5064 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5065 ClassImplementation.push_back(CI);
5066 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5067 CategoryImplementation.push_back(CI);
5068 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5069 RewriteForwardClassDecl(CD);
5070 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5071 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005072 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005073 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005074 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005075 CheckFunctionPointerDecl(VD->getType(), VD);
5076 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005077 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005078 RewriteCastExpr(CE);
5079 }
5080 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005081 } else if (VD->getType()->isRecordType()) {
5082 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5083 if (RD->isDefinition())
5084 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005085 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005086 if (VD->getInit()) {
5087 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005088 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005089 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005090 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005091 CurrentBody = 0;
5092 if (PropParentMap) {
5093 delete PropParentMap;
5094 PropParentMap = 0;
5095 }
Mike Stump11289f42009-09-09 15:08:12 +00005096 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005097 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005098 GlobalVarDecl = 0;
5099
5100 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005101 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005102 RewriteCastExpr(CE);
5103 }
5104 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005105 return;
5106 }
5107 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005108 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005109 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005110 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005111 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005112 else if (TD->getUnderlyingType()->isRecordType()) {
5113 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5114 if (RD->isDefinition())
5115 RewriteRecordBody(RD);
5116 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005117 return;
5118 }
5119 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005120 if (RD->isDefinition())
5121 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005122 return;
5123 }
5124 // Nothing yet.
5125}
5126
Chris Lattnercf169832009-03-28 04:11:33 +00005127void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005128 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005129
Steve Narofff4b992a2008-10-28 20:29:00 +00005130 // Rewrite tabs if we care.
5131 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005132
Steve Narofff4b992a2008-10-28 20:29:00 +00005133 if (Diags.hasErrorOccurred())
5134 return;
Mike Stump11289f42009-09-09 15:08:12 +00005135
Steve Narofff4b992a2008-10-28 20:29:00 +00005136 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005137
Steve Naroffd9803712009-04-29 16:37:50 +00005138 // Here's a great place to add any extra declarations that may be needed.
5139 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005140 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005141 E = ProtocolExprDecls.end(); I != E; ++I)
5142 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5143
Mike Stump11289f42009-09-09 15:08:12 +00005144 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005145 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005146 if (ClassImplementation.size() || CategoryImplementation.size())
5147 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005148
Steve Narofff4b992a2008-10-28 20:29:00 +00005149 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5150 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005151 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005152 Rewrite.getRewriteBufferFor(MainFileID)) {
5153 //printf("Changed:\n");
5154 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5155 } else {
5156 fprintf(stderr, "No changes\n");
5157 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005158
Steve Naroffd9803712009-04-29 16:37:50 +00005159 if (ClassImplementation.size() || CategoryImplementation.size() ||
5160 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005161 // Rewrite Objective-c meta data*
5162 std::string ResultStr;
5163 SynthesizeMetaDataIntoBuffer(ResultStr);
5164 // Emit metadata.
5165 *OutFile << ResultStr;
5166 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005167 OutFile->flush();
5168}
5169