blob: f7855fa3a41d72836be085352ba9ea062e5b9013 [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"
Chris Lattnere99c8322007-10-11 00:43:27 +000028using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000029using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000030
Chris Lattnere99c8322007-10-11 00:43:27 +000031namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000032 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000033 enum {
34 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
35 block, ... */
36 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
37 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
38 __block variable */
39 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
40 helpers */
41 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
42 support routines */
43 BLOCK_BYREF_CURRENT_MAX = 256
44 };
45
46 enum {
47 BLOCK_NEEDS_FREE = (1 << 24),
48 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
49 BLOCK_HAS_CXX_OBJ = (1 << 26),
50 BLOCK_IS_GC = (1 << 27),
51 BLOCK_IS_GLOBAL = (1 << 28),
52 BLOCK_HAS_DESCRIPTOR = (1 << 29)
53 };
54
Chris Lattner0bd1c972007-10-16 21:07:07 +000055 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000056 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000057 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000058 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000059 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattnerc6d91c02007-10-17 22:35:30 +000061 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000062 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000063 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000064 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000065 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000066 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000067
Ted Kremenek1b0ea822008-01-07 19:49:32 +000068 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
69 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
70 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000071 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000072 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
73 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000074 llvm::SmallVector<Stmt *, 32> Stmts;
75 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000076 // Remember all the @protocol(<expr>) expressions.
77 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Mike Stump11289f42009-09-09 15:08:12 +000078
Steve Naroffce8e8862008-03-15 00:55:56 +000079 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000080
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000081 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000082 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000083 FunctionDecl *MsgSendStretFunctionDecl;
84 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000085 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000086 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000087 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000088 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000089 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000090 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000091
Steve Naroffa397efd2007-11-03 11:27:19 +000092 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000093 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000094 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000095
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000096 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000097 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +000098
Steve Naroff7fa2f042007-11-15 10:28:18 +000099 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000100 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +0000101 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +0000102 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000103
Steve Naroffd9803712009-04-29 16:37:50 +0000104 TypeDecl *ProtocolTypeDecl;
105 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +0000106
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000107 // Needed for header files being rewritten
108 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +0000109
Steve Narofff9e7c902008-03-28 22:26:09 +0000110 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +0000111 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +0000112
113 bool SilenceRewriteMacroWarning;
114
Steve Naroff00a31762008-03-27 22:29:16 +0000115 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000116
117 // Block expressions.
118 llvm::SmallVector<BlockExpr *, 32> Blocks;
119 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
120 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +0000121
Steve Naroff677ab3a2008-10-27 17:20:55 +0000122 // Block related declarations.
123 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
124 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
125 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
126
127 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
128
Steve Naroff4588d0f2008-12-04 16:24:46 +0000129 // This maps a property to it's assignment statement.
130 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000131 // This maps a property to it's synthesied message expression.
132 // This allows us to rewrite chained getters (e.g. o.a.b.c).
133 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000134
Steve Naroff22216db2008-12-04 23:50:32 +0000135 // This maps an original source AST to it's rewritten form. This allows
136 // us to avoid rewriting the same node twice (which is very uncommon).
137 // This is needed to support some of the exotic property rewriting.
138 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000139
Steve Naroff677ab3a2008-10-27 17:20:55 +0000140 FunctionDecl *CurFunctionDef;
Steve Naroffd8907b72008-10-29 18:15:37 +0000141 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000142
Steve Naroff08628db2008-12-09 12:56:34 +0000143 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000144
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000145 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000146 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000147 virtual void Initialize(ASTContext &context);
148
Chris Lattner3c799d72007-10-24 17:06:59 +0000149 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000150 virtual void HandleTopLevelDecl(DeclGroupRef D) {
151 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
152 HandleTopLevelSingleDecl(*I);
153 }
154 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000155 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000156 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000157 Diagnostic &D, const LangOptions &LOpts,
158 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000159
160 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000161
Chris Lattnercf169832009-03-28 04:11:33 +0000162 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000163
Chris Lattner2e0d2602008-01-31 19:37:57 +0000164 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000165 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000166
Steve Naroff22216db2008-12-04 23:50:32 +0000167 if (ReplacingStmt)
168 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000169
Steve Naroff08628db2008-12-09 12:56:34 +0000170 if (DisableReplaceStmt)
171 return; // Used when rewriting the assignment of a property setter.
172
Steve Naroff22216db2008-12-04 23:50:32 +0000173 // If replacement succeeded or warning disabled return with no warning.
174 if (!Rewrite.ReplaceStmt(Old, New)) {
175 ReplacedNodes[Old] = New;
176 return;
177 }
178 if (SilenceRewriteMacroWarning)
179 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000180 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
181 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000182 }
Steve Naroff08628db2008-12-09 12:56:34 +0000183
184 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
185 // Measaure the old text.
186 int Size = Rewrite.getRangeSize(SrcRange);
187 if (Size == -1) {
188 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
189 << Old->getSourceRange();
190 return;
191 }
192 // Get the new text.
193 std::string SStr;
194 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000195 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000196 const std::string &Str = S.str();
197
198 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000199 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000200 ReplacedNodes[Old] = New;
201 return;
202 }
203 if (SilenceRewriteMacroWarning)
204 return;
205 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
206 << Old->getSourceRange();
207 }
208
Steve Naroff00a31762008-03-27 22:29:16 +0000209 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
210 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000211 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000212 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
213 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000214 SilenceRewriteMacroWarning)
215 return;
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner1780a852008-01-31 19:42:41 +0000217 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
218 }
Mike Stump11289f42009-09-09 15:08:12 +0000219
Chris Lattner9cc55f52008-01-31 19:51:04 +0000220 void RemoveText(SourceLocation Loc, unsigned StrLen) {
221 // If removal succeeded or warning disabled return with no warning.
222 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
223 return;
Mike Stump11289f42009-09-09 15:08:12 +0000224
Chris Lattner9cc55f52008-01-31 19:51:04 +0000225 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
226 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000227
Chris Lattner9cc55f52008-01-31 19:51:04 +0000228 void ReplaceText(SourceLocation Start, unsigned OrigLength,
229 const char *NewStr, unsigned NewLength) {
230 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000231 if (!Rewrite.ReplaceText(Start, OrigLength,
232 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000233 SilenceRewriteMacroWarning)
234 return;
Mike Stump11289f42009-09-09 15:08:12 +0000235
Chris Lattner9cc55f52008-01-31 19:51:04 +0000236 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
237 }
Mike Stump11289f42009-09-09 15:08:12 +0000238
Chris Lattner3c799d72007-10-24 17:06:59 +0000239 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000240 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000241 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000243 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000244 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
245 ObjCImplementationDecl *IMD,
246 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000247 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000248 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000249 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
250 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
251 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
252 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
253 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000254 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000255 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000256 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000257 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000258 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000259 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000260 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000261 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000262 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000263
Chris Lattner3c799d72007-10-24 17:06:59 +0000264 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000265 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000266 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000267
Steve Naroff1042ff32008-12-08 16:43:47 +0000268 Stmt *CurrentBody;
269 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000270
Chris Lattner69534692007-10-24 16:57:36 +0000271 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000272 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000273 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000274 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000275 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000276 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000277 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000278 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000279 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000280 void WarnAboutReturnGotoStmts(Stmt *S);
281 void HasReturnStmts(Stmt *S, bool &hasReturns);
282 void RewriteTryReturnStmts(Stmt *S);
283 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000284 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000285 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000286 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
287 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
288 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000289 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
290 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000291 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000292 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000293 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000294 Stmt *RewriteBreakStmt(BreakStmt *S);
295 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000296 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000297
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000298 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000299 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000300 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000301 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000302 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000303 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000304 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000305 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000306 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000307
Chris Lattner3c799d72007-10-24 17:06:59 +0000308 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000309 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000310 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000311
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000312 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000313 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000314
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000315 template<typename MethodIterator>
316 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
317 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000318 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000319 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000320 const char *ClassName,
321 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000322
Steve Naroffd9803712009-04-29 16:37:50 +0000323 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
324 const char *prefix,
325 const char *ClassName,
326 std::string &Result);
327 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000328 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000329 const char *ClassName,
330 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000331 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000332 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000333 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
334 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000335 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000336 void RewriteImplementations();
337 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000338
Steve Naroff677ab3a2008-10-27 17:20:55 +0000339 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000340 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000341 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000342
Steve Naroff677ab3a2008-10-27 17:20:55 +0000343 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
344 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000345
346 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000347 void RewriteBlockCall(CallExpr *Exp);
348 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000349 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +0000350 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +0000351 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000352 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000353
354 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000355 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000356 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000357 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000358 std::string SynthesizeBlockImpl(BlockExpr *CE,
359 std::string Tag, std::string Desc);
360 std::string SynthesizeBlockDescriptor(std::string DescTag,
361 std::string ImplTag,
362 int i, const char *funcName,
363 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000364 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000365 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
366 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000367 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000368
Steve Naroff677ab3a2008-10-27 17:20:55 +0000369 void CollectBlockDeclRefInfo(BlockExpr *Exp);
370 void GetBlockCallExprs(Stmt *S);
371 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Steve Naroff677ab3a2008-10-27 17:20:55 +0000373 // We avoid calling Type::isBlockPointerType(), since it operates on the
374 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000375 bool isTopLevelBlockPointerType(QualType T) {
376 return isa<BlockPointerType>(T);
377 }
Mike Stump11289f42009-09-09 15:08:12 +0000378
Steve Naroff677ab3a2008-10-27 17:20:55 +0000379 // FIXME: This predicate seems like it would be useful to add to ASTContext.
380 bool isObjCType(QualType T) {
381 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
382 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000383
Steve Naroff677ab3a2008-10-27 17:20:55 +0000384 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000385
Steve Naroff677ab3a2008-10-27 17:20:55 +0000386 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
387 OCT == Context->getCanonicalType(Context->getObjCClassType()))
388 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000389
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000390 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000391 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000392 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000393 return true;
394 }
395 return false;
396 }
397 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000398 void GetExtentOfArgList(const char *Name, const char *&LParen,
399 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000400 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000401
Steve Narofff4b992a2008-10-28 20:29:00 +0000402 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000403 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000404
Steve Naroffd9803712009-04-29 16:37:50 +0000405 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000406 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000407 if (From[i] == '"')
408 To += "\\\"";
409 else
410 To += From[i];
411 }
412 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000413 };
414}
415
Mike Stump11289f42009-09-09 15:08:12 +0000416void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
417 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000418 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000419 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000420 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000421 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000422 // All the args are checked/rewritten. Don't call twice!
423 RewriteBlockPointerDecl(D);
424 break;
425 }
426 }
427}
428
429void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000430 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000431 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000432 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000433}
434
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000435static bool IsHeaderFile(const std::string &Filename) {
436 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000437
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000438 if (DotPos == std::string::npos) {
439 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000440 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000441 }
Mike Stump11289f42009-09-09 15:08:12 +0000442
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000443 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
444 // C header: .h
445 // C++ header: .hh or .H;
446 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000447}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000448
Eli Friedman94cf21e2009-05-18 22:20:00 +0000449RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000450 Diagnostic &D, const LangOptions &LOpts,
451 bool silenceMacroWarn)
452 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
453 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000454 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000455 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000456 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000457 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000458 "rewriter doesn't support user-specified control flow semantics "
459 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000460}
461
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000462ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
463 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000464 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000465 const LangOptions &LOpts,
466 bool SilenceRewriteMacroWarning) {
467 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000468}
Chris Lattnere99c8322007-10-11 00:43:27 +0000469
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000470void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000471 Context = &context;
472 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000473 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000474 MsgSendFunctionDecl = 0;
475 MsgSendSuperFunctionDecl = 0;
476 MsgSendStretFunctionDecl = 0;
477 MsgSendSuperStretFunctionDecl = 0;
478 MsgSendFpretFunctionDecl = 0;
479 GetClassFunctionDecl = 0;
480 GetMetaClassFunctionDecl = 0;
481 SelGetUidFunctionDecl = 0;
482 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000483 ConstantStringClassReference = 0;
484 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000485 CurMethodDef = 0;
486 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000487 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000488 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000489 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000490 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000491 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000492 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000493 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000494 PropParentMap = 0;
495 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000496 DisableReplaceStmt = false;
Mike Stump11289f42009-09-09 15:08:12 +0000497
Chris Lattner187f6262008-01-31 19:38:44 +0000498 // Get the ID and start/end of the main file.
499 MainFileID = SM->getMainFileID();
500 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
501 MainFileStart = MainBuf->getBufferStart();
502 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000503
Chris Lattner184e65d2009-04-14 23:22:57 +0000504 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000505
Chris Lattner187f6262008-01-31 19:38:44 +0000506 // declaring objc_selector outside the parameter list removes a silly
507 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000508 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000509 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000510 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000511 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000512 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000513 if (LangOpts.Microsoft) {
514 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000515 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
516 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000517 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000518 }
Steve Naroff00a31762008-03-27 22:29:16 +0000519 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000520 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
521 Preamble += "typedef struct objc_object Protocol;\n";
522 Preamble += "#define _REWRITER_typedef_Protocol\n";
523 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000524 if (LangOpts.Microsoft) {
525 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
526 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
527 } else
528 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
529 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000530 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000531 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000532 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000533 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000534 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000535 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000536 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000537 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000538 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000539 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000540 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000541 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000542 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000543 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
544 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
545 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
546 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
547 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000548 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000549 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000550 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
551 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
552 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000553 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
554 Preamble += "struct __objcFastEnumerationState {\n\t";
555 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000556 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000557 Preamble += "unsigned long *mutationsPtr;\n\t";
558 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000559 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000560 Preamble += "#define __FASTENUMERATIONSTATE\n";
561 Preamble += "#endif\n";
562 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
563 Preamble += "struct __NSConstantStringImpl {\n";
564 Preamble += " int *isa;\n";
565 Preamble += " int flags;\n";
566 Preamble += " char *str;\n";
567 Preamble += " long length;\n";
568 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000569 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
570 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
571 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000573 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000574 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
575 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000576 // Blocks preamble.
577 Preamble += "#ifndef BLOCK_IMPL\n";
578 Preamble += "#define BLOCK_IMPL\n";
579 Preamble += "struct __block_impl {\n";
580 Preamble += " void *isa;\n";
581 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000582 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000583 Preamble += " void *FuncPtr;\n";
584 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000585 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000586 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000587 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
588 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
589 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
590 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
591 Preamble += "#else\n";
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +0000592 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_assign(void *, const void *, const int);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000594 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
595 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
596 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000597 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000598 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000599 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
600 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000601 Preamble += "#define __attribute__(X)\n";
602 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000603 else
604 Preamble += "#define __block\n";
Chris Lattner187f6262008-01-31 19:38:44 +0000605}
606
607
Chris Lattner3c799d72007-10-24 17:06:59 +0000608//===----------------------------------------------------------------------===//
609// Top Level Driver Code
610//===----------------------------------------------------------------------===//
611
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000612void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000613 // Two cases: either the decl could be in the main file, or it could be in a
614 // #included file. If the former, rewrite it now. If the later, check to see
615 // if we rewrote the #include/#import.
616 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000617 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000618
Chris Lattner0bd1c972007-10-16 21:07:07 +0000619 // If this is for a builtin, ignore it.
620 if (Loc.isInvalid()) return;
621
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000622 // Look for built-in declarations that we need to refer during the rewrite.
623 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000624 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000625 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000626 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000627 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000628 ConstantStringClassReference = FVD;
629 return;
630 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000631 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000632 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000633 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000634 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000635 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000636 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000637 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000638 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000639 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000640 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
641 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000642 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
643 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000644 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000645 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000646 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000647 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000648 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000649 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000650}
651
Chris Lattner3c799d72007-10-24 17:06:59 +0000652//===----------------------------------------------------------------------===//
653// Syntactic (non-AST) Rewriting Code
654//===----------------------------------------------------------------------===//
655
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000656void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000657 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000658 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
659 const char *MainBufStart = MainBuf.first;
660 const char *MainBufEnd = MainBuf.second;
661 size_t ImportLen = strlen("import");
662 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000663
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000664 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000665 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
666 if (*BufPtr == '#') {
667 if (++BufPtr == MainBufEnd)
668 return;
669 while (*BufPtr == ' ' || *BufPtr == '\t')
670 if (++BufPtr == MainBufEnd)
671 return;
672 if (!strncmp(BufPtr, "import", ImportLen)) {
673 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000674 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000675 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000676 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000677 BufPtr += ImportLen;
678 }
679 }
680 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000681}
682
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000683void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000684 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
685 const char *MainBufStart = MainBuf.first;
686 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000687
Chris Lattner3c799d72007-10-24 17:06:59 +0000688 // Loop over the whole file, looking for tabs.
689 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
690 if (*BufPtr != '\t')
691 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000692
Chris Lattner3c799d72007-10-24 17:06:59 +0000693 // Okay, we found a tab. This tab will turn into at least one character,
694 // but it depends on which 'virtual column' it is in. Compute that now.
695 unsigned VCol = 0;
696 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
697 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
698 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner3c799d72007-10-24 17:06:59 +0000700 // Okay, now that we know the virtual column, we know how many spaces to
701 // insert. We assume 8-character tab-stops.
702 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000703
Chris Lattner3c799d72007-10-24 17:06:59 +0000704 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000705 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
706 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000707
Chris Lattner3c799d72007-10-24 17:06:59 +0000708 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000709 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000710 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000711}
712
Steve Naroff9af94912008-12-02 15:48:25 +0000713static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
714 ObjCIvarDecl *OID) {
715 std::string S;
716 S = "((struct ";
717 S += ClassDecl->getIdentifier()->getName();
718 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000719 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000720 return S;
721}
722
Steve Naroffc038b3a2008-12-02 17:36:43 +0000723void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
724 ObjCImplementationDecl *IMD,
725 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000726 SourceLocation startLoc = PID->getLocStart();
727 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000728 const char *startBuf = SM->getCharacterData(startLoc);
729 assert((*startBuf == '@') && "bogus @synthesize location");
730 const char *semiBuf = strchr(startBuf, ';');
731 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000732 SourceLocation onePastSemiLoc =
733 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000734
735 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
736 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000737
Steve Naroff9af94912008-12-02 15:48:25 +0000738 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000739 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000740 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000741 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000742
Steve Naroff003d00e2008-12-02 16:05:55 +0000743 if (!OID)
744 return;
Mike Stump11289f42009-09-09 15:08:12 +0000745
Steve Naroff003d00e2008-12-02 16:05:55 +0000746 std::string Getr;
747 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
748 Getr += "{ ";
749 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000750 // FIXME: deal with code generation implications for various property
751 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000752 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000753 Getr += "return " + getIvarAccessString(ClassDecl, OID);
754 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000755 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000756 if (PD->isReadOnly())
757 return;
Mike Stump11289f42009-09-09 15:08:12 +0000758
Steve Naroff9af94912008-12-02 15:48:25 +0000759 // Generate the 'setter' function.
760 std::string Setr;
761 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000762 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000763 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000764 // FIXME: deal with code generation implications for various property
765 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000766 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000767 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000768 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000769 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000770 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000771}
Chris Lattner16a0de42007-10-11 18:38:32 +0000772
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000773void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000774 // Get the start location and compute the semi location.
775 SourceLocation startLoc = ClassDecl->getLocation();
776 const char *startBuf = SM->getCharacterData(startLoc);
777 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000778
Chris Lattner3c799d72007-10-24 17:06:59 +0000779 // Translate to typedef's that forward reference structs with the same name
780 // as the class. As a convenience, we include the original declaration
781 // as a comment.
782 std::string typedefString;
783 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000784 typedefString.append(startBuf, semiPtr-startBuf+1);
785 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000786 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
787 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000788 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000789 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000790 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000791 typedefString += "\n";
792 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000793 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000794 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000795 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000796 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000797 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000798 }
Mike Stump11289f42009-09-09 15:08:12 +0000799
Steve Naroff574440f2007-10-24 22:48:43 +0000800 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000801 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000802 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000803}
804
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000805void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000806 SourceLocation LocStart = Method->getLocStart();
807 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000808
Chris Lattner88ea93e2009-02-04 01:06:56 +0000809 if (SM->getInstantiationLineNumber(LocEnd) >
810 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000811 InsertText(LocStart, "#if 0\n", 6);
812 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000813 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000814 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000815 }
816}
817
Mike Stump11289f42009-09-09 15:08:12 +0000818void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000819 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000820
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000821 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000822
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000823 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000824}
825
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000826void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000827 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000828
Steve Naroff5448cf62007-10-30 13:30:57 +0000829 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000830 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000831
832 for (ObjCCategoryDecl::instmeth_iterator
833 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000834 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000835 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000836 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000837 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000838 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000839 RewriteMethodDeclaration(*I);
840
Steve Naroff5448cf62007-10-30 13:30:57 +0000841 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000842 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000843}
844
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000845void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000846 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000847
Steve Narofff921385f2007-10-30 16:42:30 +0000848 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000849
Steve Narofff921385f2007-10-30 16:42:30 +0000850 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000851 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000852
853 for (ObjCProtocolDecl::instmeth_iterator
854 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000855 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000856 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000857 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000858 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000859 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000860 RewriteMethodDeclaration(*I);
861
Steve Narofff921385f2007-10-30 16:42:30 +0000862 // Lastly, comment out the @end.
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000863 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000864 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000865
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000866 // Must comment out @optional/@required
867 const char *startBuf = SM->getCharacterData(LocStart);
868 const char *endBuf = SM->getCharacterData(LocEnd);
869 for (const char *p = startBuf; p < endBuf; p++) {
870 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
871 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000872 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000873 ReplaceText(OptionalLoc, strlen("@optional"),
874 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000875
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000876 }
877 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
878 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000879 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000880 ReplaceText(OptionalLoc, strlen("@required"),
881 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000882
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000883 }
884 }
Steve Narofff921385f2007-10-30 16:42:30 +0000885}
886
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000887void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000888 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000889 if (LocStart.isInvalid())
890 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000891 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000892 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000893}
894
Mike Stump11289f42009-09-09 15:08:12 +0000895void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000896 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000897 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000898 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000899 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000900 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000901 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000902 else if (OMD->getResultType()->isFunctionPointerType() ||
903 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000904 // needs special handling, since pointer-to-functions have special
905 // syntax (where a decaration models use).
906 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000907 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000908 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000909 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000910 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000911 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000912 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000913 ResultStr += FPRetType->getResultType().getAsString();
914 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000915 }
916 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000917 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000918 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000919
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000920 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000921 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregorffca3a22009-01-09 17:18:27 +0000923 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000924 NameStr += "_I_";
925 else
926 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000927
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000928 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000929 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000930
931 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000932 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000933 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000934 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000935 }
Mike Stump11289f42009-09-09 15:08:12 +0000936 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000937 {
938 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000939 int len = selString.size();
940 for (int i = 0; i < len; i++)
941 if (selString[i] == ':')
942 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000943 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000944 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000945 // Remember this name for metadata emission
946 MethodInternalNames[OMD] = NameStr;
947 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000948
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000949 // Rewrite arguments
950 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000951
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000952 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000953 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000954 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000955 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000956 if (!LangOpts.Microsoft) {
957 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
958 ResultStr += "struct ";
959 }
960 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000961 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000962 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000963 }
964 else
Steve Naroffd9803712009-04-29 16:37:50 +0000965 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000966
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000967 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000968 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000969 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000970
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000971 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000972 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
973 E = OMD->param_end(); PI != E; ++PI) {
974 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000975 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000976 if (PDecl->getType()->isObjCQualifiedIdType()) {
977 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000978 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000979 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000980 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000981 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000982 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000983 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000984 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
985 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000986 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000987 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000988 ResultStr += Name;
989 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000990 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000991 if (OMD->isVariadic())
992 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000993 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +0000994
Steve Naroffb067bbd2008-07-16 14:40:40 +0000995 if (FPRetType) {
996 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +0000997
Steve Naroffb067bbd2008-07-16 14:40:40 +0000998 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000999 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001000 ResultStr += "(";
1001 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1002 if (i) ResultStr += ", ";
1003 std::string ParamStr = FT->getArgType(i).getAsString();
1004 ResultStr += ParamStr;
1005 }
1006 if (FT->isVariadic()) {
1007 if (FT->getNumArgs()) ResultStr += ", ";
1008 ResultStr += "...";
1009 }
1010 ResultStr += ")";
1011 } else {
1012 ResultStr += "()";
1013 }
1014 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001015}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001016void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001017 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1018 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001019
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001020 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001021 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001022 else
Chris Lattner1780a852008-01-31 19:42:41 +00001023 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +00001024
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001025 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001026 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1027 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001028 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001029 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001030 ObjCMethodDecl *OMD = *I;
1031 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001032 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001033 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001034
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001035 const char *startBuf = SM->getCharacterData(LocStart);
1036 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001037 ReplaceText(LocStart, endBuf-startBuf,
1038 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001039 }
Mike Stump11289f42009-09-09 15:08:12 +00001040
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001041 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001042 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1043 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001044 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001045 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001046 ObjCMethodDecl *OMD = *I;
1047 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001048 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001049 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001050
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001051 const char *startBuf = SM->getCharacterData(LocStart);
1052 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001053 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001054 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001055 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001056 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001057 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001058 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001059 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001060 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001061 }
1062
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001063 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001064 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001065 else
Mike Stump11289f42009-09-09 15:08:12 +00001066 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001067}
1068
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001069void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001070 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001071 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001072 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001073 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001074 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001075 ResultStr += "\n";
1076 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001077 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001078 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001079 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001080 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001081 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001082 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001083 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001084 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001085 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001086
1087 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001088 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001089 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001090 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001091 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001092 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001093 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001094 for (ObjCInterfaceDecl::classmeth_iterator
1095 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001096 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001097 RewriteMethodDeclaration(*I);
1098
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001099 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001100 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001101}
1102
Steve Naroff08628db2008-12-09 12:56:34 +00001103Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1104 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001105 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1106 // This allows us to reuse all the fun and games in SynthMessageExpr().
1107 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1108 ObjCMessageExpr *MsgExpr;
1109 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1110 llvm::SmallVector<Expr *, 1> ExprVec;
1111 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001112
Steve Naroff1042ff32008-12-08 16:43:47 +00001113 Stmt *Receiver = PropRefExpr->getBase();
1114 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1115 if (PRE && PropGetters[PRE]) {
1116 // This allows us to handle chain/nested property getters.
1117 Receiver = PropGetters[PRE];
1118 }
Mike Stump11289f42009-09-09 15:08:12 +00001119 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1120 PDecl->getSetterName(), PDecl->getType(),
1121 PDecl->getSetterMethodDecl(),
1122 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001123 &ExprVec[0], 1);
1124 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001125
Steve Naroff4588d0f2008-12-04 16:24:46 +00001126 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001127 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001128 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001129 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1130 // to things that stay around.
1131 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001132 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001133}
1134
Steve Naroff4588d0f2008-12-04 16:24:46 +00001135Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001136 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1137 // This allows us to reuse all the fun and games in SynthMessageExpr().
1138 ObjCMessageExpr *MsgExpr;
1139 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001140
Steve Naroff1042ff32008-12-08 16:43:47 +00001141 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001142
Steve Naroff1042ff32008-12-08 16:43:47 +00001143 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1144 if (PRE && PropGetters[PRE]) {
1145 // This allows us to handle chain/nested property getters.
1146 Receiver = PropGetters[PRE];
1147 }
Mike Stump11289f42009-09-09 15:08:12 +00001148 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1149 PDecl->getGetterName(), PDecl->getType(),
1150 PDecl->getGetterMethodDecl(),
1151 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001152 0, 0);
1153
Steve Naroff22216db2008-12-04 23:50:32 +00001154 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001155
1156 if (!PropParentMap)
1157 PropParentMap = new ParentMap(CurrentBody);
1158
1159 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1160 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1161 // We stash away the ReplacingStmt since actually doing the
1162 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1163 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001164 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1165 // to things that stay around.
1166 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001167 return PropRefExpr; // return the original...
1168 } else {
1169 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001170 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001171 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1172 // to things that stay around.
1173 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001174 return ReplacingStmt;
1175 }
Steve Narofff326f402008-12-03 00:56:33 +00001176}
1177
Mike Stump11289f42009-09-09 15:08:12 +00001178Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001179 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001180 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001181 if (CurMethodDef) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001182 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001183 ObjCInterfaceType *iFaceDecl =
1184 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001185 // lookup which class implements the instance variable.
1186 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001187 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001188 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001189 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001190
Steve Naroffb1c02372008-05-08 17:52:16 +00001191 // Synthesize an explicit cast to gain access to the ivar.
1192 std::string RecName = clsDeclared->getIdentifier()->getName();
1193 RecName += "_IMPL";
1194 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001195 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001196 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001197 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1198 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001199 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001200 CastExpr::CK_Unknown,
1201 IV->getBase(),
1202 castT,SourceLocation(),
1203 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001204 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001205 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1206 IV->getBase()->getLocEnd(),
1207 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001208 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001209 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001210 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1211 IV->getLocation(),
1212 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001213 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001214 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001215 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001216 }
Mike Stump11289f42009-09-09 15:08:12 +00001217
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001218 ReplaceStmt(IV->getBase(), PE);
1219 // Cannot delete IV->getBase(), since PE points to it.
1220 // Replace the old base with the cast. This is important when doing
1221 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001222 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001223 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001224 }
Steve Naroff24840f62008-04-18 21:55:08 +00001225 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001226 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001227
Steve Naroff29ce4e52008-05-06 23:20:07 +00001228 // Explicit ivar refs need to have a cast inserted.
1229 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001230 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001231 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001232 // lookup which class implements the instance variable.
1233 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001234 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001235 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001236 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001237
Steve Naroff29ce4e52008-05-06 23:20:07 +00001238 // Synthesize an explicit cast to gain access to the ivar.
1239 std::string RecName = clsDeclared->getIdentifier()->getName();
1240 RecName += "_IMPL";
1241 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001242 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001243 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001244 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1245 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001246 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001247 CastExpr::CK_Unknown,
1248 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001249 castT, SourceLocation(),
1250 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001251 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001252 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001253 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001254 ReplaceStmt(IV->getBase(), PE);
1255 // Cannot delete IV->getBase(), since PE points to it.
1256 // Replace the old base with the cast. This is important when doing
1257 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001258 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001259 return IV;
1260 }
Steve Naroff05caa482007-11-15 11:33:00 +00001261 }
Steve Naroff24840f62008-04-18 21:55:08 +00001262 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001263}
1264
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001265/// SynthCountByEnumWithState - To print:
1266/// ((unsigned int (*)
1267/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001268/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001269/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001270/// "countByEnumeratingWithState:objects:count:"),
1271/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001272/// (id *)items, (unsigned int)16)
1273///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001274void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001275 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1276 "id *, unsigned int))(void *)objc_msgSend)";
1277 buf += "\n\t\t";
1278 buf += "((id)l_collection,\n\t\t";
1279 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1280 buf += "\n\t\t";
1281 buf += "&enumState, "
1282 "(id *)items, (unsigned int)16)";
1283}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001284
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001285/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1286/// statement to exit to its outer synthesized loop.
1287///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001288Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001289 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1290 return S;
1291 // replace break with goto __break_label
1292 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001293
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001294 SourceLocation startLoc = S->getLocStart();
1295 buf = "goto __break_label_";
1296 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001297 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001298
1299 return 0;
1300}
1301
1302/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1303/// statement to continue with its inner synthesized loop.
1304///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001305Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001306 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1307 return S;
1308 // replace continue with goto __continue_label
1309 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001310
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001311 SourceLocation startLoc = S->getLocStart();
1312 buf = "goto __continue_label_";
1313 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001314 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001315
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001316 return 0;
1317}
1318
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001319/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001320/// It rewrites:
1321/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001323/// Into:
1324/// {
Mike Stump11289f42009-09-09 15:08:12 +00001325/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001326/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001327/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001328/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001329/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001330/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001331/// if (limit) {
1332/// unsigned long startMutations = *enumState.mutationsPtr;
1333/// do {
1334/// unsigned long counter = 0;
1335/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001336/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001337/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001338/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001339/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001340/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001341/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001342/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001343/// objects:items count:16]);
1344/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001345/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001346/// }
1347/// else
1348/// elem = nil;
1349/// }
1350///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001351Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001352 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001353 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001354 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001355 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001356 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001357 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001358
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001359 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001360 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001361 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001362 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001363 std::string buf;
1364 buf = "\n{\n\t";
1365 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1366 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001367 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001368 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001369 if (ElementType->isObjCQualifiedIdType() ||
1370 ElementType->isObjCQualifiedInterfaceType())
1371 // Simply use 'id' for all qualified types.
1372 elementTypeAsString = "id";
1373 else
1374 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001375 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001376 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001377 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001378 buf += elementName;
1379 buf += ";\n\t";
1380 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001381 else {
1382 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001383 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001384 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1385 if (VD->getType()->isObjCQualifiedIdType() ||
1386 VD->getType()->isObjCQualifiedInterfaceType())
1387 // Simply use 'id' for all qualified types.
1388 elementTypeAsString = "id";
1389 else
1390 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001391 }
Mike Stump11289f42009-09-09 15:08:12 +00001392
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001393 // struct __objcFastEnumerationState enumState = { 0 };
1394 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1395 // id items[16];
1396 buf += "id items[16];\n\t";
1397 // id l_collection = (id)
1398 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001399 // Find start location of 'collection' the hard way!
1400 const char *startCollectionBuf = startBuf;
1401 startCollectionBuf += 3; // skip 'for'
1402 startCollectionBuf = strchr(startCollectionBuf, '(');
1403 startCollectionBuf++; // skip '('
1404 // find 'in' and skip it.
1405 while (*startCollectionBuf != ' ' ||
1406 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1407 (*(startCollectionBuf+3) != ' ' &&
1408 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1409 startCollectionBuf++;
1410 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001411
1412 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001413 ReplaceText(startLoc, startCollectionBuf - startBuf,
1414 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001415 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001416 SourceLocation rightParenLoc = S->getRParenLoc();
1417 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1418 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001419 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001420
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001421 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1422 // objects:items count:16];
1423 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001424 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001425 // ((unsigned int (*)
1426 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001427 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001428 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001429 // "countByEnumeratingWithState:objects:count:"),
1430 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001431 // (id *)items, (unsigned int)16);
1432 buf += "unsigned long limit =\n\t\t";
1433 SynthCountByEnumWithState(buf);
1434 buf += ";\n\t";
1435 /// if (limit) {
1436 /// unsigned long startMutations = *enumState.mutationsPtr;
1437 /// do {
1438 /// unsigned long counter = 0;
1439 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001440 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001441 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001442 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001443 buf += "if (limit) {\n\t";
1444 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1445 buf += "do {\n\t\t";
1446 buf += "unsigned long counter = 0;\n\t\t";
1447 buf += "do {\n\t\t\t";
1448 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1449 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1450 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001451 buf += " = (";
1452 buf += elementTypeAsString;
1453 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001454 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001455 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001456
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001457 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001458 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001459 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001460 /// objects:items count:16]);
1461 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001462 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001463 /// }
1464 /// else
1465 /// elem = nil;
1466 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001467 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001468 buf = ";\n\t";
1469 buf += "__continue_label_";
1470 buf += utostr(ObjCBcLabelNo.back());
1471 buf += ": ;";
1472 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001473 buf += "} while (counter < limit);\n\t";
1474 buf += "} while (limit = ";
1475 SynthCountByEnumWithState(buf);
1476 buf += ");\n\t";
1477 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001478 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001479 buf += "__break_label_";
1480 buf += utostr(ObjCBcLabelNo.back());
1481 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001482 buf += "}\n\t";
1483 buf += "else\n\t\t";
1484 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001485 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001486 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001487
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001488 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001489 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001490 if (isa<CompoundStmt>(S->getBody())) {
1491 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1492 InsertText(endBodyLoc, buf.c_str(), buf.size());
1493 } else {
1494 /* Need to treat single statements specially. For example:
1495 *
1496 * for (A *a in b) if (stuff()) break;
1497 * for (A *a in b) xxxyy;
1498 *
1499 * The following code simply scans ahead to the semi to find the actual end.
1500 */
1501 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1502 const char *semiBuf = strchr(stmtBuf, ';');
1503 assert(semiBuf && "Can't find ';'");
1504 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1505 InsertText(endBodyLoc, buf.c_str(), buf.size());
1506 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001507 Stmts.pop_back();
1508 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001509 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001510}
1511
Mike Stump11289f42009-09-09 15:08:12 +00001512/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001513/// This routine rewrites @synchronized(expr) stmt;
1514/// into:
1515/// objc_sync_enter(expr);
1516/// @try stmt @finally { objc_sync_exit(expr); }
1517///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001518Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001519 // Get the start location and compute the semi location.
1520 SourceLocation startLoc = S->getLocStart();
1521 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001522
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001523 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001524
1525 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001526 buf = "objc_sync_enter((id)";
1527 const char *lparenBuf = startBuf;
1528 while (*lparenBuf != '(') lparenBuf++;
1529 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001530 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1531 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001532 // been rewritten! (which implies the SourceLocation's are invalid).
1533 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001534 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001535 while (*endBuf != ')') endBuf--;
1536 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001537 buf = ");\n";
1538 // declare a new scope with two variables, _stack and _rethrow.
1539 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1540 buf += "int buf[18/*32-bit i386*/];\n";
1541 buf += "char *pointers[4];} _stack;\n";
1542 buf += "id volatile _rethrow = 0;\n";
1543 buf += "objc_exception_try_enter(&_stack);\n";
1544 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001545 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001546 startLoc = S->getSynchBody()->getLocEnd();
1547 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001548
Steve Naroffad7013b2008-08-19 13:04:19 +00001549 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001550 SourceLocation lastCurlyLoc = startLoc;
1551 buf = "}\nelse {\n";
1552 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001553 buf += "}\n";
1554 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001555 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001556
1557 std::string syncBuf;
1558 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001559 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001560 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001561 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001562 Context->getObjCIdType(),
1563 SourceLocation(),
1564 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001565 std::string syncExprBufS;
1566 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001567 syncExpr->printPretty(syncExprBuf, *Context, 0,
1568 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001569 syncBuf += syncExprBuf.str();
1570 syncBuf += ");";
1571
1572 buf += syncBuf;
1573 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001574 buf += "}\n";
1575 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001576
Chris Lattner9cc55f52008-01-31 19:51:04 +00001577 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001578
1579 bool hasReturns = false;
1580 HasReturnStmts(S->getSynchBody(), hasReturns);
1581 if (hasReturns)
1582 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1583
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001584 return 0;
1585}
1586
Steve Naroffec60b432009-12-05 21:43:12 +00001587void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1588{
Steve Naroff6d6da252008-12-05 17:03:39 +00001589 // Perform a bottom up traversal of all children.
1590 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1591 CI != E; ++CI)
1592 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001593 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001594
Steve Naroffec60b432009-12-05 21:43:12 +00001595 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001596 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001597 TryFinallyContainsReturnDiag);
1598 }
1599 return;
1600}
1601
Steve Naroffec60b432009-12-05 21:43:12 +00001602void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1603{
1604 // Perform a bottom up traversal of all children.
1605 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1606 CI != E; ++CI)
1607 if (*CI)
1608 HasReturnStmts(*CI, hasReturns);
1609
1610 if (isa<ReturnStmt>(S))
1611 hasReturns = true;
1612 return;
1613}
1614
1615void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1616 // Perform a bottom up traversal of all children.
1617 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1618 CI != E; ++CI)
1619 if (*CI) {
1620 RewriteTryReturnStmts(*CI);
1621 }
1622 if (isa<ReturnStmt>(S)) {
1623 SourceLocation startLoc = S->getLocStart();
1624 const char *startBuf = SM->getCharacterData(startLoc);
1625
1626 const char *semiBuf = strchr(startBuf, ';');
1627 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1628 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1629
1630 std::string buf;
1631 buf = "{ objc_exception_try_exit(&_stack); return";
1632
1633 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1634 InsertText(onePastSemiLoc, "}", 1);
1635 }
1636 return;
1637}
1638
1639void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1640 // Perform a bottom up traversal of all children.
1641 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1642 CI != E; ++CI)
1643 if (*CI) {
1644 RewriteSyncReturnStmts(*CI, syncExitBuf);
1645 }
1646 if (isa<ReturnStmt>(S)) {
1647 SourceLocation startLoc = S->getLocStart();
1648 const char *startBuf = SM->getCharacterData(startLoc);
1649
1650 const char *semiBuf = strchr(startBuf, ';');
1651 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1652 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1653
1654 std::string buf;
1655 buf = "{ objc_exception_try_exit(&_stack);";
1656 buf += syncExitBuf;
1657 buf += " return";
1658
1659 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1660 InsertText(onePastSemiLoc, "}", 1);
1661 }
1662 return;
1663}
1664
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001665Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001666 // Get the start location and compute the semi location.
1667 SourceLocation startLoc = S->getLocStart();
1668 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001669
Steve Naroffbf478ec2007-11-07 04:08:17 +00001670 assert((*startBuf == '@') && "bogus @try location");
1671
1672 std::string buf;
1673 // declare a new scope with two variables, _stack and _rethrow.
1674 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1675 buf += "int buf[18/*32-bit i386*/];\n";
1676 buf += "char *pointers[4];} _stack;\n";
1677 buf += "id volatile _rethrow = 0;\n";
1678 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001679 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001680
Chris Lattner9cc55f52008-01-31 19:51:04 +00001681 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001682
Steve Naroffbf478ec2007-11-07 04:08:17 +00001683 startLoc = S->getTryBody()->getLocEnd();
1684 startBuf = SM->getCharacterData(startLoc);
1685
1686 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001687
Steve Naroffbf478ec2007-11-07 04:08:17 +00001688 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001689 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1690 if (catchList) {
1691 startLoc = startLoc.getFileLocWithOffset(1);
1692 buf = " /* @catch begin */ else {\n";
1693 buf += " id _caught = objc_exception_extract(&_stack);\n";
1694 buf += " objc_exception_try_enter (&_stack);\n";
1695 buf += " if (_setjmp(_stack.buf))\n";
1696 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1697 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001698
Steve Naroffce2dca12008-07-16 15:31:30 +00001699 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001700 } else { /* no catch list */
1701 buf = "}\nelse {\n";
1702 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1703 buf += "}";
1704 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001705 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001706 bool sawIdTypedCatch = false;
1707 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001708 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001709 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001710
Mike Stump11289f42009-09-09 15:08:12 +00001711 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001712 buf = "if ("; // we are generating code for the first catch clause
1713 else
1714 buf = "else if (";
1715 startLoc = catchList->getLocStart();
1716 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001717
Steve Naroffbf478ec2007-11-07 04:08:17 +00001718 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001719
Steve Naroffbf478ec2007-11-07 04:08:17 +00001720 const char *lParenLoc = strchr(startBuf, '(');
1721
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001722 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001723 // Now rewrite the body...
1724 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001725 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1726 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001727 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1728 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001729 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001730
Steve Naroffedb5bc62008-02-01 20:02:07 +00001731 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001732 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001733 } else if (catchDecl) {
1734 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001735 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001736 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001737 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001738 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001739 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001740 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001741
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001742 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001743 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001744 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001745 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001746 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001747 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001748 }
1749 }
1750 // Now rewrite the body...
1751 lastCatchBody = catchList->getCatchBody();
1752 SourceLocation rParenLoc = catchList->getRParenLoc();
1753 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1754 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1755 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1756 assert((*rParenBuf == ')') && "bogus @catch paren location");
1757 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001758
Steve Naroffbf478ec2007-11-07 04:08:17 +00001759 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001760 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001761 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001762 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001763 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001764 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001765 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001766 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001767 catchList = catchList->getNextCatchStmt();
1768 }
1769 // Complete the catch list...
1770 if (lastCatchBody) {
1771 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001772 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1773 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001774
Steve Naroff4adbe312008-09-11 15:29:03 +00001775 // Insert the last (implicit) else clause *before* the right curly brace.
1776 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1777 buf = "} /* last catch end */\n";
1778 buf += "else {\n";
1779 buf += " _rethrow = _caught;\n";
1780 buf += " objc_exception_try_exit(&_stack);\n";
1781 buf += "} } /* @catch end */\n";
1782 if (!S->getFinallyStmt())
1783 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001784 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001785
Steve Naroffbf478ec2007-11-07 04:08:17 +00001786 // Set lastCurlyLoc
1787 lastCurlyLoc = lastCatchBody->getLocEnd();
1788 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001789 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001790 startLoc = finalStmt->getLocStart();
1791 startBuf = SM->getCharacterData(startLoc);
1792 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001793
Steve Naroffbf478ec2007-11-07 04:08:17 +00001794 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001795 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001796
Steve Naroffbf478ec2007-11-07 04:08:17 +00001797 Stmt *body = finalStmt->getFinallyBody();
1798 SourceLocation startLoc = body->getLocStart();
1799 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001800 assert(*SM->getCharacterData(startLoc) == '{' &&
1801 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001802 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001803 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001804
Steve Naroffbf478ec2007-11-07 04:08:17 +00001805 startLoc = startLoc.getFileLocWithOffset(1);
1806 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001807 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001808 endLoc = endLoc.getFileLocWithOffset(-1);
1809 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001810 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001811
Steve Naroffbf478ec2007-11-07 04:08:17 +00001812 // Set lastCurlyLoc
1813 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001814
Steve Naroff6d6da252008-12-05 17:03:39 +00001815 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001816 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001817 } else { /* no finally clause - make sure we synthesize an implicit one */
1818 buf = "{ /* implicit finally clause */\n";
1819 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1820 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1821 buf += "}";
1822 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001823
1824 // Now check for any return/continue/go statements within the @try.
1825 // The implicit finally clause won't called if the @try contains any
1826 // jump statements.
1827 bool hasReturns = false;
1828 HasReturnStmts(S->getTryBody(), hasReturns);
1829 if (hasReturns)
1830 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001831 }
1832 // Now emit the final closing curly brace...
1833 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1834 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001835 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001836 return 0;
1837}
1838
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001839Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001840 return 0;
1841}
1842
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001843Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001844 return 0;
1845}
1846
Mike Stump11289f42009-09-09 15:08:12 +00001847// This can't be done with ReplaceStmt(S, ThrowExpr), since
1848// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001849// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001850Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001851 // Get the start location and compute the semi location.
1852 SourceLocation startLoc = S->getLocStart();
1853 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001854
Steve Naroffa733c7f2007-11-07 15:32:26 +00001855 assert((*startBuf == '@') && "bogus @throw location");
1856
1857 std::string buf;
1858 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001859 if (S->getThrowExpr())
1860 buf = "objc_exception_throw(";
1861 else // add an implicit argument
1862 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001863
Steve Naroff29788342008-07-25 15:41:30 +00001864 // handle "@ throw" correctly.
1865 const char *wBuf = strchr(startBuf, 'w');
1866 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1867 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001868
Steve Naroffa733c7f2007-11-07 15:32:26 +00001869 const char *semiBuf = strchr(startBuf, ';');
1870 assert((*semiBuf == ';') && "@throw: can't find ';'");
1871 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1872 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001873 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001874 return 0;
1875}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001876
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001877Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001878 // Create a new string expression.
1879 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001880 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001881 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001882 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1883 StrEncoding.length(), false,StrType,
1884 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001885 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001886
Chris Lattner4431a1b2007-11-30 22:53:43 +00001887 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001888 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001889 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001890}
1891
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001892Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001893 if (!SelGetUidFunctionDecl)
1894 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001895 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1896 // Create a call to sel_registerName("selName").
1897 llvm::SmallVector<Expr*, 8> SelExprs;
1898 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001899 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001900 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001901 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001902 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001903 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1904 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001905 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001906 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001907 return SelExp;
1908}
1909
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001910CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001911 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001912 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001913 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001914
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001915 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001916 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001917
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001918 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001919 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001920 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001921 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001922 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001923 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001924
John McCall9dd450b2009-09-21 23:43:11 +00001925 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001926
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001927 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1928 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001929}
1930
Steve Naroff50d42052007-11-01 13:24:47 +00001931static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1932 const char *&startRef, const char *&endRef) {
1933 while (startBuf < endBuf) {
1934 if (*startBuf == '<')
1935 startRef = startBuf; // mark the start.
1936 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001937 if (startRef && *startRef == '<') {
1938 endRef = startBuf; // mark the end.
1939 return true;
1940 }
1941 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001942 }
1943 startBuf++;
1944 }
1945 return false;
1946}
1947
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001948static void scanToNextArgument(const char *&argRef) {
1949 int angle = 0;
1950 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1951 if (*argRef == '<')
1952 angle++;
1953 else if (*argRef == '>')
1954 angle--;
1955 argRef++;
1956 }
1957 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1958}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001959
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001960bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001961 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001962}
1963
Steve Naroff873bd842008-07-29 18:15:38 +00001964void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1965 QualType Type = E->getType();
1966 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001967 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001968
Steve Naroffdbfc6932008-11-19 21:15:47 +00001969 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1970 Loc = ECE->getLParenLoc();
1971 EndLoc = ECE->getRParenLoc();
1972 } else {
1973 Loc = E->getLocStart();
1974 EndLoc = E->getLocEnd();
1975 }
1976 // This will defend against trying to rewrite synthesized expressions.
1977 if (Loc.isInvalid() || EndLoc.isInvalid())
1978 return;
1979
Steve Naroff873bd842008-07-29 18:15:38 +00001980 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001981 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001982 const char *startRef = 0, *endRef = 0;
1983 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1984 // Get the locations of the startRef, endRef.
1985 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1986 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1987 // Comment out the protocol references.
1988 InsertText(LessLoc, "/*", 2);
1989 InsertText(GreaterLoc, "*/", 2);
1990 }
1991 }
1992}
1993
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001994void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001995 SourceLocation Loc;
1996 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001997 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001998 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1999 Loc = VD->getLocation();
2000 Type = VD->getType();
2001 }
2002 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2003 Loc = FD->getLocation();
2004 // Check for ObjC 'id' and class types that have been adorned with protocol
2005 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002006 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002007 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002008 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002009 if (!proto)
2010 return;
2011 Type = proto->getResultType();
2012 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002013 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2014 Loc = FD->getLocation();
2015 Type = FD->getType();
2016 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002017 else
2018 return;
Mike Stump11289f42009-09-09 15:08:12 +00002019
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002020 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002021 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002022
Steve Naroff50d42052007-11-01 13:24:47 +00002023 const char *endBuf = SM->getCharacterData(Loc);
2024 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002025 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002026 startBuf--; // scan backward (from the decl location) for return type.
2027 const char *startRef = 0, *endRef = 0;
2028 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2029 // Get the locations of the startRef, endRef.
2030 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2031 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2032 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002033 InsertText(LessLoc, "/*", 2);
2034 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002035 }
2036 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002037 if (!proto)
2038 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002039 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002040 const char *startBuf = SM->getCharacterData(Loc);
2041 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002042 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2043 if (needToScanForQualifiers(proto->getArgType(i))) {
2044 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002045
Steve Naroff50d42052007-11-01 13:24:47 +00002046 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002047 // scan forward (from the decl location) for argument types.
2048 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002049 const char *startRef = 0, *endRef = 0;
2050 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2051 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002052 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002053 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002054 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002055 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002056 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002057 InsertText(LessLoc, "/*", 2);
2058 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002059 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002060 startBuf = ++endBuf;
2061 }
2062 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002063 // If the function name is derived from a macro expansion, then the
2064 // argument buffer will not follow the name. Need to speak with Chris.
2065 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002066 startBuf++; // scan forward (from the decl location) for argument types.
2067 startBuf++;
2068 }
Steve Naroff50d42052007-11-01 13:24:47 +00002069 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002070}
2071
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002072// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002073void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002074 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2075 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002076 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002077 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002078 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002079 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002080 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002081 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002082 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002083 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002084}
2085
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002086void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002087 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002088 if (FD->getIdentifier() &&
2089 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002090 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002091 return;
2092 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002093 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002094}
2095
Steve Naroff17978c42008-03-11 17:37:02 +00002096// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002097void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002098 if (SuperContructorFunctionDecl)
2099 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002100 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002101 llvm::SmallVector<QualType, 16> ArgTys;
2102 QualType argT = Context->getObjCIdType();
2103 assert(!argT.isNull() && "Can't find 'id' type");
2104 ArgTys.push_back(argT);
2105 ArgTys.push_back(argT);
2106 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2107 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002108 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002109 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002110 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002111 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002112 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002113}
2114
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002115// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002116void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002117 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2118 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002119 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002120 assert(!argT.isNull() && "Can't find 'id' type");
2121 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002122 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002123 assert(!argT.isNull() && "Can't find 'SEL' type");
2124 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002125 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002126 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002127 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002128 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002129 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002130 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002131 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002132}
2133
Steve Naroff7fa2f042007-11-15 10:28:18 +00002134// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002135void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002136 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2137 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002138 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002139 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002140 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002141 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2142 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2143 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002144 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +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 Naroff7fa2f042007-11-15 10:28:18 +00002148 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002149 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002150 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +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 Naroff7fa2f042007-11-15 10:28:18 +00002154}
2155
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002156// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002157void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002158 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2159 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002160 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002161 assert(!argT.isNull() && "Can't find 'id' type");
2162 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002163 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002164 assert(!argT.isNull() && "Can't find 'SEL' type");
2165 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002166 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002167 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002168 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002169 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002170 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002171 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002172 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002173}
2174
Mike Stump11289f42009-09-09 15:08:12 +00002175// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002176// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002177void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002178 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002179 &Context->Idents.get("objc_msgSendSuper_stret");
2180 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002181 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002182 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002183 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002184 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2185 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2186 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002187 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002188 assert(!argT.isNull() && "Can't find 'SEL' type");
2189 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002190 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002191 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002192 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002193 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002194 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002195 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002196 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002197}
2198
Steve Naroff2e4e3852008-05-08 22:02:18 +00002199// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002200void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002201 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2202 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002203 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002204 assert(!argT.isNull() && "Can't find 'id' type");
2205 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002206 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002207 assert(!argT.isNull() && "Can't find 'SEL' type");
2208 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002209 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002210 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002211 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002212 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002213 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002214 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002215 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002216}
2217
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002218// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002219void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002220 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2221 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002222 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002223 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002224 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002225 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002226 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002227 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002228 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002229 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002230}
2231
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002232// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002233void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002234 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2235 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002236 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002237 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002238 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002239 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002240 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002241 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002242 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002243 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002244}
2245
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002246Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002247 QualType strType = getConstantStringStructType();
2248
2249 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002250
2251 std::string tmpName = InFileName;
2252 unsigned i;
2253 for (i=0; i < tmpName.length(); i++) {
2254 char c = tmpName.at(i);
2255 // replace any non alphanumeric characters with '_'.
2256 if (!isalpha(c) && (c < '0' || c > '9'))
2257 tmpName[i] = '_';
2258 }
2259 S += tmpName;
2260 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002261 S += utostr(NumObjCStringLiterals++);
2262
Steve Naroff00a31762008-03-27 22:29:16 +00002263 Preamble += "static __NSConstantStringImpl " + S;
2264 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2265 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002266 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002267 std::string prettyBufS;
2268 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002269 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2270 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002271 Preamble += prettyBuf.str();
2272 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002273 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002274
2275 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2276 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002277 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002278 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2279 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002280 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002281 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002282 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002283 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002284 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002285 Unop, Exp->getType(),
2286 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002287 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002288 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002289 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002290 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002291}
2292
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002293ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002294 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002295 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002296
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002297 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002298 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002299 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002300 assert(OPT);
2301 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002302 return IT->getDecl();
2303 }
2304 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002305}
2306
2307// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002308QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002309 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002310 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002311 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002312 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002313 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002314
Steve Naroff7fa2f042007-11-15 10:28:18 +00002315 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002316 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002317 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002318 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002319
Steve Naroff7fa2f042007-11-15 10:28:18 +00002320 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002321 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002322 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2323 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002324 FieldTypes[i], 0,
2325 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002326 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002327 }
Mike Stump11289f42009-09-09 15:08:12 +00002328
Douglas Gregor91f84212008-12-11 16:49:14 +00002329 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002330 }
2331 return Context->getTagDeclType(SuperStructDecl);
2332}
2333
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002334QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002335 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002336 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002337 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002338 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002339 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002340
Steve Naroffce8e8862008-03-15 00:55:56 +00002341 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002342 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002343 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002344 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002345 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002346 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002347 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002348 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002349
Steve Naroffce8e8862008-03-15 00:55:56 +00002350 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002351 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002352 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2353 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002354 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002355 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002356 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002357 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002358 }
2359
2360 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002361 }
2362 return Context->getTagDeclType(ConstantStringDecl);
2363}
2364
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002365Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002366 if (!SelGetUidFunctionDecl)
2367 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002368 if (!MsgSendFunctionDecl)
2369 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002370 if (!MsgSendSuperFunctionDecl)
2371 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002372 if (!MsgSendStretFunctionDecl)
2373 SynthMsgSendStretFunctionDecl();
2374 if (!MsgSendSuperStretFunctionDecl)
2375 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002376 if (!MsgSendFpretFunctionDecl)
2377 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002378 if (!GetClassFunctionDecl)
2379 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002380 if (!GetMetaClassFunctionDecl)
2381 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002382
Steve Naroff7fa2f042007-11-15 10:28:18 +00002383 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002384 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2385 // May need to use objc_msgSend_stret() as well.
2386 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002387 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2388 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002389 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002390 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002391 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002392 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002393 }
Mike Stump11289f42009-09-09 15:08:12 +00002394
Steve Naroff574440f2007-10-24 22:48:43 +00002395 // Synthesize a call to objc_msgSend().
2396 llvm::SmallVector<Expr*, 8> MsgExprs;
2397 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002398
Steve Naroff574440f2007-10-24 22:48:43 +00002399 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2400 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002401 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2402 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002403 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002404 MsgSendFlavor = MsgSendSuperFunctionDecl;
2405 if (MsgSendStretFlavor)
2406 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2407 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002408
2409 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002410 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002411
2412 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002413
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002414 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002415 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002416 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002417 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002418 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002419 Context->getObjCIdType(),
2420 SourceLocation()),
2421 Context->getObjCIdType(),
2422 SourceLocation(), SourceLocation())); // set the 'receiver'.
2423
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002424 llvm::SmallVector<Expr*, 8> ClsExprs;
2425 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002426 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002427 SuperDecl->getIdentifier()->getNameStart(),
2428 SuperDecl->getIdentifier()->getLength(),
2429 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002430 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002431 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002432 ClsExprs.size());
2433 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002434 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002435 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002436 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002437 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002438 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002439 // struct objc_super
2440 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002441 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002442
Steve Naroff0b844f02008-03-11 18:14:26 +00002443 if (LangOpts.Microsoft) {
2444 SynthSuperContructorFunctionDecl();
2445 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002446 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002447 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002448 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002449 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002450 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002451 // The code for super is a little tricky to prevent collision with
2452 // the structure definition in the header. The rewriter has it's own
2453 // internal definition (__rw_objc_super) that is uses. This is why
2454 // we need the cast below. For example:
2455 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2456 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002457 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002458 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002459 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002460 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2461 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002462 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002463 SourceLocation(), SourceLocation());
2464 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002465 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002466 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2467 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002468 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002469 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002470 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002471 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002472 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002473 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002474 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002475 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002476 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002477 } else {
2478 llvm::SmallVector<Expr*, 8> ClsExprs;
2479 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002480 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002481 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002482 clsName->getLength(),
2483 false, argType,
2484 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002485 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002486 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002487 ClsExprs.size());
2488 MsgExprs.push_back(Cls);
2489 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002490 } else { // instance message.
2491 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002492
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002493 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002494 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002495 if (MsgSendStretFlavor)
2496 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002497 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002498
Steve Naroff7fa2f042007-11-15 10:28:18 +00002499 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002500
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002501 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002502 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002503 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002504 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002505 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002506 SourceLocation()),
2507 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002508 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002509
Steve Naroff7fa2f042007-11-15 10:28:18 +00002510 llvm::SmallVector<Expr*, 8> ClsExprs;
2511 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002512 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002513 SuperDecl->getIdentifier()->getNameStart(),
2514 SuperDecl->getIdentifier()->getLength(),
2515 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002516 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002517 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002518 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002519 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002520 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002521 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002522 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002523 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002524 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002525 // struct objc_super
2526 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002527 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002528
Steve Naroff17978c42008-03-11 17:37:02 +00002529 if (LangOpts.Microsoft) {
2530 SynthSuperContructorFunctionDecl();
2531 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002532 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002533 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002534 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002535 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002536 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002537 // The code for super is a little tricky to prevent collision with
2538 // the structure definition in the header. The rewriter has it's own
2539 // internal definition (__rw_objc_super) that is uses. This is why
2540 // we need the cast below. For example:
2541 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2542 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002543 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002544 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002545 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002546 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002547 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002548 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002549 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002550 } else {
2551 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002552 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2553 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002554 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002555 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002556 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002557 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002558 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002559 // Remove all type-casts because it may contain objc-style types; e.g.
2560 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002561 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002562 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002563 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002564 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002565 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002566 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002567 MsgExprs.push_back(recExpr);
2568 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002569 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002570 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002571 llvm::SmallVector<Expr*, 8> SelExprs;
2572 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002573 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002574 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002575 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002576 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002577 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2578 &SelExprs[0], SelExprs.size());
2579 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002580
Steve Naroff574440f2007-10-24 22:48:43 +00002581 // Now push any user supplied arguments.
2582 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002583 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002584 // Make all implicit casts explicit...ICE comes in handy:-)
2585 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2586 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002587 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002588 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002589 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002590 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002591 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002592 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002593 }
2594 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002595 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002596 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002597 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002598 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002599 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002600 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002601 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002602 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002603 }
Mike Stump11289f42009-09-09 15:08:12 +00002604 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002605 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002606 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2607 // out the argument in the original expression (since we aren't deleting
2608 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2609 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002610 }
Steve Narofff36987c2007-11-04 22:37:50 +00002611 // Generate the funky cast.
2612 CastExpr *cast;
2613 llvm::SmallVector<QualType, 8> ArgTypes;
2614 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002615
Steve Narofff36987c2007-11-04 22:37:50 +00002616 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002617 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2618 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2619 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002620 ArgTypes.push_back(Context->getObjCIdType());
2621 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002622 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002623 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002624 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2625 E = OMD->param_end(); PI != E; ++PI) {
2626 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002627 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002628 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002629 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002630 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002631 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002632 t = Context->getPointerType(BPT->getPointeeType());
2633 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002634 ArgTypes.push_back(t);
2635 }
Chris Lattnera4997152009-02-20 18:43:26 +00002636 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2637 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002638 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002639 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002640 }
2641 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002642 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002643
Steve Narofff36987c2007-11-04 22:37:50 +00002644 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002645 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002646 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002647
Mike Stump11289f42009-09-09 15:08:12 +00002648 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002649 // If we don't do this cast, we get the following bizarre warning/note:
2650 // xx.m:13: warning: function called through a non-compatible type
2651 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002652 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2653 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002654 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002655 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002656
Steve Narofff36987c2007-11-04 22:37:50 +00002657 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002658 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002659 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002660 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002661 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002662 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002663 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2664 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002665 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002666
2667 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002668 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002669
John McCall9dd450b2009-09-21 23:43:11 +00002670 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002671 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002672 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002673 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002674 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002675 if (MsgSendStretFlavor) {
2676 // We have the method which returns a struct/union. Must also generate
2677 // call to objc_msgSend_stret and hang both varieties on a conditional
2678 // expression which dictate which one to envoke depending on size of
2679 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002680
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002681 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002682 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002683 SourceLocation());
2684 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002685 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2686 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002687 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002688 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002689 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002690 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002691 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002692 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002693 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002694 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2695 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002696
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002697 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002698 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002699
John McCall9dd450b2009-09-21 23:43:11 +00002700 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002701 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002702 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002703 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002704
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002705 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002706 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002707 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002708 Context->getSizeType(),
2709 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002710 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2711 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2712 // For X86 it is more complicated and some kind of target specific routine
2713 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002714 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002715 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002716 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002717 Context->IntTy,
2718 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002719 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2720 BinaryOperator::LE,
2721 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002722 SourceLocation());
2723 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002724 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002725 new (Context) ConditionalOperator(lessThanExpr,
2726 SourceLocation(), CE,
2727 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002728 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002731 return ReplacingStmt;
2732}
2733
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002734Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002735 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002736
Steve Naroff574440f2007-10-24 22:48:43 +00002737 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002738 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002739
2740 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002741 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002742}
2743
Steve Naroffd9803712009-04-29 16:37:50 +00002744// typedef struct objc_object Protocol;
2745QualType RewriteObjC::getProtocolType() {
2746 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002747 TypeSourceInfo *TInfo
2748 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002749 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002750 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002751 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002752 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002753 }
2754 return Context->getTypeDeclType(ProtocolTypeDecl);
2755}
2756
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002757/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002758/// a synthesized/forward data reference (to the protocol's metadata).
2759/// The forward references (and metadata) are generated in
2760/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002761Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002762 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2763 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002764 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002765 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002766 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2767 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2768 Context->getPointerType(DRE->getType()),
2769 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002770 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2771 CastExpr::CK_Unknown,
2772 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002773 SourceLocation(), SourceLocation());
2774 ReplaceStmt(Exp, castExpr);
2775 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002776 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002777 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002778
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002779}
2780
Mike Stump11289f42009-09-09 15:08:12 +00002781bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002782 const char *endBuf) {
2783 while (startBuf < endBuf) {
2784 if (*startBuf == '#') {
2785 // Skip whitespace.
2786 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2787 ;
2788 if (!strncmp(startBuf, "if", strlen("if")) ||
2789 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2790 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2791 !strncmp(startBuf, "define", strlen("define")) ||
2792 !strncmp(startBuf, "undef", strlen("undef")) ||
2793 !strncmp(startBuf, "else", strlen("else")) ||
2794 !strncmp(startBuf, "elif", strlen("elif")) ||
2795 !strncmp(startBuf, "endif", strlen("endif")) ||
2796 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2797 !strncmp(startBuf, "include", strlen("include")) ||
2798 !strncmp(startBuf, "import", strlen("import")) ||
2799 !strncmp(startBuf, "include_next", strlen("include_next")))
2800 return true;
2801 }
2802 startBuf++;
2803 }
2804 return false;
2805}
2806
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002807/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002808/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002809void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002810 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002811 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002812 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002813 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002814 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002815 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002816 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002817 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002818 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002819 SourceLocation LocStart = CDecl->getLocStart();
2820 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002821
Steve Naroffdde78982007-11-14 19:25:57 +00002822 const char *startBuf = SM->getCharacterData(LocStart);
2823 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002824
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002825 // If no ivars and no root or if its root, directly or indirectly,
2826 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002827 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2828 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002829 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002830 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002831 return;
2832 }
Mike Stump11289f42009-09-09 15:08:12 +00002833
2834 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002835 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002836 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002837 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002838 if (LangOpts.Microsoft)
2839 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002840
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002841 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002842 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002843 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002844 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002845 // If the buffer contains preprocessor directives, we do more fine-grained
2846 // rewrites. This is intended to fix code that looks like (which occurs in
2847 // NSURL.h, for example):
2848 //
2849 // #ifdef XYZ
2850 // @interface Foo : NSObject
2851 // #else
2852 // @interface FooBar : NSObject
2853 // #endif
2854 // {
2855 // int i;
2856 // }
2857 // @end
2858 //
2859 // This clause is segregated to avoid breaking the common case.
2860 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002861 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002862 CDecl->getClassLoc();
2863 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002864 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002865
Chris Lattnerf5b77512009-02-20 18:18:36 +00002866 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002867 // advance to the end of the referenced protocols.
2868 while (endHeader < cursor && *endHeader != '>') endHeader++;
2869 endHeader++;
2870 }
2871 // rewrite the original header
2872 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2873 } else {
2874 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002875 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002876 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002877 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002878 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002879 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002880 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002881 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002882 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002883
Steve Naroffdde78982007-11-14 19:25:57 +00002884 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002885 SourceLocation OnePastCurly =
2886 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2887 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002888 }
2889 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002890
Steve Naroffdde78982007-11-14 19:25:57 +00002891 // Now comment out any visibility specifiers.
2892 while (cursor < endBuf) {
2893 if (*cursor == '@') {
2894 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002895 // Skip whitespace.
2896 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2897 /*scan*/;
2898
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002899 // FIXME: presence of @public, etc. inside comment results in
2900 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002901 if (!strncmp(cursor, "public", strlen("public")) ||
2902 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002903 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002904 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002905 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002906 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002907 // FIXME: If there are cases where '<' is used in ivar declaration part
2908 // of user code, then scan the ivar list and use needToScanForQualifiers
2909 // for type checking.
2910 else if (*cursor == '<') {
2911 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002912 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002913 cursor = strchr(cursor, '>');
2914 cursor++;
2915 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002916 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002917 } else if (*cursor == '^') { // rewrite block specifier.
2918 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2919 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002920 }
Steve Naroffdde78982007-11-14 19:25:57 +00002921 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002922 }
Steve Naroffdde78982007-11-14 19:25:57 +00002923 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002924 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002925 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002926 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002927 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002928 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002929 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002930 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002931 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002932 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002933 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002934 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002935 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002936 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002937}
2938
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002939// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002940/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002941template<typename MethodIterator>
2942void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2943 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002944 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002945 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002946 const char *ClassName,
2947 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002948 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002949
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002950 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002951 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002952 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002953 SEL _cmd;
2954 char *method_types;
2955 void *_imp;
2956 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002957 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002958 Result += "\nstruct _objc_method {\n";
2959 Result += "\tSEL _cmd;\n";
2960 Result += "\tchar *method_types;\n";
2961 Result += "\tvoid *_imp;\n";
2962 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002963
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002964 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002965 }
Mike Stump11289f42009-09-09 15:08:12 +00002966
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002967 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002968
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002969 /* struct {
2970 struct _objc_method_list *next_method;
2971 int method_count;
2972 struct _objc_method method_list[];
2973 }
2974 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002975 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002976 Result += "\nstatic struct {\n";
2977 Result += "\tstruct _objc_method_list *next_method;\n";
2978 Result += "\tint method_count;\n";
2979 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002980 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002981 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002982 Result += prefix;
2983 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2984 Result += "_METHODS_";
2985 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002986 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002987 Result += IsInstanceMethod ? "inst" : "cls";
2988 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002989 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002990
Chris Lattner31bc07e2007-12-12 07:46:12 +00002991 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002992 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002993 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002994 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00002995 Result += "\", \"";
2996 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002997 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002998 Result += MethodInternalNames[*MethodBegin];
2999 Result += "}\n";
3000 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3001 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00003002 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003003 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003004 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00003005 Result += "\", \"";
3006 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003007 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00003008 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00003009 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003010 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00003011 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003012}
3013
Steve Naroffd9803712009-04-29 16:37:50 +00003014/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00003015void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00003016RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3017 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003018 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00003019
3020 // Output struct protocol_methods holder of method selector and type.
3021 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3022 /* struct protocol_methods {
3023 SEL _cmd;
3024 char *method_types;
3025 }
3026 */
3027 Result += "\nstruct _protocol_methods {\n";
3028 Result += "\tstruct objc_selector *_cmd;\n";
3029 Result += "\tchar *method_types;\n";
3030 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003031
Steve Naroffd9803712009-04-29 16:37:50 +00003032 objc_protocol_methods = true;
3033 }
3034 // Do not synthesize the protocol more than once.
3035 if (ObjCSynthesizedProtocols.count(PDecl))
3036 return;
Mike Stump11289f42009-09-09 15:08:12 +00003037
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003038 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3039 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3040 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003041 /* struct _objc_protocol_method_list {
3042 int protocol_method_count;
3043 struct protocol_methods protocols[];
3044 }
Steve Naroff251084d2008-03-12 01:06:30 +00003045 */
Steve Naroffd9803712009-04-29 16:37:50 +00003046 Result += "\nstatic struct {\n";
3047 Result += "\tint protocol_method_count;\n";
3048 Result += "\tstruct _protocol_methods protocol_methods[";
3049 Result += utostr(NumMethods);
3050 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3051 Result += PDecl->getNameAsString();
3052 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3053 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003054
Steve Naroffd9803712009-04-29 16:37:50 +00003055 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003056 for (ObjCProtocolDecl::instmeth_iterator
3057 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003058 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003059 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003060 Result += "\t ,{{(struct objc_selector *)\"";
3061 else
3062 Result += "\t ,{(struct objc_selector *)\"";
3063 Result += (*I)->getSelector().getAsString().c_str();
3064 std::string MethodTypeString;
3065 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3066 Result += "\", \"";
3067 Result += MethodTypeString;
3068 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003069 }
Steve Naroffd9803712009-04-29 16:37:50 +00003070 Result += "\t }\n};\n";
3071 }
Mike Stump11289f42009-09-09 15:08:12 +00003072
Steve Naroffd9803712009-04-29 16:37:50 +00003073 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003074 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3075 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003076 if (NumMethods > 0) {
3077 /* struct _objc_protocol_method_list {
3078 int protocol_method_count;
3079 struct protocol_methods protocols[];
3080 }
3081 */
3082 Result += "\nstatic struct {\n";
3083 Result += "\tint protocol_method_count;\n";
3084 Result += "\tstruct _protocol_methods protocol_methods[";
3085 Result += utostr(NumMethods);
3086 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3087 Result += PDecl->getNameAsString();
3088 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3089 "{\n\t";
3090 Result += utostr(NumMethods);
3091 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003092
Steve Naroffd9803712009-04-29 16:37:50 +00003093 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003094 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003095 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003096 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003097 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003098 Result += "\t ,{{(struct objc_selector *)\"";
3099 else
3100 Result += "\t ,{(struct objc_selector *)\"";
3101 Result += (*I)->getSelector().getAsString().c_str();
3102 std::string MethodTypeString;
3103 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3104 Result += "\", \"";
3105 Result += MethodTypeString;
3106 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003107 }
Steve Naroffd9803712009-04-29 16:37:50 +00003108 Result += "\t }\n};\n";
3109 }
3110
3111 // Output:
3112 /* struct _objc_protocol {
3113 // Objective-C 1.0 extensions
3114 struct _objc_protocol_extension *isa;
3115 char *protocol_name;
3116 struct _objc_protocol **protocol_list;
3117 struct _objc_protocol_method_list *instance_methods;
3118 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003119 };
Steve Naroffd9803712009-04-29 16:37:50 +00003120 */
3121 static bool objc_protocol = false;
3122 if (!objc_protocol) {
3123 Result += "\nstruct _objc_protocol {\n";
3124 Result += "\tstruct _objc_protocol_extension *isa;\n";
3125 Result += "\tchar *protocol_name;\n";
3126 Result += "\tstruct _objc_protocol **protocol_list;\n";
3127 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3128 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003129 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003130
Steve Naroffd9803712009-04-29 16:37:50 +00003131 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003132 }
Mike Stump11289f42009-09-09 15:08:12 +00003133
Steve Naroffd9803712009-04-29 16:37:50 +00003134 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3135 Result += PDecl->getNameAsString();
3136 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3137 "{\n\t0, \"";
3138 Result += PDecl->getNameAsString();
3139 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003140 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003141 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3142 Result += PDecl->getNameAsString();
3143 Result += ", ";
3144 }
3145 else
3146 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003147 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003148 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3149 Result += PDecl->getNameAsString();
3150 Result += "\n";
3151 }
3152 else
3153 Result += "0\n";
3154 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003155
Steve Naroffd9803712009-04-29 16:37:50 +00003156 // Mark this protocol as having been generated.
3157 if (!ObjCSynthesizedProtocols.insert(PDecl))
3158 assert(false && "protocol already synthesized");
3159
3160}
3161
3162void RewriteObjC::
3163RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3164 const char *prefix, const char *ClassName,
3165 std::string &Result) {
3166 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003167
Steve Naroffd9803712009-04-29 16:37:50 +00003168 for (unsigned i = 0; i != Protocols.size(); i++)
3169 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3170
Chris Lattner388f6e92008-07-21 21:33:21 +00003171 // Output the top lovel protocol meta-data for the class.
3172 /* struct _objc_protocol_list {
3173 struct _objc_protocol_list *next;
3174 int protocol_count;
3175 struct _objc_protocol *class_protocols[];
3176 }
3177 */
3178 Result += "\nstatic struct {\n";
3179 Result += "\tstruct _objc_protocol_list *next;\n";
3180 Result += "\tint protocol_count;\n";
3181 Result += "\tstruct _objc_protocol *class_protocols[";
3182 Result += utostr(Protocols.size());
3183 Result += "];\n} _OBJC_";
3184 Result += prefix;
3185 Result += "_PROTOCOLS_";
3186 Result += ClassName;
3187 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3188 "{\n\t0, ";
3189 Result += utostr(Protocols.size());
3190 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003191
Chris Lattner388f6e92008-07-21 21:33:21 +00003192 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003193 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003194 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003195
Chris Lattner388f6e92008-07-21 21:33:21 +00003196 for (unsigned i = 1; i != Protocols.size(); i++) {
3197 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003198 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003199 Result += "\n";
3200 }
3201 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003202}
3203
Steve Naroffd9803712009-04-29 16:37:50 +00003204
Mike Stump11289f42009-09-09 15:08:12 +00003205/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003206/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003207void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003208 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003209 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003210 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003211 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003212 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003213 CDecl = CDecl->getNextClassCategory())
3214 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3215 break;
Mike Stump11289f42009-09-09 15:08:12 +00003216
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003217 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003218 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003219 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003220
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003221 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003222 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003223 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003224
3225 // If any of our property implementations have associated getters or
3226 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003227 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3228 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003229 Prop != PropEnd; ++Prop) {
3230 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3231 continue;
3232 if (!(*Prop)->getPropertyIvarDecl())
3233 continue;
3234 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3235 if (!PD)
3236 continue;
3237 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3238 InstanceMethods.push_back(Getter);
3239 if (PD->isReadOnly())
3240 continue;
3241 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3242 InstanceMethods.push_back(Setter);
3243 }
3244 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003245 true, "CATEGORY_", FullCategoryName.c_str(),
3246 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003247
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003248 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003249 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003250 false, "CATEGORY_", FullCategoryName.c_str(),
3251 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003252
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003253 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003254 // Null CDecl is case of a category implementation with no category interface
3255 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003256 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3257 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003258 /* struct _objc_category {
3259 char *category_name;
3260 char *class_name;
3261 struct _objc_method_list *instance_methods;
3262 struct _objc_method_list *class_methods;
3263 struct _objc_protocol_list *protocols;
3264 // Objective-C 1.0 extensions
3265 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003266 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003267 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003268 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003269 */
Mike Stump11289f42009-09-09 15:08:12 +00003270
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003271 static bool objc_category = false;
3272 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003273 Result += "\nstruct _objc_category {\n";
3274 Result += "\tchar *category_name;\n";
3275 Result += "\tchar *class_name;\n";
3276 Result += "\tstruct _objc_method_list *instance_methods;\n";
3277 Result += "\tstruct _objc_method_list *class_methods;\n";
3278 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003279 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003280 Result += "\tstruct _objc_property_list *instance_properties;\n";
3281 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003282 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003283 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003284 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3285 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003286 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003287 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003288 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003289 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003290 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003291
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003292 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003293 Result += "\t, (struct _objc_method_list *)"
3294 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3295 Result += FullCategoryName;
3296 Result += "\n";
3297 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003298 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003299 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003300 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003301 Result += "\t, (struct _objc_method_list *)"
3302 "&_OBJC_CATEGORY_CLASS_METHODS_";
3303 Result += FullCategoryName;
3304 Result += "\n";
3305 }
3306 else
3307 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003308
Chris Lattnerf5b77512009-02-20 18:18:36 +00003309 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003310 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003311 Result += FullCategoryName;
3312 Result += "\n";
3313 }
3314 else
3315 Result += "\t, 0\n";
3316 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003317}
3318
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003319/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3320/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003321void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3322 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003323 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003324 if (ivar->isBitField()) {
3325 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3326 // place all bitfields at offset 0.
3327 Result += "0";
3328 } else {
3329 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003330 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003331 if (LangOpts.Microsoft)
3332 Result += "_IMPL";
3333 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003334 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003335 Result += ")";
3336 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003337}
3338
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003339//===----------------------------------------------------------------------===//
3340// Meta Data Emission
3341//===----------------------------------------------------------------------===//
3342
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003343void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003344 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003345 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003346
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003347 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003348 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003349 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003350 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003351 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003352 }
Mike Stump11289f42009-09-09 15:08:12 +00003353
Chris Lattner30d23e82007-12-12 07:56:42 +00003354 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003355 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003356 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003357 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003358 if (NumIvars > 0) {
3359 static bool objc_ivar = false;
3360 if (!objc_ivar) {
3361 /* struct _objc_ivar {
3362 char *ivar_name;
3363 char *ivar_type;
3364 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003365 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003366 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003367 Result += "\nstruct _objc_ivar {\n";
3368 Result += "\tchar *ivar_name;\n";
3369 Result += "\tchar *ivar_type;\n";
3370 Result += "\tint ivar_offset;\n";
3371 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003372
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003373 objc_ivar = true;
3374 }
3375
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003376 /* struct {
3377 int ivar_count;
3378 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003379 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003380 */
Mike Stump11289f42009-09-09 15:08:12 +00003381 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003382 Result += "\tint ivar_count;\n";
3383 Result += "\tstruct _objc_ivar ivar_list[";
3384 Result += utostr(NumIvars);
3385 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003386 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003387 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003388 "{\n\t";
3389 Result += utostr(NumIvars);
3390 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003391
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003392 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003393 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003394 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003395 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003396 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003397 IV != IVEnd; ++IV)
3398 IVars.push_back(*IV);
3399 IVI = IVars.begin();
3400 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003401 } else {
3402 IVI = CDecl->ivar_begin();
3403 IVE = CDecl->ivar_end();
3404 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003405 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003406 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003407 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003408 std::string TmpString, StrEncoding;
3409 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3410 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003411 Result += StrEncoding;
3412 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003413 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003414 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003415 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003416 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003417 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003418 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003419 std::string TmpString, StrEncoding;
3420 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3421 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003422 Result += StrEncoding;
3423 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003424 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003425 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003426 }
Mike Stump11289f42009-09-09 15:08:12 +00003427
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003428 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003429 }
Mike Stump11289f42009-09-09 15:08:12 +00003430
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003431 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003432 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003433 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003434
3435 // If any of our property implementations have associated getters or
3436 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003437 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3438 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003439 Prop != PropEnd; ++Prop) {
3440 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3441 continue;
3442 if (!(*Prop)->getPropertyIvarDecl())
3443 continue;
3444 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3445 if (!PD)
3446 continue;
3447 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3448 InstanceMethods.push_back(Getter);
3449 if (PD->isReadOnly())
3450 continue;
3451 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3452 InstanceMethods.push_back(Setter);
3453 }
3454 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003455 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003456
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003457 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003458 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003459 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003460
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003461 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003462 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3463 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003464
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003465 // Declaration of class/meta-class metadata
3466 /* struct _objc_class {
3467 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003468 const char *super_class_name;
3469 char *name;
3470 long version;
3471 long info;
3472 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003473 struct _objc_ivar_list *ivars;
3474 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003475 struct objc_cache *cache;
3476 struct objc_protocol_list *protocols;
3477 const char *ivar_layout;
3478 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003479 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003480 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003481 static bool objc_class = false;
3482 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003483 Result += "\nstruct _objc_class {\n";
3484 Result += "\tstruct _objc_class *isa;\n";
3485 Result += "\tconst char *super_class_name;\n";
3486 Result += "\tchar *name;\n";
3487 Result += "\tlong version;\n";
3488 Result += "\tlong info;\n";
3489 Result += "\tlong instance_size;\n";
3490 Result += "\tstruct _objc_ivar_list *ivars;\n";
3491 Result += "\tstruct _objc_method_list *methods;\n";
3492 Result += "\tstruct objc_cache *cache;\n";
3493 Result += "\tstruct _objc_protocol_list *protocols;\n";
3494 Result += "\tconst char *ivar_layout;\n";
3495 Result += "\tstruct _objc_class_ext *ext;\n";
3496 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003497 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003498 }
Mike Stump11289f42009-09-09 15:08:12 +00003499
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003500 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003501 ObjCInterfaceDecl *RootClass = 0;
3502 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003503 while (SuperClass) {
3504 RootClass = SuperClass;
3505 SuperClass = SuperClass->getSuperClass();
3506 }
3507 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003508
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003509 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003510 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003511 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003512 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003513 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003514 Result += "\"";
3515
3516 if (SuperClass) {
3517 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003518 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003519 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003520 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003521 Result += "\"";
3522 }
3523 else {
3524 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003525 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003526 Result += "\"";
3527 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003528 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003529 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003530 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003531 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003532 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003533 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003534 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003535 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003536 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003537 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003538 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003539 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003540 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003541 Result += ",0,0\n";
3542 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003543 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003544 Result += "\t,0,0,0,0\n";
3545 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003546
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003547 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003548 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003549 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003550 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003551 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003552 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003553 if (SuperClass) {
3554 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003555 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003556 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003557 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003558 Result += "\"";
3559 }
3560 else {
3561 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003562 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003563 Result += "\"";
3564 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003565 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003566 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003567 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003568 Result += ",0";
3569 else {
3570 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003571 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003572 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003573 if (LangOpts.Microsoft)
3574 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003575 Result += ")";
3576 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003577 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003578 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003579 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003580 Result += "\n\t";
3581 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003582 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003583 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003584 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003585 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003586 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003587 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003588 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003589 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003590 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003591 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003592 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003593 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003594 Result += ", 0,0\n";
3595 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003596 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003597 Result += ",0,0,0\n";
3598 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003599}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003600
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003601/// RewriteImplementations - This routine rewrites all method implementations
3602/// and emits meta-data.
3603
Steve Narofff8cfd162008-11-13 20:07:04 +00003604void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003605 int ClsDefCount = ClassImplementation.size();
3606 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003607
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003608 // Rewrite implemented methods
3609 for (int i = 0; i < ClsDefCount; i++)
3610 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003611
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003612 for (int i = 0; i < CatDefCount; i++)
3613 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003614}
Mike Stump11289f42009-09-09 15:08:12 +00003615
Steve Narofff8cfd162008-11-13 20:07:04 +00003616void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3617 int ClsDefCount = ClassImplementation.size();
3618 int CatDefCount = CategoryImplementation.size();
3619
Steve Naroff30ac2222008-05-07 21:23:49 +00003620 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003621 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003622 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003623 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003624 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003625
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003626 // For each implemented category, write out all its meta data.
3627 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003628 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003629
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003630 // Write objc_symtab metadata
3631 /*
3632 struct _objc_symtab
3633 {
3634 long sel_ref_cnt;
3635 SEL *refs;
3636 short cls_def_cnt;
3637 short cat_def_cnt;
3638 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003639 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003640 */
Mike Stump11289f42009-09-09 15:08:12 +00003641
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003642 Result += "\nstruct _objc_symtab {\n";
3643 Result += "\tlong sel_ref_cnt;\n";
3644 Result += "\tSEL *refs;\n";
3645 Result += "\tshort cls_def_cnt;\n";
3646 Result += "\tshort cat_def_cnt;\n";
3647 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3648 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003649
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003650 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003651 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003652 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003653 + ", " + utostr(CatDefCount) + "\n";
3654 for (int i = 0; i < ClsDefCount; i++) {
3655 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003656 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003657 Result += "\n";
3658 }
Mike Stump11289f42009-09-09 15:08:12 +00003659
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003660 for (int i = 0; i < CatDefCount; i++) {
3661 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003662 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003663 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003664 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003665 Result += "\n";
3666 }
Mike Stump11289f42009-09-09 15:08:12 +00003667
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003668 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003669
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003670 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003671
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003672 /*
3673 struct _objc_module {
3674 long version;
3675 long size;
3676 const char *name;
3677 struct _objc_symtab *symtab;
3678 }
3679 */
Mike Stump11289f42009-09-09 15:08:12 +00003680
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003681 Result += "\nstruct _objc_module {\n";
3682 Result += "\tlong version;\n";
3683 Result += "\tlong size;\n";
3684 Result += "\tconst char *name;\n";
3685 Result += "\tstruct _objc_symtab *symtab;\n";
3686 Result += "};\n\n";
3687 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003688 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003689 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003690 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003691 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003692
3693 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003694 if (ProtocolExprDecls.size()) {
3695 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3696 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003697 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003698 E = ProtocolExprDecls.end(); I != E; ++I) {
3699 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3700 Result += (*I)->getNameAsString();
3701 Result += " = &_OBJC_PROTOCOL_";
3702 Result += (*I)->getNameAsString();
3703 Result += ";\n";
3704 }
3705 Result += "#pragma data_seg(pop)\n\n";
3706 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003707 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003708 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003709 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3710 Result += "&_OBJC_MODULES;\n";
3711 Result += "#pragma data_seg(pop)\n\n";
3712 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003713}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003714
Steve Naroff677ab3a2008-10-27 17:20:55 +00003715std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3716 const char *funcName,
3717 std::string Tag) {
3718 const FunctionType *AFT = CE->getFunctionType();
3719 QualType RT = AFT->getResultType();
3720 std::string StructRef = "struct " + Tag;
3721 std::string S = "static " + RT.getAsString() + " __" +
3722 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003723
Steve Naroff677ab3a2008-10-27 17:20:55 +00003724 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003725
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003726 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003727 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003728 // block (to reference imported block decl refs).
3729 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003730 } else if (BD->param_empty()) {
3731 S += "(" + StructRef + " *__cself)";
3732 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003733 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003734 assert(FT && "SynthesizeBlockFunc: No function proto");
3735 S += '(';
3736 // first add the implicit argument.
3737 S += StructRef + " *__cself, ";
3738 std::string ParamStr;
3739 for (BlockDecl::param_iterator AI = BD->param_begin(),
3740 E = BD->param_end(); AI != E; ++AI) {
3741 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003742 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003743 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003744 S += ParamStr;
3745 }
3746 if (FT->isVariadic()) {
3747 if (!BD->param_empty()) S += ", ";
3748 S += "...";
3749 }
3750 S += ')';
3751 }
3752 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003753
Steve Naroff677ab3a2008-10-27 17:20:55 +00003754 // Create local declarations to avoid rewriting all closure decl ref exprs.
3755 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003756 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003757 E = BlockByRefDecls.end(); I != E; ++I) {
3758 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003759 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003760 std::string TypeString = "struct __Block_byref_" + Name + " *";
3761 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003762 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003763 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003764 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003765 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003766 E = BlockByCopyDecls.end(); I != E; ++I) {
3767 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003768 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003769 // Handle nested closure invocation. For example:
3770 //
3771 // void (^myImportedClosure)(void);
3772 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003773 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003774 // void (^anotherClosure)(void);
3775 // anotherClosure = ^(void) {
3776 // myImportedClosure(); // import and invoke the closure
3777 // };
3778 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003779 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003780 S += "struct __block_impl *";
3781 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003782 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003783 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003784 }
3785 std::string RewrittenStr = RewrittenBlockExprs[CE];
3786 const char *cstr = RewrittenStr.c_str();
3787 while (*cstr++ != '{') ;
3788 S += cstr;
3789 S += "\n";
3790 return S;
3791}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003792
Steve Naroff677ab3a2008-10-27 17:20:55 +00003793std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3794 const char *funcName,
3795 std::string Tag) {
3796 std::string StructRef = "struct " + Tag;
3797 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003798
Steve Naroff677ab3a2008-10-27 17:20:55 +00003799 S += funcName;
3800 S += "_block_copy_" + utostr(i);
3801 S += "(" + StructRef;
3802 S += "*dst, " + StructRef;
3803 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003804 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003805 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003806 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003807 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003808 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003809 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003810 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003811 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003812 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003813 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003815 S += "}\n";
3816
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817 S += "\nstatic void __";
3818 S += funcName;
3819 S += "_block_dispose_" + utostr(i);
3820 S += "(" + StructRef;
3821 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003822 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003823 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003824 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003825 S += (*I)->getNameAsString();
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003826 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003827 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003828 else
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003829 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003830 }
Mike Stump11289f42009-09-09 15:08:12 +00003831 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003832 return S;
3833}
3834
Steve Naroff30484702009-12-06 21:14:13 +00003835std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3836 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003837 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003838 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003839
Steve Naroff677ab3a2008-10-27 17:20:55 +00003840 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003841 S += " struct " + Desc;
3842 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003843
Steve Naroff30484702009-12-06 21:14:13 +00003844 Constructor += "(void *fp, "; // Invoke function pointer.
3845 Constructor += "struct " + Desc; // Descriptor pointer.
3846 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003847
Steve Naroff677ab3a2008-10-27 17:20:55 +00003848 if (BlockDeclRefs.size()) {
3849 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003850 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003851 E = BlockByCopyDecls.end(); I != E; ++I) {
3852 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003853 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003854 std::string ArgName = "_" + FieldName;
3855 // Handle nested closure invocation. For example:
3856 //
3857 // void (^myImportedBlock)(void);
3858 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003859 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003860 // void (^anotherBlock)(void);
3861 // anotherBlock = ^(void) {
3862 // myImportedBlock(); // import and invoke the closure
3863 // };
3864 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003865 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003866 S += "struct __block_impl *";
3867 Constructor += ", void *" + ArgName;
3868 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003869 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3870 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003871 Constructor += ", " + ArgName;
3872 }
3873 S += FieldName + ";\n";
3874 }
3875 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003876 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003877 E = BlockByRefDecls.end(); I != E; ++I) {
3878 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003879 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003880 std::string ArgName = "_" + FieldName;
3881 // Handle nested closure invocation. For example:
3882 //
3883 // void (^myImportedBlock)(void);
3884 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003885 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003886 // void (^anotherBlock)(void);
3887 // anotherBlock = ^(void) {
3888 // myImportedBlock(); // import and invoke the closure
3889 // };
3890 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003891 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003892 S += "struct __block_impl *";
3893 Constructor += ", void *" + ArgName;
3894 } else {
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003895 std::string TypeString = "struct __Block_byref_" + FieldName;
3896 TypeString += " *";
3897 FieldName = TypeString + FieldName;
3898 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003899 Constructor += ", " + ArgName;
3900 }
3901 S += FieldName + "; // by ref\n";
3902 }
3903 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003904 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003905 if (GlobalVarDecl)
3906 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3907 else
3908 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003909 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003910
Steve Naroff30484702009-12-06 21:14:13 +00003911 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003912
Steve Naroff677ab3a2008-10-27 17:20:55 +00003913 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003914 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003915 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003916 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003917 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003918 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003919 Constructor += Name + " = (struct __block_impl *)_";
3920 else
3921 Constructor += Name + " = _";
3922 Constructor += Name + ";\n";
3923 }
3924 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003925 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003926 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003927 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003928 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003929 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003930 Constructor += Name + " = (struct __block_impl *)_";
3931 else
3932 Constructor += Name + " = _";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003933 Constructor += Name + "->__forwarding;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003934 }
3935 } else {
3936 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003937 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003938 if (GlobalVarDecl)
3939 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3940 else
3941 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003942 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3943 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003944 }
3945 Constructor += " ";
3946 Constructor += "}\n";
3947 S += Constructor;
3948 S += "};\n";
3949 return S;
3950}
3951
Steve Naroff30484702009-12-06 21:14:13 +00003952std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3953 std::string ImplTag, int i,
3954 const char *FunName,
3955 unsigned hasCopy) {
3956 std::string S = "\nstatic struct " + DescTag;
3957
3958 S += " {\n unsigned long reserved;\n";
3959 S += " unsigned long Block_size;\n";
3960 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003961 S += " void (*copy)(struct ";
3962 S += ImplTag; S += "*, struct ";
3963 S += ImplTag; S += "*);\n";
3964
3965 S += " void (*dispose)(struct ";
3966 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003967 }
3968 S += "} ";
3969
3970 S += DescTag + "_DATA = { 0, sizeof(struct ";
3971 S += ImplTag + ")";
3972 if (hasCopy) {
3973 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3974 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3975 }
3976 S += "};\n";
3977 return S;
3978}
3979
Steve Naroff677ab3a2008-10-27 17:20:55 +00003980void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3981 const char *FunName) {
3982 // Insert closures that were part of the function.
3983 for (unsigned i = 0; i < Blocks.size(); i++) {
3984
3985 CollectBlockDeclRefInfo(Blocks[i]);
3986
Steve Naroff30484702009-12-06 21:14:13 +00003987 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3988 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003989
Steve Naroff30484702009-12-06 21:14:13 +00003990 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003991
3992 InsertText(FunLocStart, CI.c_str(), CI.size());
3993
Steve Naroff30484702009-12-06 21:14:13 +00003994 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003995
Steve Naroff677ab3a2008-10-27 17:20:55 +00003996 InsertText(FunLocStart, CF.c_str(), CF.size());
3997
3998 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003999 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000 InsertText(FunLocStart, HF.c_str(), HF.size());
4001 }
Steve Naroff30484702009-12-06 21:14:13 +00004002 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4003 ImportedBlockDecls.size() > 0);
4004 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00004005
Steve Naroff677ab3a2008-10-27 17:20:55 +00004006 BlockDeclRefs.clear();
4007 BlockByRefDecls.clear();
4008 BlockByCopyDecls.clear();
4009 BlockCallExprs.clear();
4010 ImportedBlockDecls.clear();
4011 }
4012 Blocks.clear();
4013 RewrittenBlockExprs.clear();
4014}
4015
4016void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4017 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00004018 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00004019
Steve Naroff677ab3a2008-10-27 17:20:55 +00004020 SynthesizeBlockLiterals(FunLocStart, FuncName);
4021}
4022
4023void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00004024 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4025 //SourceLocation FunLocStart = MD->getLocStart();
4026 // FIXME: This hack works around a bug in Rewrite.InsertText().
4027 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00004028 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004029 // Convert colons to underscores.
4030 std::string::size_type loc = 0;
4031 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4032 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004033
Steve Naroff677ab3a2008-10-27 17:20:55 +00004034 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4035}
4036
4037void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4038 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4039 CI != E; ++CI)
4040 if (*CI) {
4041 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4042 GetBlockDeclRefExprs(CBE->getBody());
4043 else
4044 GetBlockDeclRefExprs(*CI);
4045 }
4046 // Handle specific things.
4047 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4048 // FIXME: Handle enums.
4049 if (!isa<FunctionDecl>(CDRE->getDecl()))
4050 BlockDeclRefs.push_back(CDRE);
4051 return;
4052}
4053
4054void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4055 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4056 CI != E; ++CI)
4057 if (*CI) {
4058 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4059 GetBlockCallExprs(CBE->getBody());
4060 else
4061 GetBlockCallExprs(*CI);
4062 }
Mike Stump11289f42009-09-09 15:08:12 +00004063
Steve Naroff677ab3a2008-10-27 17:20:55 +00004064 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4065 if (CE->getCallee()->getType()->isBlockPointerType()) {
4066 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4067 }
4068 }
4069 return;
4070}
4071
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004072Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004073 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004074 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004075
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004076 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004077 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004078 } else if (const BlockDeclRefExpr *CDRE =
4079 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004080 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004081 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004082 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004083 }
4084 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4085 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4086 }
4087 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4088 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4089 else if (const ConditionalOperator *CEXPR =
4090 dyn_cast<ConditionalOperator>(BlockExp)) {
4091 Expr *LHSExp = CEXPR->getLHS();
4092 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4093 Expr *RHSExp = CEXPR->getRHS();
4094 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4095 Expr *CONDExp = CEXPR->getCond();
4096 ConditionalOperator *CondExpr =
4097 new (Context) ConditionalOperator(CONDExp,
4098 SourceLocation(), cast<Expr>(LHSStmt),
4099 SourceLocation(), cast<Expr>(RHSStmt),
4100 Exp->getType());
4101 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004102 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4103 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004104 } else {
4105 assert(1 && "RewriteBlockClass: Bad type");
4106 }
4107 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004108 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004109 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004110 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004111 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004112
Steve Naroff350b6652008-10-30 10:07:53 +00004113 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4114 SourceLocation(),
4115 &Context->Idents.get("__block_impl"));
4116 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004117
Steve Naroff350b6652008-10-30 10:07:53 +00004118 // Generate a funky cast.
4119 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004120
Steve Naroff350b6652008-10-30 10:07:53 +00004121 // Push the block argument type.
4122 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004123 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004124 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004125 E = FTP->arg_type_end(); I && (I != E); ++I) {
4126 QualType t = *I;
4127 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004128 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004129 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004130 t = Context->getPointerType(BPT->getPointeeType());
4131 }
4132 ArgTypes.push_back(t);
4133 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004134 }
Steve Naroff350b6652008-10-30 10:07:53 +00004135 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004136 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004137 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004138
Steve Naroff350b6652008-10-30 10:07:53 +00004139 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004140
4141 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004142 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004143 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004144 PtrBlock, SourceLocation(),
4145 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004146 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004147 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4148 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004149 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004150
Douglas Gregor91f84212008-12-11 16:49:14 +00004151 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004152 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004153 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004154 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4155 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004156
Anders Carlssona2615922009-07-31 00:48:10 +00004157 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4158 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004159 PtrToFuncCastType,
4160 SourceLocation(),
4161 SourceLocation());
4162 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004163
Steve Naroff350b6652008-10-30 10:07:53 +00004164 llvm::SmallVector<Expr*, 8> BlkExprs;
4165 // Add the implicit argument.
4166 BlkExprs.push_back(BlkCast);
4167 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004168 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004169 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004170 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004171 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004172 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4173 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004174 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004175 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004176}
4177
4178void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004179 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004180 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004181}
4182
Steve Naroffd9803712009-04-29 16:37:50 +00004183// We need to return the rewritten expression to handle cases where the
4184// BlockDeclRefExpr is embedded in another expression being rewritten.
4185// For example:
4186//
4187// int main() {
4188// __block Foo *f;
4189// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004190//
Steve Naroffd9803712009-04-29 16:37:50 +00004191// void (^myblock)() = ^() {
4192// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4193// i = 77;
4194// };
4195//}
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004196Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00004197 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004198 // for each DeclRefExp where BYREFVAR is name of the variable.
4199 ValueDecl *VD;
4200 bool isArrow = true;
4201 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4202 VD = BDRE->getDecl();
4203 else {
4204 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4205 isArrow = false;
4206 }
4207
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004208 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4209 &Context->Idents.get("__forwarding"),
4210 Context->VoidPtrTy, 0,
4211 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004212 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4213 FD, SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004214 FD->getType());
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004215
4216 const char *Name = VD->getNameAsCString();
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004217 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4218 &Context->Idents.get(Name),
4219 Context->VoidPtrTy, 0,
4220 /*BitWidth=*/0, /*Mutable=*/true);
4221 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004222 DeclRefExp->getType());
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004223
4224
4225
Steve Narofff26a1d42009-02-02 17:19:26 +00004226 // Need parens to enforce precedence.
Fariborz Jahanian7df39802009-12-23 19:22:33 +00004227 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4228 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004229 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004230 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004231}
4232
Steve Naroffc989a7b2008-11-03 23:29:32 +00004233void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4234 SourceLocation LocStart = CE->getLParenLoc();
4235 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004236
4237 // Need to avoid trying to rewrite synthesized casts.
4238 if (LocStart.isInvalid())
4239 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004240 // Need to avoid trying to rewrite casts contained in macros.
4241 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4242 return;
Mike Stump11289f42009-09-09 15:08:12 +00004243
Steve Naroff677ab3a2008-10-27 17:20:55 +00004244 const char *startBuf = SM->getCharacterData(LocStart);
4245 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004246
Steve Naroff677ab3a2008-10-27 17:20:55 +00004247 // advance the location to startArgList.
4248 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004249
Steve Naroff677ab3a2008-10-27 17:20:55 +00004250 while (*argPtr++ && (argPtr < endBuf)) {
4251 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004252 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004253 // Replace the '^' with '*'.
4254 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4255 ReplaceText(LocStart, 1, "*", 1);
4256 break;
4257 }
4258 }
4259 return;
4260}
4261
4262void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4263 SourceLocation DeclLoc = FD->getLocation();
4264 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004265
Steve Naroff677ab3a2008-10-27 17:20:55 +00004266 // We have 1 or more arguments that have closure pointers.
4267 const char *startBuf = SM->getCharacterData(DeclLoc);
4268 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004269
Steve Naroff677ab3a2008-10-27 17:20:55 +00004270 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004271
Steve Naroff677ab3a2008-10-27 17:20:55 +00004272 parenCount++;
4273 // advance the location to startArgList.
4274 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4275 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004276
Steve Naroff677ab3a2008-10-27 17:20:55 +00004277 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004278
Steve Naroff677ab3a2008-10-27 17:20:55 +00004279 while (*argPtr++ && parenCount) {
4280 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004281 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004282 // Replace the '^' with '*'.
4283 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4284 ReplaceText(DeclLoc, 1, "*", 1);
4285 break;
Mike Stump11289f42009-09-09 15:08:12 +00004286 case '(':
4287 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004288 break;
Mike Stump11289f42009-09-09 15:08:12 +00004289 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004290 parenCount--;
4291 break;
4292 }
4293 }
4294 return;
4295}
4296
4297bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004298 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004299 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004300 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004301 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004302 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004303 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004304 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004305 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004306 }
4307 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004308 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004309 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004310 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004311 return true;
4312 }
4313 return false;
4314}
4315
Ted Kremenek5a201952009-02-07 01:47:29 +00004316void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4317 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004318 const char *argPtr = strchr(Name, '(');
4319 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004320
Steve Naroff677ab3a2008-10-27 17:20:55 +00004321 LParen = argPtr; // output the start.
4322 argPtr++; // skip past the left paren.
4323 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004324
Steve Naroff677ab3a2008-10-27 17:20:55 +00004325 while (*argPtr && parenCount) {
4326 switch (*argPtr) {
4327 case '(': parenCount++; break;
4328 case ')': parenCount--; break;
4329 default: break;
4330 }
4331 if (parenCount) argPtr++;
4332 }
4333 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4334 RParen = argPtr; // output the end
4335}
4336
4337void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4338 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4339 RewriteBlockPointerFunctionArgs(FD);
4340 return;
Mike Stump11289f42009-09-09 15:08:12 +00004341 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004342 // Handle Variables and Typedefs.
4343 SourceLocation DeclLoc = ND->getLocation();
4344 QualType DeclT;
4345 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4346 DeclT = VD->getType();
4347 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4348 DeclT = TDD->getUnderlyingType();
4349 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4350 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004351 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004352 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004353
Steve Naroff677ab3a2008-10-27 17:20:55 +00004354 const char *startBuf = SM->getCharacterData(DeclLoc);
4355 const char *endBuf = startBuf;
4356 // scan backward (from the decl location) for the end of the previous decl.
4357 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4358 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004359
Steve Naroff677ab3a2008-10-27 17:20:55 +00004360 // *startBuf != '^' if we are dealing with a pointer to function that
4361 // may take block argument types (which will be handled below).
4362 if (*startBuf == '^') {
4363 // Replace the '^' with '*', computing a negative offset.
4364 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4365 ReplaceText(DeclLoc, 1, "*", 1);
4366 }
4367 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4368 // Replace the '^' with '*' for arguments.
4369 DeclLoc = ND->getLocation();
4370 startBuf = SM->getCharacterData(DeclLoc);
4371 const char *argListBegin, *argListEnd;
4372 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4373 while (argListBegin < argListEnd) {
4374 if (*argListBegin == '^') {
4375 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4376 ReplaceText(CaretLoc, 1, "*", 1);
4377 }
4378 argListBegin++;
4379 }
4380 }
4381 return;
4382}
4383
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004384
4385/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4386/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4387/// struct Block_byref_id_object *src) {
4388/// _Block_object_assign (&_dest->object, _src->object,
4389/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4390/// [|BLOCK_FIELD_IS_WEAK]) // object
4391/// _Block_object_assign(&_dest->object, _src->object,
4392/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4393/// [|BLOCK_FIELD_IS_WEAK]) // block
4394/// }
4395/// And:
4396/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4397/// _Block_object_dispose(_src->object,
4398/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4399/// [|BLOCK_FIELD_IS_WEAK]) // object
4400/// _Block_object_dispose(_src->object,
4401/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4402/// [|BLOCK_FIELD_IS_WEAK]) // block
4403/// }
4404
4405std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD) {
4406 static bool synthesized = false;
4407 std::string S;
4408 if (synthesized)
4409 return S;
4410 synthesized = true;
4411 S = "static void __Block_byref_id_object_copy(void *dst, void *src) {\n";
4412 int flag = BLOCK_BYREF_CALLER;
4413 QualType Ty = VD->getType();
4414 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4415 if (Ty->isBlockPointerType())
4416 flag |= BLOCK_FIELD_IS_BLOCK;
4417 else
4418 flag |= BLOCK_FIELD_IS_OBJECT;
4419 // offset into the object pointer is computed as:
4420 // void * + void* + int + int + void* + void *
4421 unsigned IntSize =
4422 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4423 unsigned VoidPtrSize =
4424 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4425
4426 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4427 S += " _Block_object_assign((char*)dst + ";
4428 S += utostr(offset);
4429 S += ", *(void * *) ((char*)src + ";
4430 S += utostr(offset);
4431 S += "), ";
4432 S += utostr(flag);
4433 S += ");\n}\n";
4434
4435 S += "static void __Block_byref_id_object_dispose(void *src) {\n";
4436 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4437 S += utostr(offset);
4438 S += "), ";
4439 S += utostr(flag);
4440 S += ");\n}\n";
4441 return S;
4442}
4443
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004444/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4445/// the declaration into:
4446/// struct __Block_byref_ND {
4447/// void *__isa; // NULL for everything except __weak pointers
4448/// struct __Block_byref_ND *__forwarding;
4449/// int32_t __flags;
4450/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004451/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4452/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004453/// typex ND;
4454/// };
4455///
4456/// It then replaces declaration of ND variable with:
4457/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4458/// __size=sizeof(struct __Block_byref_ND),
4459/// ND=initializer-if-any};
4460///
4461///
4462void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4463 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4464 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004465 SourceLocation X = ND->getLocEnd();
4466 X = SM->getInstantiationLoc(X);
4467 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004468 std::string Name(ND->getNameAsString());
4469 std::string ByrefType = "struct __Block_byref_";
4470 ByrefType += Name;
4471 ByrefType += " {\n";
4472 ByrefType += " void *__isa;\n";
4473 ByrefType += " struct __Block_byref_" + Name + " *__forwarding;\n";
4474 ByrefType += " int __flags;\n";
4475 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004476 // Add void *__Block_byref_id_object_copy;
4477 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004478 QualType Ty = ND->getType();
4479 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4480 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004481 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4482 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004483 }
4484
4485 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004486 ByrefType += " " + Name + ";\n";
4487 ByrefType += "};\n";
4488 // Insert this type in global scope. It is needed by helper function.
4489 assert(CurFunctionDef && "RewriteByRefVar - CurFunctionDef is null");
4490 SourceLocation FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4491 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004492 if (HasCopyAndDispose) {
4493 std::string HF = SynthesizeByrefCopyDestroyHelper(ND);
4494 if (!HF.empty())
4495 InsertText(FunLocStart, HF.c_str(), HF.size());
4496 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004497
4498 // struct __Block_byref_ND ND =
4499 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4500 // initializer-if-any};
4501 bool hasInit = (ND->getInit() != 0);
4502 Name = ND->getNameAsString();
4503 ByrefType = "struct __Block_byref_" + Name;
4504 if (!hasInit) {
4505 ByrefType += " " + Name + " = ";
4506 ByrefType += "{0, &" + Name + ", ";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004507 unsigned flag = 0;
4508 if (HasCopyAndDispose)
4509 flag |= BLOCK_HAS_COPY_DISPOSE;
4510 ByrefType += utostr(flag);
4511 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004512 ByrefType += "sizeof(struct __Block_byref_" + Name + ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004513 if (HasCopyAndDispose) {
4514 ByrefType += ", __Block_byref_id_object_copy";
4515 ByrefType += ", __Block_byref_id_object_dispose";
4516 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004517 ByrefType += "};\n";
4518 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4519 ByrefType.c_str(), ByrefType.size());
4520 }
4521 else {
4522 SourceLocation startLoc = ND->getInit()->getLocStart();
4523 ByrefType += " " + Name;
4524 ReplaceText(DeclLoc, endBuf-startBuf,
4525 ByrefType.c_str(), ByrefType.size());
4526 ByrefType = " = {0, &" + Name + ", ";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004527 unsigned flag = 0;
4528 if (HasCopyAndDispose)
4529 flag |= BLOCK_HAS_COPY_DISPOSE;
4530 ByrefType += utostr(flag);
4531 ByrefType += ", ";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004532 ByrefType += "sizeof(struct __Block_byref_" + Name + "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004533 if (HasCopyAndDispose) {
4534 ByrefType += "__Block_byref_id_object_copy";
4535 ByrefType += ", __Block_byref_id_object_dispose, ";
4536 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004537 InsertText(startLoc, ByrefType.c_str(), ByrefType.size());
Steve Naroff13468372009-12-23 17:24:33 +00004538
4539 // Complete the newly synthesized compound expression by inserting a right
4540 // curly brace before the end of the declaration.
4541 // FIXME: This approach avoids rewriting the initializer expression. It
4542 // also assumes there is only one declarator. For example, the following
4543 // isn't currently supported by this routine (in general):
4544 //
4545 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4546 //
4547 const char *startBuf = SM->getCharacterData(startLoc);
4548 const char *semiBuf = strchr(startBuf, ';');
4549 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4550 SourceLocation semiLoc =
4551 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4552
4553 InsertText(semiLoc, "}", 1);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004554 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004555 return;
4556}
4557
Mike Stump11289f42009-09-09 15:08:12 +00004558void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004559 // Add initializers for any closure decl refs.
4560 GetBlockDeclRefExprs(Exp->getBody());
4561 if (BlockDeclRefs.size()) {
4562 // Unique all "by copy" declarations.
4563 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4564 if (!BlockDeclRefs[i]->isByRef())
4565 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4566 // Unique all "by ref" declarations.
4567 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4568 if (BlockDeclRefs[i]->isByRef()) {
4569 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4570 }
4571 // Find any imported blocks...they will need special attention.
4572 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004573 if (BlockDeclRefs[i]->isByRef() ||
4574 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4575 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004576 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004577 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4578 }
4579 }
4580}
4581
Steve Narofff4b992a2008-10-28 20:29:00 +00004582FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4583 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004584 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004585 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004586 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004587 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004588}
4589
Steve Naroffd8907b72008-10-29 18:15:37 +00004590Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004591 Blocks.push_back(Exp);
4592
4593 CollectBlockDeclRefInfo(Exp);
4594 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004595
Steve Narofff4b992a2008-10-28 20:29:00 +00004596 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004597 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004598 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004599 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004600 // Convert colons to underscores.
4601 std::string::size_type loc = 0;
4602 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4603 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004604 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004605 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004606
Steve Narofff4b992a2008-10-28 20:29:00 +00004607 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004608
Steve Narofff4b992a2008-10-28 20:29:00 +00004609 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4610 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004611
Steve Narofff4b992a2008-10-28 20:29:00 +00004612 // Get a pointer to the function type so we can cast appropriately.
4613 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4614
4615 FunctionDecl *FD;
4616 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004617
Steve Narofff4b992a2008-10-28 20:29:00 +00004618 // Simulate a contructor call...
4619 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004620 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004621
Steve Narofff4b992a2008-10-28 20:29:00 +00004622 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004623
Steve Naroffe2514232008-10-29 21:23:59 +00004624 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004625 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004626 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4627 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004628 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4629 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004630 Context->VoidPtrTy, SourceLocation(),
4631 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004632 InitExprs.push_back(castExpr);
4633
Steve Naroff30484702009-12-06 21:14:13 +00004634 // Initialize the block descriptor.
4635 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004636
Steve Naroff30484702009-12-06 21:14:13 +00004637 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4638 &Context->Idents.get(DescData.c_str()),
4639 Context->VoidPtrTy, 0,
4640 VarDecl::Static);
4641 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4642 new (Context) DeclRefExpr(NewVD,
4643 Context->VoidPtrTy, SourceLocation()),
4644 UnaryOperator::AddrOf,
4645 Context->getPointerType(Context->VoidPtrTy),
4646 SourceLocation());
4647 InitExprs.push_back(DescRefExpr);
4648
Steve Narofff4b992a2008-10-28 20:29:00 +00004649 // Add initializers for any closure decl refs.
4650 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004651 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004652 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004653 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004654 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004655 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004656 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004657 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004658 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004659 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004660 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004661 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004662 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4663 CastExpr::CK_Unknown, Arg,
4664 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004665 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004666 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004667 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004668 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004669 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004670 }
Mike Stump11289f42009-09-09 15:08:12 +00004671 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004672 }
4673 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004674 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004675 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004676 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004677 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4678 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004679 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004680 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004681 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004682 }
4683 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004684 if (ImportedBlockDecls.size()) {
4685 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4686 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004687 unsigned IntSize =
4688 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004689 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4690 Context->IntTy, SourceLocation());
4691 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004692 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004693 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4694 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004695 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004696 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004697 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004698 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004699 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004700 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004701 BlockDeclRefs.clear();
4702 BlockByRefDecls.clear();
4703 BlockByCopyDecls.clear();
4704 ImportedBlockDecls.clear();
4705 return NewRep;
4706}
4707
4708//===----------------------------------------------------------------------===//
4709// Function Body / Expression rewriting
4710//===----------------------------------------------------------------------===//
4711
Steve Naroff4588d0f2008-12-04 16:24:46 +00004712// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4713// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4714// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4715// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4716// Since the rewriter isn't capable of rewriting rewritten code, it's important
4717// we get this right.
4718void RewriteObjC::CollectPropertySetters(Stmt *S) {
4719 // Perform a bottom up traversal of all children.
4720 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4721 CI != E; ++CI)
4722 if (*CI)
4723 CollectPropertySetters(*CI);
4724
4725 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4726 if (BinOp->isAssignmentOp()) {
4727 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4728 PropSetters[PRE] = BinOp;
4729 }
4730 }
4731}
4732
Steve Narofff4b992a2008-10-28 20:29:00 +00004733Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004734 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004735 isa<DoStmt>(S) || isa<ForStmt>(S))
4736 Stmts.push_back(S);
4737 else if (isa<ObjCForCollectionStmt>(S)) {
4738 Stmts.push_back(S);
Anders Carlsson3caa2b42009-12-22 06:13:42 +00004739 ++BcLabelCount;
4740 ObjCBcLabelNo.push_back(BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004741 }
Mike Stump11289f42009-09-09 15:08:12 +00004742
Steve Narofff4b992a2008-10-28 20:29:00 +00004743 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004744
Steve Narofff4b992a2008-10-28 20:29:00 +00004745 // Perform a bottom up rewrite of all children.
4746 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4747 CI != E; ++CI)
4748 if (*CI) {
4749 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004750 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004751 *CI = newStmt;
4752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753
Steve Narofff4b992a2008-10-28 20:29:00 +00004754 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4755 // Rewrite the block body in place.
4756 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004757
Steve Narofff4b992a2008-10-28 20:29:00 +00004758 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004759 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4760 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004761
Steve Narofff4b992a2008-10-28 20:29:00 +00004762 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4763 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004764 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004765 return blockTranscribed;
4766 }
4767 // Handle specific things.
4768 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4769 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004770
Steve Narofff4b992a2008-10-28 20:29:00 +00004771 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4772 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4773
Steve Naroff4588d0f2008-12-04 16:24:46 +00004774 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4775 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4776 if (BinOp) {
4777 // Because the rewriter doesn't allow us to rewrite rewritten code,
4778 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004779 DisableReplaceStmt = true;
4780 // Save the source range. Even if we disable the replacement, the
4781 // rewritten node will have been inserted into the tree. If the synthesized
4782 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004783 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004784 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4785 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004786 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004787 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004788 //
4789 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4790 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4791 // to see the original expression). Consider this example:
4792 //
4793 // Foo *obj1, *obj2;
4794 //
4795 // obj1.i = [obj2 rrrr];
4796 //
4797 // 'BinOp' for the previous expression looks like:
4798 //
4799 // (BinaryOperator 0x231ccf0 'int' '='
4800 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4801 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4802 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4803 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4804 //
4805 // 'newStmt' represents the rewritten message expression. For example:
4806 //
4807 // (CallExpr 0x231d300 'id':'struct objc_object *'
4808 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4809 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4810 // (CStyleCastExpr 0x231d220 'void *'
4811 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4812 //
4813 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4814 // can be used as the setter argument. ReplaceStmt() will still 'see'
4815 // the original RHS (since we haven't altered BinOp).
4816 //
Mike Stump11289f42009-09-09 15:08:12 +00004817 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004818 // node. As a result, we now leak the original AST nodes.
4819 //
Steve Naroff08628db2008-12-09 12:56:34 +00004820 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004821 } else {
4822 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004823 }
4824 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004825 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4826 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004827
Steve Narofff4b992a2008-10-28 20:29:00 +00004828 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4829 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004830
Steve Narofff4b992a2008-10-28 20:29:00 +00004831 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004832#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004833 // Before we rewrite it, put the original message expression in a comment.
4834 SourceLocation startLoc = MessExpr->getLocStart();
4835 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004836
Steve Narofff4b992a2008-10-28 20:29:00 +00004837 const char *startBuf = SM->getCharacterData(startLoc);
4838 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004839
Steve Narofff4b992a2008-10-28 20:29:00 +00004840 std::string messString;
4841 messString += "// ";
4842 messString.append(startBuf, endBuf-startBuf+1);
4843 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004844
4845 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004846 // InsertText(clang::SourceLocation, char const*, unsigned int).
4847 // InsertText(startLoc, messString.c_str(), messString.size());
4848 // Tried this, but it didn't work either...
4849 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004850#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004851 return RewriteMessageExpr(MessExpr);
4852 }
Mike Stump11289f42009-09-09 15:08:12 +00004853
Steve Narofff4b992a2008-10-28 20:29:00 +00004854 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4855 return RewriteObjCTryStmt(StmtTry);
4856
4857 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4858 return RewriteObjCSynchronizedStmt(StmtTry);
4859
4860 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4861 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004862
Steve Narofff4b992a2008-10-28 20:29:00 +00004863 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4864 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004865
4866 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004867 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004868 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004869 OrigStmtRange.getEnd());
4870 if (BreakStmt *StmtBreakStmt =
4871 dyn_cast<BreakStmt>(S))
4872 return RewriteBreakStmt(StmtBreakStmt);
4873 if (ContinueStmt *StmtContinueStmt =
4874 dyn_cast<ContinueStmt>(S))
4875 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004876
4877 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004878 // and cast exprs.
4879 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4880 // FIXME: What we're doing here is modifying the type-specifier that
4881 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004882 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004883 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4884 // the context of an ObjCForCollectionStmt. For example:
4885 // NSArray *someArray;
4886 // for (id <FooProtocol> index in someArray) ;
4887 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4888 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004889 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004890 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004891
Steve Narofff4b992a2008-10-28 20:29:00 +00004892 // Blocks rewrite rules.
4893 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4894 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004895 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004896 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004897 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004898 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004899 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004900 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004901 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
4902 if (VD->hasAttr<BlocksAttr>())
4903 RewriteByRefVar(VD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004904 }
4905 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004906 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004907 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004908 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004909 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4910 }
4911 }
4912 }
Mike Stump11289f42009-09-09 15:08:12 +00004913
Steve Narofff4b992a2008-10-28 20:29:00 +00004914 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4915 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004916
4917 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004918 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4919 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004920 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4921 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004922 && "Statement stack mismatch");
4923 Stmts.pop_back();
4924 }
4925 // Handle blocks rewriting.
4926 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4927 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004928 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004929 }
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004930 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4931 ValueDecl *VD = DRE->getDecl();
4932 if (VD->hasAttr<BlocksAttr>())
4933 return RewriteBlockDeclRefExpr(DRE);
4934 }
4935
Steve Narofff4b992a2008-10-28 20:29:00 +00004936 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004937 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004938 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004939 ReplaceStmt(S, BlockCall);
4940 return BlockCall;
4941 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004942 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004943 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004944 RewriteCastExpr(CE);
4945 }
4946#if 0
4947 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004948 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004949 // Get the new text.
4950 std::string SStr;
4951 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004952 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004953 const std::string &Str = Buf.str();
4954
4955 printf("CAST = %s\n", &Str[0]);
4956 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4957 delete S;
4958 return Replacement;
4959 }
4960#endif
4961 // Return this stmt unmodified.
4962 return S;
4963}
4964
Steve Naroffe70a52a2009-12-05 15:55:59 +00004965void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4966 for (RecordDecl::field_iterator i = RD->field_begin(),
4967 e = RD->field_end(); i != e; ++i) {
4968 FieldDecl *FD = *i;
4969 if (isTopLevelBlockPointerType(FD->getType()))
4970 RewriteBlockPointerDecl(FD);
4971 if (FD->getType()->isObjCQualifiedIdType() ||
4972 FD->getType()->isObjCQualifiedInterfaceType())
4973 RewriteObjCQualifiedInterfaceTypes(FD);
4974 }
4975}
4976
Steve Narofff4b992a2008-10-28 20:29:00 +00004977/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4978/// main file of the input.
4979void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4980 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00004981 if (FD->isOverloadedOperator())
4982 return;
Mike Stump11289f42009-09-09 15:08:12 +00004983
Steve Narofff4b992a2008-10-28 20:29:00 +00004984 // Since function prototypes don't have ParmDecl's, we check the function
4985 // prototype. This enables us to rewrite function declarations and
4986 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004987 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004988
Sebastian Redla7b98a72009-04-26 20:35:05 +00004989 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004990 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004991 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004992 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004993 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004994 Body =
4995 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4996 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004997 CurrentBody = 0;
4998 if (PropParentMap) {
4999 delete PropParentMap;
5000 PropParentMap = 0;
5001 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005002 // This synthesizes and inserts the block "impl" struct, invoke function,
5003 // and any copy/dispose helper functions.
5004 InsertBlockLiteralsWithinFunction(FD);
5005 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00005006 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005007 return;
5008 }
5009 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00005010 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005011 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005012 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005013 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00005014 Body =
5015 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5016 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00005017 CurrentBody = 0;
5018 if (PropParentMap) {
5019 delete PropParentMap;
5020 PropParentMap = 0;
5021 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005022 InsertBlockLiteralsWithinMethod(MD);
5023 CurMethodDef = 0;
5024 }
5025 }
5026 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5027 ClassImplementation.push_back(CI);
5028 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5029 CategoryImplementation.push_back(CI);
5030 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5031 RewriteForwardClassDecl(CD);
5032 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5033 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00005034 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005035 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00005036 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005037 CheckFunctionPointerDecl(VD->getType(), VD);
5038 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00005039 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005040 RewriteCastExpr(CE);
5041 }
5042 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00005043 } else if (VD->getType()->isRecordType()) {
5044 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5045 if (RD->isDefinition())
5046 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005047 }
Steve Naroffd8907b72008-10-29 18:15:37 +00005048 if (VD->getInit()) {
5049 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00005050 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005051 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00005052 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00005053 CurrentBody = 0;
5054 if (PropParentMap) {
5055 delete PropParentMap;
5056 PropParentMap = 0;
5057 }
Mike Stump11289f42009-09-09 15:08:12 +00005058 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00005059 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00005060 GlobalVarDecl = 0;
5061
5062 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00005063 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00005064 RewriteCastExpr(CE);
5065 }
5066 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005067 return;
5068 }
5069 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00005070 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00005071 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00005072 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00005073 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00005074 else if (TD->getUnderlyingType()->isRecordType()) {
5075 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5076 if (RD->isDefinition())
5077 RewriteRecordBody(RD);
5078 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005079 return;
5080 }
5081 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00005082 if (RD->isDefinition())
5083 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00005084 return;
5085 }
5086 // Nothing yet.
5087}
5088
Chris Lattnercf169832009-03-28 04:11:33 +00005089void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005090 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00005091
Steve Narofff4b992a2008-10-28 20:29:00 +00005092 // Rewrite tabs if we care.
5093 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00005094
Steve Narofff4b992a2008-10-28 20:29:00 +00005095 if (Diags.hasErrorOccurred())
5096 return;
Mike Stump11289f42009-09-09 15:08:12 +00005097
Steve Narofff4b992a2008-10-28 20:29:00 +00005098 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005099
Steve Naroffd9803712009-04-29 16:37:50 +00005100 // Here's a great place to add any extra declarations that may be needed.
5101 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005102 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005103 E = ProtocolExprDecls.end(); I != E; ++I)
5104 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5105
Mike Stump11289f42009-09-09 15:08:12 +00005106 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00005107 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005108 if (ClassImplementation.size() || CategoryImplementation.size())
5109 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005110
Steve Narofff4b992a2008-10-28 20:29:00 +00005111 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5112 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005113 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005114 Rewrite.getRewriteBufferFor(MainFileID)) {
5115 //printf("Changed:\n");
5116 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5117 } else {
5118 fprintf(stderr, "No changes\n");
5119 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005120
Steve Naroffd9803712009-04-29 16:37:50 +00005121 if (ClassImplementation.size() || CategoryImplementation.size() ||
5122 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005123 // Rewrite Objective-c meta data*
5124 std::string ResultStr;
5125 SynthesizeMetaDataIntoBuffer(ResultStr);
5126 // Emit metadata.
5127 *OutFile << ResultStr;
5128 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005129 OutFile->flush();
5130}
5131