blob: 5fcecc603078b42d3570d7478626902ef8d25a99 [file] [log] [blame]
Steve Naroff44e81222008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnerb429ae42007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattnerb429ae42007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Narofffbed6802008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner569faa62007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000023#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000024#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000025#include "llvm/ADT/OwningPtr.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000026#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000027#include "llvm/Support/CommandLine.h"
Dan Gohman6da15102008-05-21 20:19:16 +000028#include "llvm/Support/Streams.h"
Ted Kremenek7b6f67b2008-09-13 05:16:45 +000029#include "llvm/Support/raw_ostream.h"
Chris Lattner673f2bd2008-03-22 00:08:40 +000030#include "llvm/System/Path.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000031using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000032using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000033
Steve Naroff1c46cf12008-01-28 21:34:52 +000034static llvm::cl::opt<bool>
35SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
36 llvm::cl::desc("Silence ObjC rewriting warnings"));
37
Chris Lattnerb429ae42007-10-11 00:43:27 +000038namespace {
Steve Naroff44e81222008-04-14 22:03:09 +000039 class RewriteObjC : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000040 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000041 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000042 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000043 unsigned RewriteFailedDiag;
Steve Naroff43964fb2008-12-05 17:03:39 +000044 unsigned TryFinallyContainsReturnDiag;
45
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000046 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000047 SourceManager *SM;
Argiris Kirtzidisd3586002008-04-17 14:40:12 +000048 TranslationUnitDecl *TUDecl;
Chris Lattnerf4f776a2009-01-17 06:22:33 +000049 FileID MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000050 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000051 SourceLocation LastIncLoc;
Steve Narofffef037c2008-03-27 22:29:16 +000052
Ted Kremenek42730c52008-01-07 19:49:32 +000053 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
54 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
55 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff04eaa192008-05-06 18:26:51 +000056 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek42730c52008-01-07 19:49:32 +000057 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
58 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000059 llvm::SmallVector<Stmt *, 32> Stmts;
60 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffe9780582007-10-23 23:50:29 +000061
Steve Naroff47e7fa22008-03-15 00:55:56 +000062 unsigned NumObjCStringLiterals;
63
Steve Naroffe9780582007-10-23 23:50:29 +000064 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000065 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000066 FunctionDecl *MsgSendStretFunctionDecl;
67 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000068 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000069 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000070 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000071 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000072 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000073 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000074 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000075
Steve Naroff0add5d22007-11-03 11:27:19 +000076 // ObjC string constant support.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000077 VarDecl *ConstantStringClassReference;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000079
Fariborz Jahanian22277422008-01-16 00:09:11 +000080 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000081 int BcLabelCount;
82
Steve Naroff764c1ae2007-11-15 10:28:18 +000083 // Needed for super.
Steve Naroff38a9e3f2008-10-27 17:20:55 +000084 ObjCMethodDecl *CurMethodDef;
Steve Naroff764c1ae2007-11-15 10:28:18 +000085 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000086 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000087
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000088 // Needed for header files being rewritten
89 bool IsHeader;
90
Steve Naroffcfd9f4c2008-03-28 22:26:09 +000091 std::string InFileName;
92 std::string OutFileName;
93
Steve Narofffef037c2008-03-27 22:29:16 +000094 std::string Preamble;
Steve Naroff38a9e3f2008-10-27 17:20:55 +000095
96 // Block expressions.
97 llvm::SmallVector<BlockExpr *, 32> Blocks;
98 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
99 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Steve Narofffef037c2008-03-27 22:29:16 +0000100
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000101 // Block related declarations.
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
104 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
105
106 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
107
Steve Naroff0e948412008-12-04 16:24:46 +0000108 // This maps a property to it's assignment statement.
109 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Narofffbed6802008-12-08 16:43:47 +0000110 // This maps a property to it's synthesied message expression.
111 // This allows us to rewrite chained getters (e.g. o.a.b.c).
112 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
113
Steve Naroff102c3f22008-12-04 23:50:32 +0000114 // This maps an original source AST to it's rewritten form. This allows
115 // us to avoid rewriting the same node twice (which is very uncommon).
116 // This is needed to support some of the exotic property rewriting.
117 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff6ce8a12008-12-03 00:56:33 +0000118
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000119 FunctionDecl *CurFunctionDef;
Steve Naroff80c54752008-10-29 18:15:37 +0000120 VarDecl *GlobalVarDecl;
121
Steve Naroffedb4bc92008-12-09 12:56:34 +0000122 bool DisableReplaceStmt;
123
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000124 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +0000125 public:
Ted Kremenek79b50cb2008-05-31 20:11:04 +0000126 virtual void Initialize(ASTContext &context);
127
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000128 // Top Level Driver code.
Chris Lattnera17991f2009-03-29 16:50:03 +0000129 virtual void HandleTopLevelDecl(DeclGroupRef D) {
130 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
131 HandleTopLevelSingleDecl(*I);
132 }
133 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000134 void HandleDeclInMainFile(Decl *D);
Steve Naroff44e81222008-04-14 22:03:09 +0000135 RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000136 Diagnostic &D, const LangOptions &LOpts);
Ted Kremenekcab0b0c2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
139
Chris Lattner2a594d02009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Chris Lattnerb1548372008-01-31 19:37:57 +0000141
142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff102c3f22008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
144
145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattnerb1548372008-01-31 19:37:57 +0000147
Steve Naroffedb4bc92008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff102c3f22008-12-04 23:50:32 +0000151 // If replacement succeeded or warning disabled return with no warning.
152 if (!Rewrite.ReplaceStmt(Old, New)) {
153 ReplacedNodes[Old] = New;
154 return;
155 }
156 if (SilenceRewriteMacroWarning)
157 return;
Chris Lattner6948ae62008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattnerb1548372008-01-31 19:37:57 +0000160 }
Steve Naroffedb4bc92008-12-09 12:56:34 +0000161
162 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
163 // Measaure the old text.
164 int Size = Rewrite.getRangeSize(SrcRange);
165 if (Size == -1) {
166 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
167 << Old->getSourceRange();
168 return;
169 }
170 // Get the new text.
171 std::string SStr;
172 llvm::raw_string_ostream S(SStr);
173 New->printPretty(S);
174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, &Str[0], Str.size())) {
178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
185 }
186
Steve Narofffef037c2008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Steve Narofffef037c2008-03-27 22:29:16 +0000190 if (!Rewrite.InsertText(Loc, StrData, StrLen, InsertAfter) ||
Chris Lattner6216f292008-01-31 19:42:41 +0000191 SilenceRewriteMacroWarning)
192 return;
193
194 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
195 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000196
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000197 void RemoveText(SourceLocation Loc, unsigned StrLen) {
198 // If removal succeeded or warning disabled return with no warning.
199 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
200 return;
201
202 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
203 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000204
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000205 void ReplaceText(SourceLocation Start, unsigned OrigLength,
206 const char *NewStr, unsigned NewLength) {
207 // If removal succeeded or warning disabled return with no warning.
208 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
209 SilenceRewriteMacroWarning)
210 return;
211
212 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
213 }
214
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000215 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000216 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000217 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000218 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000219 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffea6610f2008-12-02 17:36:43 +0000220 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
221 ObjCImplementationDecl *IMD,
222 ObjCCategoryImplDecl *CID);
Ted Kremenek42730c52008-01-07 19:49:32 +0000223 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000224 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000225 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
226 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
227 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
228 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
229 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff56af2002009-01-11 01:06:09 +0000230 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000231 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000232 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd06c88d2008-07-29 18:15:38 +0000233 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000234 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000235 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000236 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000237 QualType getConstantStringStructType();
Steve Naroffef82b742008-05-31 14:15:04 +0000238 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Chris Lattner6fe8b272007-10-16 22:36:42 +0000239
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000240 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000241 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff0e948412008-12-04 16:24:46 +0000242 void CollectPropertySetters(Stmt *S);
243
Steve Narofffbed6802008-12-08 16:43:47 +0000244 Stmt *CurrentBody;
245 ParentMap *PropParentMap; // created lazily.
246
Chris Lattner0021f452007-10-24 16:57:36 +0000247 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner343c82b2008-05-23 20:40:52 +0000248 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff0e948412008-12-04 16:24:46 +0000249 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Steve Naroffedb4bc92008-12-09 12:56:34 +0000250 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
251 SourceRange SrcRange);
Steve Naroff296b74f2007-11-05 14:50:49 +0000252 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000253 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000254 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000255 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroff43964fb2008-12-05 17:03:39 +0000256 void WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000257 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000258 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000259 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
260 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
261 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000262 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
263 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000264 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
265 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000266 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000267 Stmt *RewriteBreakStmt(BreakStmt *S);
268 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000269 void SynthCountByEnumWithState(std::string &buf);
270
Steve Naroff02a82aa2007-10-30 23:14:51 +0000271 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000272 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000273 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000274 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000275 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000276 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000277 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000278 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000279 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000280 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000281
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000282 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000283 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000284 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000285
Ted Kremenek42730c52008-01-07 19:49:32 +0000286 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000287 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000288
Ted Kremenek42730c52008-01-07 19:49:32 +0000289 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
290 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000291 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000292 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000293 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000294 const char *ClassName,
295 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000296
Chris Lattner0be08822008-07-21 21:32:27 +0000297 void RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl>
298 &Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000299 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000300 const char *ClassName,
301 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000302 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000303 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000304 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
305 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000306 std::string &Result);
Steve Naroff21658f62008-11-13 20:07:04 +0000307 void RewriteImplementations();
308 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000309
310 // Block rewriting.
Douglas Gregor4fa58902009-02-26 23:50:07 +0000311 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000312 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
313
314 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
315 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
316
Steve Naroff80c54752008-10-29 18:15:37 +0000317 // Block specific rewrite rules.
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000318 void RewriteBlockCall(CallExpr *Exp);
319 void RewriteBlockPointerDecl(NamedDecl *VD);
320 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
321 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
322
323 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
324 const char *funcName, std::string Tag);
325 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
326 const char *funcName, std::string Tag);
327 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
328 bool hasCopyDisposeHelpers);
Steve Naroff85eb17b2008-10-30 10:07:53 +0000329 Stmt *SynthesizeBlockCall(CallExpr *Exp);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000330 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
331 const char *FunName);
332
333 void CollectBlockDeclRefInfo(BlockExpr *Exp);
334 void GetBlockCallExprs(Stmt *S);
335 void GetBlockDeclRefExprs(Stmt *S);
336
337 // We avoid calling Type::isBlockPointerType(), since it operates on the
338 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000339 bool isTopLevelBlockPointerType(QualType T) {
340 return isa<BlockPointerType>(T);
341 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000342
343 // FIXME: This predicate seems like it would be useful to add to ASTContext.
344 bool isObjCType(QualType T) {
345 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
346 return false;
347
348 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
349
350 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
351 OCT == Context->getCanonicalType(Context->getObjCClassType()))
352 return true;
353
354 if (const PointerType *PT = OCT->getAsPointerType()) {
355 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
356 isa<ObjCQualifiedIdType>(PT->getPointeeType()))
357 return true;
358 }
359 return false;
360 }
361 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek0c97e042009-02-07 01:47:29 +0000362 void GetExtentOfArgList(const char *Name, const char *&LParen,
363 const char *&RParen);
Steve Naroff7f1412d2008-11-03 23:29:32 +0000364 void RewriteCastExpr(CStyleCastExpr *CE);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +0000365
366 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff80c54752008-10-29 18:15:37 +0000367 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000368 };
369}
370
Douglas Gregor4fa58902009-02-26 23:50:07 +0000371void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000372 NamedDecl *D) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000373 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
374 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000375 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +0000376 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000377 // All the args are checked/rewritten. Don't call twice!
378 RewriteBlockPointerDecl(D);
379 break;
380 }
381 }
382}
383
384void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
385 const PointerType *PT = funcType->getAsPointerType();
386 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor4fa58902009-02-26 23:50:07 +0000387 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000388}
389
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000390static bool IsHeaderFile(const std::string &Filename) {
391 std::string::size_type DotPos = Filename.rfind('.');
392
393 if (DotPos == std::string::npos) {
394 // no file extension
395 return false;
396 }
397
398 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
399 // C header: .h
400 // C++ header: .hh or .H;
401 return Ext == "h" || Ext == "hh" || Ext == "H";
402}
403
Steve Naroff44e81222008-04-14 22:03:09 +0000404RewriteObjC::RewriteObjC(std::string inFile, std::string outFile,
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000405 Diagnostic &D, const LangOptions &LOpts)
406 : Diags(D), LangOpts(LOpts) {
407 IsHeader = IsHeaderFile(inFile);
408 InFileName = inFile;
409 OutFileName = outFile;
410 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
411 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff43964fb2008-12-05 17:03:39 +0000412 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek0c97e042009-02-07 01:47:29 +0000413 "rewriter doesn't support user-specified control flow semantics "
414 "for @try/@finally (code may not execute properly)");
Steve Naroffcfd9f4c2008-03-28 22:26:09 +0000415}
416
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000417ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Chris Lattner673f2bd2008-03-22 00:08:40 +0000418 const std::string& OutFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000419 Diagnostic &Diags,
420 const LangOptions &LOpts) {
Steve Naroff44e81222008-04-14 22:03:09 +0000421 return new RewriteObjC(InFile, OutFile, Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000422}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000423
Steve Naroff44e81222008-04-14 22:03:09 +0000424void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner12499682008-01-31 19:38:44 +0000425 Context = &context;
426 SM = &Context->getSourceManager();
Argiris Kirtzidisd3586002008-04-17 14:40:12 +0000427 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner12499682008-01-31 19:38:44 +0000428 MsgSendFunctionDecl = 0;
429 MsgSendSuperFunctionDecl = 0;
430 MsgSendStretFunctionDecl = 0;
431 MsgSendSuperStretFunctionDecl = 0;
432 MsgSendFpretFunctionDecl = 0;
433 GetClassFunctionDecl = 0;
434 GetMetaClassFunctionDecl = 0;
435 SelGetUidFunctionDecl = 0;
436 CFStringFunctionDecl = 0;
437 GetProtocolFunctionDecl = 0;
438 ConstantStringClassReference = 0;
439 NSStringRecord = 0;
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000440 CurMethodDef = 0;
441 CurFunctionDef = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000442 GlobalVarDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000443 SuperStructDecl = 0;
Steve Naroff053ae3f2008-03-27 22:59:54 +0000444 ConstantStringDecl = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000445 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000446 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000447 NumObjCStringLiterals = 0;
Steve Naroffbad6f3b2008-12-08 20:01:41 +0000448 PropParentMap = 0;
449 CurrentBody = 0;
Steve Naroffedb4bc92008-12-09 12:56:34 +0000450 DisableReplaceStmt = false;
451
Chris Lattner12499682008-01-31 19:38:44 +0000452 // Get the ID and start/end of the main file.
453 MainFileID = SM->getMainFileID();
454 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
455 MainFileStart = MainBuf->getBufferStart();
456 MainFileEnd = MainBuf->getBufferEnd();
Steve Narofffef037c2008-03-27 22:29:16 +0000457
Chris Lattner12499682008-01-31 19:38:44 +0000458 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000459
Chris Lattner12499682008-01-31 19:38:44 +0000460 // declaring objc_selector outside the parameter list removes a silly
461 // scope related warning...
Steve Narofffef037c2008-03-27 22:29:16 +0000462 if (IsHeader)
Steve Naroff08299f82009-02-03 20:39:18 +0000463 Preamble = "#pragma once\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000464 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff12673622008-12-23 20:11:22 +0000465 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Narofffef037c2008-03-27 22:29:16 +0000466 Preamble += "struct objc_object *superClass; ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000467 if (LangOpts.Microsoft) {
468 // Add a constructor for creating temporary objects.
Ted Kremenek0c97e042009-02-07 01:47:29 +0000469 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
470 ": ";
Steve Narofffef037c2008-03-27 22:29:16 +0000471 Preamble += "object(o), superClass(s) {} ";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000472 }
Steve Narofffef037c2008-03-27 22:29:16 +0000473 Preamble += "};\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000474 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
475 Preamble += "typedef struct objc_object Protocol;\n";
476 Preamble += "#define _REWRITER_typedef_Protocol\n";
477 Preamble += "#endif\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000478 if (LangOpts.Microsoft) {
479 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
480 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
481 } else
482 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
483 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Narofffef037c2008-03-27 22:29:16 +0000484 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000485 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Narofffef037c2008-03-27 22:29:16 +0000486 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000487 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000488 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000489 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Narofffef037c2008-03-27 22:29:16 +0000490 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000491 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Narofffef037c2008-03-27 22:29:16 +0000492 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000493 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000494 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000495 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Narofffef037c2008-03-27 22:29:16 +0000496 Preamble += "(const char *);\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000497 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
498 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
499 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
500 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
501 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff3e2c98c2008-05-09 21:17:56 +0000502 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroffcd25d782008-07-16 18:58:11 +0000503 // @synchronized hooks.
Steve Naroff1b208d72008-12-08 17:30:33 +0000504 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
505 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
506 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000507 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
508 Preamble += "struct __objcFastEnumerationState {\n\t";
509 Preamble += "unsigned long state;\n\t";
Steve Naroffc960e9d2008-04-04 22:58:22 +0000510 Preamble += "void **itemsPtr;\n\t";
Steve Narofffef037c2008-03-27 22:29:16 +0000511 Preamble += "unsigned long *mutationsPtr;\n\t";
512 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000513 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000514 Preamble += "#define __FASTENUMERATIONSTATE\n";
515 Preamble += "#endif\n";
516 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
517 Preamble += "struct __NSConstantStringImpl {\n";
518 Preamble += " int *isa;\n";
519 Preamble += " int flags;\n";
520 Preamble += " char *str;\n";
521 Preamble += " long length;\n";
522 Preamble += "};\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000523 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
524 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
525 Preamble += "#else\n";
Steve Naroff1b208d72008-12-08 17:30:33 +0000526 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffc6e571e2008-08-05 20:04:48 +0000527 Preamble += "#endif\n";
Steve Narofffef037c2008-03-27 22:29:16 +0000528 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
529 Preamble += "#endif\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000530 // Blocks preamble.
531 Preamble += "#ifndef BLOCK_IMPL\n";
532 Preamble += "#define BLOCK_IMPL\n";
533 Preamble += "struct __block_impl {\n";
534 Preamble += " void *isa;\n";
535 Preamble += " int Flags;\n";
536 Preamble += " int Size;\n";
537 Preamble += " void *FuncPtr;\n";
538 Preamble += "};\n";
Steve Naroff44fe1e32008-12-16 15:50:30 +0000539 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
540 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_assign(void *, const void *, const int);\n";
541 Preamble += "__OBJC_RW_STATICIMPORT void _Block_object_dispose(const void *, const int);\n";
542 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteGlobalBlock[32];\n";
543 Preamble += "__OBJC_RW_STATICIMPORT void *_NSConcreteStackBlock[32];\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +0000544 Preamble += "#endif\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000545 if (LangOpts.Microsoft) {
Steve Naroff1b208d72008-12-08 17:30:33 +0000546 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
547 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroff39ba90e2008-10-27 18:50:14 +0000548 Preamble += "#define __attribute__(X)\n";
549 }
Chris Lattner12499682008-01-31 19:38:44 +0000550}
551
552
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000553//===----------------------------------------------------------------------===//
554// Top Level Driver Code
555//===----------------------------------------------------------------------===//
556
Chris Lattnera17991f2009-03-29 16:50:03 +0000557void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000558 // Two cases: either the decl could be in the main file, or it could be in a
559 // #included file. If the former, rewrite it now. If the later, check to see
560 // if we rewrote the #include/#import.
561 SourceLocation Loc = D->getLocation();
Chris Lattner18c8dc02009-01-16 07:36:28 +0000562 Loc = SM->getInstantiationLoc(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000563
564 // If this is for a builtin, ignore it.
565 if (Loc.isInvalid()) return;
566
Steve Naroffe9780582007-10-23 23:50:29 +0000567 // Look for built-in declarations that we need to refer during the rewrite.
568 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000569 RewriteFunctionDecl(FD);
Steve Naroff72a6ebc2008-04-15 22:42:06 +0000570 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000571 // declared in <Foundation/NSString.h>
Chris Lattnerd120b9e2008-11-24 03:54:41 +0000572 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000573 ConstantStringClassReference = FVD;
574 return;
575 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000576 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000577 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000578 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000579 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000580 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000581 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000582 } else if (ObjCForwardProtocolDecl *FP =
583 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000584 RewriteForwardProtocolDecl(FP);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000585 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
586 // Recurse into linkage specifications
587 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
588 DIEnd = LSD->decls_end();
589 DI != DIEnd; ++DI)
Chris Lattnera17991f2009-03-29 16:50:03 +0000590 HandleTopLevelSingleDecl(*DI);
Steve Naroffe9780582007-10-23 23:50:29 +0000591 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000592 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenek2450c262008-04-14 21:24:13 +0000593 if (SM->isFromMainFile(Loc))
Chris Lattner74db1682007-10-16 21:07:07 +0000594 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000595}
596
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000597//===----------------------------------------------------------------------===//
598// Syntactic (non-AST) Rewriting Code
599//===----------------------------------------------------------------------===//
600
Steve Naroff44e81222008-04-14 22:03:09 +0000601void RewriteObjC::RewriteInclude() {
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000602 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000603 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
604 const char *MainBufStart = MainBuf.first;
605 const char *MainBufEnd = MainBuf.second;
606 size_t ImportLen = strlen("import");
607 size_t IncludeLen = strlen("include");
608
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000609 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000610 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
611 if (*BufPtr == '#') {
612 if (++BufPtr == MainBufEnd)
613 return;
614 while (*BufPtr == ' ' || *BufPtr == '\t')
615 if (++BufPtr == MainBufEnd)
616 return;
617 if (!strncmp(BufPtr, "import", ImportLen)) {
618 // replace import with include
619 SourceLocation ImportLoc =
620 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000621 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000622 BufPtr += ImportLen;
623 }
624 }
625 }
Chris Lattner74db1682007-10-16 21:07:07 +0000626}
627
Steve Naroff44e81222008-04-14 22:03:09 +0000628void RewriteObjC::RewriteTabs() {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000629 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
630 const char *MainBufStart = MainBuf.first;
631 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000632
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000633 // Loop over the whole file, looking for tabs.
634 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
635 if (*BufPtr != '\t')
636 continue;
637
638 // Okay, we found a tab. This tab will turn into at least one character,
639 // but it depends on which 'virtual column' it is in. Compute that now.
640 unsigned VCol = 0;
641 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
642 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
643 ++VCol;
644
645 // Okay, now that we know the virtual column, we know how many spaces to
646 // insert. We assume 8-character tab-stops.
647 unsigned Spaces = 8-(VCol & 7);
648
649 // Get the location of the tab.
Chris Lattnerf4f776a2009-01-17 06:22:33 +0000650 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
651 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000652
653 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000654 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000655 }
Chris Lattner569faa62007-10-11 18:38:32 +0000656}
657
Steve Naroff121ed222008-12-02 15:48:25 +0000658static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
659 ObjCIvarDecl *OID) {
660 std::string S;
661 S = "((struct ";
662 S += ClassDecl->getIdentifier()->getName();
663 S += "_IMPL *)self)->";
664 S += OID->getNameAsCString();
665 return S;
666}
667
Steve Naroffea6610f2008-12-02 17:36:43 +0000668void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
669 ObjCImplementationDecl *IMD,
670 ObjCCategoryImplDecl *CID) {
Steve Naroff110be842008-12-01 20:33:01 +0000671 SourceLocation startLoc = PID->getLocStart();
672 InsertText(startLoc, "// ", 3);
Steve Naroff121ed222008-12-02 15:48:25 +0000673 const char *startBuf = SM->getCharacterData(startLoc);
674 assert((*startBuf == '@') && "bogus @synthesize location");
675 const char *semiBuf = strchr(startBuf, ';');
676 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek0c97e042009-02-07 01:47:29 +0000677 SourceLocation onePastSemiLoc =
678 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff121ed222008-12-02 15:48:25 +0000679
680 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
681 return; // FIXME: is this correct?
682
683 // Generate the 'getter' function.
Steve Naroff121ed222008-12-02 15:48:25 +0000684 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff121ed222008-12-02 15:48:25 +0000685 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff121ed222008-12-02 15:48:25 +0000686 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000687
688 if (!OID)
689 return;
690
691 std::string Getr;
692 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
693 Getr += "{ ";
694 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000695 // FIXME: deal with code generation implications for various property
696 // attributes (copy, retain, nonatomic).
697 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000698 Getr += "return " + getIvarAccessString(ClassDecl, OID);
699 Getr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000700 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffea6610f2008-12-02 17:36:43 +0000701
702 // Add the rewritten getter to trigger meta data generation. An alternate, and
703 // possibly cleaner approach is to hack RewriteObjCMethodsMetaData() to deal
704 // with properties explicitly. The following addInstanceMethod() required far
705 // less code change (and actually models what the rewriter is doing).
706 if (IMD)
707 IMD->addInstanceMethod(PD->getGetterMethodDecl());
708 else
709 CID->addInstanceMethod(PD->getGetterMethodDecl());
Steve Naroff121ed222008-12-02 15:48:25 +0000710
711 if (PD->isReadOnly())
712 return;
713
714 // Generate the 'setter' function.
715 std::string Setr;
716 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000717 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000718 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000719 // FIXME: deal with code generation implications for various property
720 // attributes (copy, retain, nonatomic).
Steve Narofff6ce8a12008-12-03 00:56:33 +0000721 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000722 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff20f67392008-12-11 19:29:16 +0000723 Setr += PD->getNameAsCString();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000724 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000725 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffea6610f2008-12-02 17:36:43 +0000726
727 // Add the rewritten setter to trigger meta data generation.
728 if (IMD)
729 IMD->addInstanceMethod(PD->getSetterMethodDecl());
730 else
731 CID->addInstanceMethod(PD->getSetterMethodDecl());
Steve Naroff110be842008-12-01 20:33:01 +0000732}
Chris Lattner569faa62007-10-11 18:38:32 +0000733
Steve Naroff44e81222008-04-14 22:03:09 +0000734void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000735 // Get the start location and compute the semi location.
736 SourceLocation startLoc = ClassDecl->getLocation();
737 const char *startBuf = SM->getCharacterData(startLoc);
738 const char *semiPtr = strchr(startBuf, ';');
739
740 // Translate to typedef's that forward reference structs with the same name
741 // as the class. As a convenience, we include the original declaration
742 // as a comment.
743 std::string typedefString;
744 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000745 typedefString.append(startBuf, semiPtr-startBuf+1);
746 typedefString += "\n";
Chris Lattner6a028742009-02-20 18:04:31 +0000747 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
748 I != E; ++I) {
749 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff2aeae312007-11-09 12:50:28 +0000750 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000751 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000752 typedefString += "\n";
753 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000754 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000755 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000756 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000757 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000758 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000759 }
760
761 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000762 ReplaceText(startLoc, semiPtr-startBuf+1,
763 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000764}
765
Steve Naroff44e81222008-04-14 22:03:09 +0000766void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000767 SourceLocation LocStart = Method->getLocStart();
768 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000769
Chris Lattner2d89c562009-02-04 01:06:56 +0000770 if (SM->getInstantiationLineNumber(LocEnd) >
771 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000772 InsertText(LocStart, "#if 0\n", 6);
773 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000774 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000775 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000776 }
777}
778
Steve Naroff56af2002009-01-11 01:06:09 +0000779void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000780{
Steve Naroff56af2002009-01-11 01:06:09 +0000781 SourceLocation Loc = prop->getLocation();
782
783 ReplaceText(Loc, 0, "// ", 3);
784
785 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000786}
787
Steve Naroff44e81222008-04-14 22:03:09 +0000788void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000789 SourceLocation LocStart = CatDecl->getLocStart();
790
791 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000792 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000793
Ted Kremenek42730c52008-01-07 19:49:32 +0000794 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000795 E = CatDecl->instmeth_end(); I != E; ++I)
796 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000797 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000798 E = CatDecl->classmeth_end(); I != E; ++I)
799 RewriteMethodDeclaration(*I);
800
Steve Naroff667f1682007-10-30 13:30:57 +0000801 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000802 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000803}
804
Steve Naroff44e81222008-04-14 22:03:09 +0000805void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000806 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000807
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000808 SourceLocation LocStart = PDecl->getLocStart();
809
810 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000811 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000812
Ted Kremenek42730c52008-01-07 19:49:32 +0000813 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000814 E = PDecl->instmeth_end(); I != E; ++I)
815 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000816 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000817 E = PDecl->classmeth_end(); I != E; ++I)
818 RewriteMethodDeclaration(*I);
819
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000820 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000821 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000822 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000823
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000824 // Must comment out @optional/@required
825 const char *startBuf = SM->getCharacterData(LocStart);
826 const char *endBuf = SM->getCharacterData(LocEnd);
827 for (const char *p = startBuf; p < endBuf; p++) {
828 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
829 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000830 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000831 ReplaceText(OptionalLoc, strlen("@optional"),
832 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000833
834 }
835 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
836 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000837 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000838 ReplaceText(OptionalLoc, strlen("@required"),
839 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000840
841 }
842 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000843}
844
Steve Naroff44e81222008-04-14 22:03:09 +0000845void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000846 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000847 if (LocStart.isInvalid())
848 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000849 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000850 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000851}
852
Steve Naroff44e81222008-04-14 22:03:09 +0000853void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000854 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000855 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000856 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000857 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000858 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000859 ResultStr += "id";
Steve Naroff20f67392008-12-11 19:29:16 +0000860 else if (OMD->getResultType()->isFunctionPointerType() ||
861 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000862 // needs special handling, since pointer-to-functions have special
863 // syntax (where a decaration models use).
864 QualType retType = OMD->getResultType();
Steve Naroff20f67392008-12-11 19:29:16 +0000865 QualType PointeeTy;
866 if (const PointerType* PT = retType->getAsPointerType())
867 PointeeTy = PT->getPointeeType();
868 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
869 PointeeTy = BPT->getPointeeType();
870 if ((FPRetType = PointeeTy->getAsFunctionType())) {
871 ResultStr += FPRetType->getResultType().getAsString();
872 ResultStr += "(*";
Steve Naroff91044cf2008-07-16 14:40:40 +0000873 }
874 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000875 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000876 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000877
878 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000879 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000880
Douglas Gregor5d764842009-01-09 17:18:27 +0000881 if (OMD->isInstanceMethod())
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000882 NameStr += "_I_";
883 else
884 NameStr += "_C_";
885
Chris Lattner271d4c22008-11-24 05:29:24 +0000886 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000887 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000888
Ted Kremenek42730c52008-01-07 19:49:32 +0000889 if (ObjCCategoryImplDecl *CID =
Steve Naroff438be772009-01-08 19:41:02 +0000890 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000891 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000892 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000893 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000894 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000895 {
896 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000897 int len = selString.size();
898 for (int i = 0; i < len; i++)
899 if (selString[i] == ':')
900 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000901 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000902 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000903 // Remember this name for metadata emission
904 MethodInternalNames[OMD] = NameStr;
905 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000906
907 // Rewrite arguments
908 ResultStr += "(";
909
910 // invisible arguments
Douglas Gregor5d764842009-01-09 17:18:27 +0000911 if (OMD->isInstanceMethod()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000912 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000913 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000914 if (!LangOpts.Microsoft) {
915 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
916 ResultStr += "struct ";
917 }
918 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000919 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000920 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000921 }
922 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000923 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000924
925 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000926 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000927 ResultStr += " _cmd";
928
929 // Method arguments.
Chris Lattner5c6b2c62009-02-20 18:43:26 +0000930 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
931 E = OMD->param_end(); PI != E; ++PI) {
932 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000933 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000934 if (PDecl->getType()->isObjCQualifiedIdType()) {
935 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000936 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000937 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000938 std::string Name = PDecl->getNameAsString();
Steve Naroffd896f4b2008-12-11 21:05:33 +0000939 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff4e2ae512008-10-30 14:45:29 +0000940 // Make sure we convert "t (^)(...)" to "t (*)(...)".
941 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
942 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
943 } else
944 PDecl->getType().getAsStringInternal(Name);
Steve Naroff133dfda2008-04-18 21:13:19 +0000945 ResultStr += Name;
946 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000947 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000948 if (OMD->isVariadic())
949 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000950 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000951
Steve Naroff91044cf2008-07-16 14:40:40 +0000952 if (FPRetType) {
953 ResultStr += ")"; // close the precedence "scope" for "*".
954
955 // Now, emit the argument types (if any).
Douglas Gregor4fa58902009-02-26 23:50:07 +0000956 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000957 ResultStr += "(";
958 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
959 if (i) ResultStr += ", ";
960 std::string ParamStr = FT->getArgType(i).getAsString();
961 ResultStr += ParamStr;
962 }
963 if (FT->isVariadic()) {
964 if (FT->getNumArgs()) ResultStr += ", ";
965 ResultStr += "...";
966 }
967 ResultStr += ")";
968 } else {
969 ResultStr += "()";
970 }
971 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000972}
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000973void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000974 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
975 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000976
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000977 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000978 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000979 else
Chris Lattner6216f292008-01-31 19:42:41 +0000980 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000981
Ted Kremenek42730c52008-01-07 19:49:32 +0000982 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000983 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
984 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000985 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000986 ObjCMethodDecl *OMD = *I;
987 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000988 SourceLocation LocStart = OMD->getLocStart();
989 SourceLocation LocEnd = OMD->getBody()->getLocStart();
990
991 const char *startBuf = SM->getCharacterData(LocStart);
992 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000993 ReplaceText(LocStart, endBuf-startBuf,
994 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000995 }
996
Ted Kremenek42730c52008-01-07 19:49:32 +0000997 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000998 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
999 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001000 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001001 ObjCMethodDecl *OMD = *I;
1002 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001003 SourceLocation LocStart = OMD->getLocStart();
1004 SourceLocation LocEnd = OMD->getBody()->getLocStart();
1005
1006 const char *startBuf = SM->getCharacterData(LocStart);
1007 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001008 ReplaceText(LocStart, endBuf-startBuf,
1009 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001010 }
Steve Naroff110be842008-12-01 20:33:01 +00001011 for (ObjCCategoryImplDecl::propimpl_iterator
1012 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1013 E = IMD ? IMD->propimpl_end() : CID->propimpl_end(); I != E; ++I) {
Steve Naroffea6610f2008-12-02 17:36:43 +00001014 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroff110be842008-12-01 20:33:01 +00001015 }
1016
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001017 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +00001018 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001019 else
Chris Lattner6216f292008-01-31 19:42:41 +00001020 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001021}
1022
Steve Naroff44e81222008-04-14 22:03:09 +00001023void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +00001024 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001025 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +00001026 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +00001027 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001028 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001029 ResultStr += "\n";
1030 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001031 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001032 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +00001033 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +00001034 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001035 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +00001036 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001037 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +00001038 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001039 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +00001040
Steve Naroff56af2002009-01-11 01:06:09 +00001041 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1042 E = ClassDecl->prop_end(); I != E; ++I)
1043 RewriteProperty(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +00001044 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +00001045 E = ClassDecl->instmeth_end(); I != E; ++I)
1046 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +00001047 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +00001048 E = ClassDecl->classmeth_end(); I != E; ++I)
1049 RewriteMethodDeclaration(*I);
1050
Steve Naroff1ccf4632007-10-30 03:43:13 +00001051 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001052 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +00001053}
1054
Steve Naroffedb4bc92008-12-09 12:56:34 +00001055Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1056 SourceRange SrcRange) {
Steve Naroff0e948412008-12-04 16:24:46 +00001057 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1058 // This allows us to reuse all the fun and games in SynthMessageExpr().
1059 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1060 ObjCMessageExpr *MsgExpr;
1061 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1062 llvm::SmallVector<Expr *, 1> ExprVec;
1063 ExprVec.push_back(newStmt);
1064
Steve Narofffbed6802008-12-08 16:43:47 +00001065 Stmt *Receiver = PropRefExpr->getBase();
1066 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1067 if (PRE && PropGetters[PRE]) {
1068 // This allows us to handle chain/nested property getters.
1069 Receiver = PropGetters[PRE];
1070 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001071 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Naroff0e948412008-12-04 16:24:46 +00001072 PDecl->getSetterName(), PDecl->getType(),
1073 PDecl->getSetterMethodDecl(),
1074 SourceLocation(), SourceLocation(),
1075 &ExprVec[0], 1);
1076 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
1077
1078 // Now do the actual rewrite.
Steve Naroffedb4bc92008-12-09 12:56:34 +00001079 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroff478f7382008-12-10 14:53:27 +00001080 //delete BinOp;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001081 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1082 // to things that stay around.
1083 Context->Deallocate(MsgExpr);
Steve Naroff0e948412008-12-04 16:24:46 +00001084 return ReplacingStmt;
Steve Narofff6ce8a12008-12-03 00:56:33 +00001085}
1086
Steve Naroff0e948412008-12-04 16:24:46 +00001087Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff6ce8a12008-12-03 00:56:33 +00001088 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1089 // This allows us to reuse all the fun and games in SynthMessageExpr().
1090 ObjCMessageExpr *MsgExpr;
1091 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1092
Steve Narofffbed6802008-12-08 16:43:47 +00001093 Stmt *Receiver = PropRefExpr->getBase();
1094
1095 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1096 if (PRE && PropGetters[PRE]) {
1097 // This allows us to handle chain/nested property getters.
1098 Receiver = PropGetters[PRE];
1099 }
Ted Kremenek0c97e042009-02-07 01:47:29 +00001100 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
Steve Narofff6ce8a12008-12-03 00:56:33 +00001101 PDecl->getGetterName(), PDecl->getType(),
1102 PDecl->getGetterMethodDecl(),
1103 SourceLocation(), SourceLocation(),
1104 0, 0);
1105
Steve Naroff102c3f22008-12-04 23:50:32 +00001106 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001107
1108 if (!PropParentMap)
1109 PropParentMap = new ParentMap(CurrentBody);
1110
1111 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1112 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1113 // We stash away the ReplacingStmt since actually doing the
1114 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1115 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001116 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1117 // to things that stay around.
1118 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001119 return PropRefExpr; // return the original...
1120 } else {
1121 ReplaceStmt(PropRefExpr, ReplacingStmt);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001122 // delete PropRefExpr; elsewhere...
1123 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1124 // to things that stay around.
1125 Context->Deallocate(MsgExpr);
Steve Narofffbed6802008-12-08 16:43:47 +00001126 return ReplacingStmt;
1127 }
Steve Narofff6ce8a12008-12-03 00:56:33 +00001128}
1129
Chris Lattner343c82b2008-05-23 20:40:52 +00001130Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
1131 SourceLocation OrigStart) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001132 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001133 if (CurMethodDef) {
Steve Naroff60dfb6b2008-03-12 00:25:36 +00001134 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001135 ObjCInterfaceType *iFaceDecl =
1136 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffa9636222008-05-08 17:52:16 +00001137 // lookup which class implements the instance variable.
1138 ObjCInterfaceDecl *clsDeclared = 0;
1139 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
1140 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1141
1142 // Synthesize an explicit cast to gain access to the ivar.
1143 std::string RecName = clsDeclared->getIdentifier()->getName();
1144 RecName += "_IMPL";
1145 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001146 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001147 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +00001148 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1149 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001150 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1151 castT,SourceLocation(),
1152 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +00001153 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001154 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1155 IV->getBase()->getLocEnd(),
1156 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +00001157 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001158 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001159 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1160 IV->getLocation(),
1161 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +00001162 ReplaceStmt(IV, ME);
Steve Naroff102c3f22008-12-04 23:50:32 +00001163 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffa9636222008-05-08 17:52:16 +00001164 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +00001165 }
Chris Lattner343c82b2008-05-23 20:40:52 +00001166
1167 ReplaceStmt(IV->getBase(), PE);
1168 // Cannot delete IV->getBase(), since PE points to it.
1169 // Replace the old base with the cast. This is important when doing
1170 // embedded rewrites. For example, [newInv->_container addObject:0].
1171 IV->setBase(PE);
1172 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001173 }
Steve Naroffe6155362008-04-18 21:55:08 +00001174 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001175 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1176
1177 // Explicit ivar refs need to have a cast inserted.
1178 // FIXME: consider sharing some of this code with the code above.
1179 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001180 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001181 // lookup which class implements the instance variable.
1182 ObjCInterfaceDecl *clsDeclared = 0;
Steve Naroffa9636222008-05-08 17:52:16 +00001183 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001184 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1185
1186 // Synthesize an explicit cast to gain access to the ivar.
1187 std::string RecName = clsDeclared->getIdentifier()->getName();
1188 RecName += "_IMPL";
1189 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001190 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001191 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001192 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1193 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001194 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1195 castT, SourceLocation(),
1196 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001197 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001198 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner3cca6612008-05-28 16:38:23 +00001199 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001200 ReplaceStmt(IV->getBase(), PE);
1201 // Cannot delete IV->getBase(), since PE points to it.
1202 // Replace the old base with the cast. This is important when doing
1203 // embedded rewrites. For example, [newInv->_container addObject:0].
1204 IV->setBase(PE);
1205 return IV;
1206 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001207 }
Steve Naroffe6155362008-04-18 21:55:08 +00001208 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001209}
1210
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001211/// SynthCountByEnumWithState - To print:
1212/// ((unsigned int (*)
1213/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1214/// (void *)objc_msgSend)((id)l_collection,
1215/// sel_registerName(
1216/// "countByEnumeratingWithState:objects:count:"),
1217/// &enumState,
1218/// (id *)items, (unsigned int)16)
1219///
Steve Naroff44e81222008-04-14 22:03:09 +00001220void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001221 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1222 "id *, unsigned int))(void *)objc_msgSend)";
1223 buf += "\n\t\t";
1224 buf += "((id)l_collection,\n\t\t";
1225 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1226 buf += "\n\t\t";
1227 buf += "&enumState, "
1228 "(id *)items, (unsigned int)16)";
1229}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001230
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001231/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1232/// statement to exit to its outer synthesized loop.
1233///
Steve Naroff44e81222008-04-14 22:03:09 +00001234Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001235 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1236 return S;
1237 // replace break with goto __break_label
1238 std::string buf;
1239
1240 SourceLocation startLoc = S->getLocStart();
1241 buf = "goto __break_label_";
1242 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001243 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001244
1245 return 0;
1246}
1247
1248/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1249/// statement to continue with its inner synthesized loop.
1250///
Steve Naroff44e81222008-04-14 22:03:09 +00001251Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001252 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1253 return S;
1254 // replace continue with goto __continue_label
1255 std::string buf;
1256
1257 SourceLocation startLoc = S->getLocStart();
1258 buf = "goto __continue_label_";
1259 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001260 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001261
1262 return 0;
1263}
1264
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001265/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001266/// It rewrites:
1267/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001268
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001269/// Into:
1270/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001271/// type elem;
1272/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001273/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001274/// id l_collection = (id)collection;
1275/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1276/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001277/// if (limit) {
1278/// unsigned long startMutations = *enumState.mutationsPtr;
1279/// do {
1280/// unsigned long counter = 0;
1281/// do {
1282/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001283/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001284/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001285/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001286/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001287/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001288/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1289/// objects:items count:16]);
1290/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001291/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001292/// }
1293/// else
1294/// elem = nil;
1295/// }
1296///
Steve Naroff44e81222008-04-14 22:03:09 +00001297Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001298 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001299 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1300 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1301 "ObjCForCollectionStmt Statement stack mismatch");
1302 assert(!ObjCBcLabelNo.empty() &&
1303 "ObjCForCollectionStmt - Label No stack empty");
1304
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001305 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001306 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001307 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001308 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001309 std::string buf;
1310 buf = "\n{\n\t";
1311 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1312 // type elem;
Chris Lattner4a9a85e2009-03-28 06:33:19 +00001313 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001314 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001315 elementTypeAsString = ElementType.getAsString();
1316 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001317 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001318 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001319 buf += elementName;
1320 buf += ";\n\t";
1321 }
Chris Lattner690c2872008-04-08 05:52:18 +00001322 else {
1323 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001324 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001325 elementTypeAsString
1326 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001327 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001328
1329 // struct __objcFastEnumerationState enumState = { 0 };
1330 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1331 // id items[16];
1332 buf += "id items[16];\n\t";
1333 // id l_collection = (id)
1334 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001335 // Find start location of 'collection' the hard way!
1336 const char *startCollectionBuf = startBuf;
1337 startCollectionBuf += 3; // skip 'for'
1338 startCollectionBuf = strchr(startCollectionBuf, '(');
1339 startCollectionBuf++; // skip '('
1340 // find 'in' and skip it.
1341 while (*startCollectionBuf != ' ' ||
1342 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1343 (*(startCollectionBuf+3) != ' ' &&
1344 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1345 startCollectionBuf++;
1346 startCollectionBuf += 3;
1347
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001348 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001349 ReplaceText(startLoc, startCollectionBuf - startBuf,
1350 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001351 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001352 SourceLocation rightParenLoc = S->getRParenLoc();
1353 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1354 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001355 buf = ";\n\t";
1356
1357 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1358 // objects:items count:16];
1359 // which is synthesized into:
1360 // unsigned int limit =
1361 // ((unsigned int (*)
1362 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1363 // (void *)objc_msgSend)((id)l_collection,
1364 // sel_registerName(
1365 // "countByEnumeratingWithState:objects:count:"),
1366 // (struct __objcFastEnumerationState *)&state,
1367 // (id *)items, (unsigned int)16);
1368 buf += "unsigned long limit =\n\t\t";
1369 SynthCountByEnumWithState(buf);
1370 buf += ";\n\t";
1371 /// if (limit) {
1372 /// unsigned long startMutations = *enumState.mutationsPtr;
1373 /// do {
1374 /// unsigned long counter = 0;
1375 /// do {
1376 /// if (startMutations != *enumState.mutationsPtr)
1377 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001378 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001379 buf += "if (limit) {\n\t";
1380 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1381 buf += "do {\n\t\t";
1382 buf += "unsigned long counter = 0;\n\t\t";
1383 buf += "do {\n\t\t\t";
1384 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1385 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1386 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001387 buf += " = (";
1388 buf += elementTypeAsString;
1389 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001390 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001391 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001392
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001393 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001394 /// } while (counter < limit);
1395 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1396 /// objects:items count:16]);
1397 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001398 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001399 /// }
1400 /// else
1401 /// elem = nil;
1402 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001403 ///
1404 buf = ";\n\t";
1405 buf += "__continue_label_";
1406 buf += utostr(ObjCBcLabelNo.back());
1407 buf += ": ;";
1408 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001409 buf += "} while (counter < limit);\n\t";
1410 buf += "} while (limit = ";
1411 SynthCountByEnumWithState(buf);
1412 buf += ");\n\t";
1413 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001414 buf += " = ((id)0);\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001415 buf += "__break_label_";
1416 buf += utostr(ObjCBcLabelNo.back());
1417 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001418 buf += "}\n\t";
1419 buf += "else\n\t\t";
1420 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001421 buf += " = ((id)0);\n";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001422 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001423
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001424 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001425 if (isa<CompoundStmt>(S->getBody())) {
1426 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1427 InsertText(endBodyLoc, buf.c_str(), buf.size());
1428 } else {
1429 /* Need to treat single statements specially. For example:
1430 *
1431 * for (A *a in b) if (stuff()) break;
1432 * for (A *a in b) xxxyy;
1433 *
1434 * The following code simply scans ahead to the semi to find the actual end.
1435 */
1436 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1437 const char *semiBuf = strchr(stmtBuf, ';');
1438 assert(semiBuf && "Can't find ';'");
1439 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1440 InsertText(endBodyLoc, buf.c_str(), buf.size());
1441 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001442 Stmts.pop_back();
1443 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001444 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001445}
1446
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001447/// RewriteObjCSynchronizedStmt -
1448/// This routine rewrites @synchronized(expr) stmt;
1449/// into:
1450/// objc_sync_enter(expr);
1451/// @try stmt @finally { objc_sync_exit(expr); }
1452///
Steve Naroff44e81222008-04-14 22:03:09 +00001453Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001454 // Get the start location and compute the semi location.
1455 SourceLocation startLoc = S->getLocStart();
1456 const char *startBuf = SM->getCharacterData(startLoc);
1457
1458 assert((*startBuf == '@') && "bogus @synchronized location");
1459
1460 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001461 buf = "objc_sync_enter((id)";
1462 const char *lparenBuf = startBuf;
1463 while (*lparenBuf != '(') lparenBuf++;
1464 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001465 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1466 // the sync expression is typically a message expression that's already
1467 // been rewritten! (which implies the SourceLocation's are invalid).
1468 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001469 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001470 while (*endBuf != ')') endBuf--;
1471 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001472 buf = ");\n";
1473 // declare a new scope with two variables, _stack and _rethrow.
1474 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1475 buf += "int buf[18/*32-bit i386*/];\n";
1476 buf += "char *pointers[4];} _stack;\n";
1477 buf += "id volatile _rethrow = 0;\n";
1478 buf += "objc_exception_try_enter(&_stack);\n";
1479 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001480 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001481 startLoc = S->getSynchBody()->getLocEnd();
1482 startBuf = SM->getCharacterData(startLoc);
1483
Steve Naroff027cd0b2008-08-19 13:04:19 +00001484 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001485 SourceLocation lastCurlyLoc = startLoc;
1486 buf = "}\nelse {\n";
1487 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1488 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001489 buf += " objc_sync_exit(";
Ted Kremenek0c97e042009-02-07 01:47:29 +00001490 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1491 S->getSynchExpr(),
1492 Context->getObjCIdType(),
1493 SourceLocation(),
1494 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001495 std::string syncExprBufS;
1496 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001497 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001498 buf += syncExprBuf.str();
1499 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001500 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1501 buf += "}\n";
1502 buf += "}";
1503
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001504 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001505 return 0;
1506}
1507
Steve Naroff43964fb2008-12-05 17:03:39 +00001508void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1509 // Perform a bottom up traversal of all children.
1510 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1511 CI != E; ++CI)
1512 if (*CI)
1513 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1514
1515 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1516 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1517 Diags.Report(Context->getFullLoc(S->getLocStart()),
1518 TryFinallyContainsReturnDiag);
1519 }
1520 return;
1521}
1522
Steve Naroff44e81222008-04-14 22:03:09 +00001523Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001524 // Get the start location and compute the semi location.
1525 SourceLocation startLoc = S->getLocStart();
1526 const char *startBuf = SM->getCharacterData(startLoc);
1527
1528 assert((*startBuf == '@') && "bogus @try location");
1529
1530 std::string buf;
1531 // declare a new scope with two variables, _stack and _rethrow.
1532 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1533 buf += "int buf[18/*32-bit i386*/];\n";
1534 buf += "char *pointers[4];} _stack;\n";
1535 buf += "id volatile _rethrow = 0;\n";
1536 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001537 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001538
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001539 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001540
1541 startLoc = S->getTryBody()->getLocEnd();
1542 startBuf = SM->getCharacterData(startLoc);
1543
1544 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001545
Steve Naroffe9f69842007-11-07 04:08:17 +00001546 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001547 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1548 if (catchList) {
1549 startLoc = startLoc.getFileLocWithOffset(1);
1550 buf = " /* @catch begin */ else {\n";
1551 buf += " id _caught = objc_exception_extract(&_stack);\n";
1552 buf += " objc_exception_try_enter (&_stack);\n";
1553 buf += " if (_setjmp(_stack.buf))\n";
1554 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1555 buf += " else { /* @catch continue */";
1556
1557 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001558 } else { /* no catch list */
1559 buf = "}\nelse {\n";
1560 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1561 buf += "}";
1562 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001563 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001564 bool sawIdTypedCatch = false;
1565 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001566 while (catchList) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001567 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffe9f69842007-11-07 04:08:17 +00001568
1569 if (catchList == S->getCatchStmts())
1570 buf = "if ("; // we are generating code for the first catch clause
1571 else
1572 buf = "else if (";
1573 startLoc = catchList->getLocStart();
1574 startBuf = SM->getCharacterData(startLoc);
1575
1576 assert((*startBuf == '@') && "bogus @catch location");
1577
1578 const char *lParenLoc = strchr(startBuf, '(');
1579
Steve Naroff397c4ce2008-02-01 22:08:12 +00001580 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001581 // Now rewrite the body...
1582 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001583 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1584 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001585 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1586 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001587 assert((*bodyBuf == '{') && "bogus @catch body location");
1588
1589 buf += "1) { id _tmp = _caught;";
1590 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1591 buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001592 } else if (catchDecl) {
1593 QualType t = catchDecl->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001594 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001595 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001596 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001597 sawIdTypedCatch = true;
1598 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001599 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001600
Ted Kremenek42730c52008-01-07 19:49:32 +00001601 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001602 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001603 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001604 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001605 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001606 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001607 }
1608 }
1609 // Now rewrite the body...
1610 lastCatchBody = catchList->getCatchBody();
1611 SourceLocation rParenLoc = catchList->getRParenLoc();
1612 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1613 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1614 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1615 assert((*rParenBuf == ')') && "bogus @catch paren location");
1616 assert((*bodyBuf == '{') && "bogus @catch body location");
1617
1618 buf = " = _caught;";
1619 // Here we replace ") {" with "= _caught;" (which initializes and
1620 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001621 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001622 } else {
Steve Naroffe9f69842007-11-07 04:08:17 +00001623 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001624 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001625 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001626 catchList = catchList->getNextCatchStmt();
1627 }
1628 // Complete the catch list...
1629 if (lastCatchBody) {
1630 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001631 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1632 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001633
Steve Naroff31325c12008-09-11 15:29:03 +00001634 // Insert the last (implicit) else clause *before* the right curly brace.
1635 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1636 buf = "} /* last catch end */\n";
1637 buf += "else {\n";
1638 buf += " _rethrow = _caught;\n";
1639 buf += " objc_exception_try_exit(&_stack);\n";
1640 buf += "} } /* @catch end */\n";
1641 if (!S->getFinallyStmt())
1642 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001643 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001644
1645 // Set lastCurlyLoc
1646 lastCurlyLoc = lastCatchBody->getLocEnd();
1647 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001648 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001649 startLoc = finalStmt->getLocStart();
1650 startBuf = SM->getCharacterData(startLoc);
1651 assert((*startBuf == '@') && "bogus @finally start");
1652
1653 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001654 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001655
1656 Stmt *body = finalStmt->getFinallyBody();
1657 SourceLocation startLoc = body->getLocStart();
1658 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001659 assert(*SM->getCharacterData(startLoc) == '{' &&
1660 "bogus @finally body location");
1661 assert(*SM->getCharacterData(endLoc) == '}' &&
1662 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001663
1664 startLoc = startLoc.getFileLocWithOffset(1);
1665 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001666 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001667 endLoc = endLoc.getFileLocWithOffset(-1);
1668 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001669 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001670
1671 // Set lastCurlyLoc
1672 lastCurlyLoc = body->getLocEnd();
Steve Naroff43964fb2008-12-05 17:03:39 +00001673
1674 // Now check for any return/continue/go statements within the @try.
1675 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff31325c12008-09-11 15:29:03 +00001676 } else { /* no finally clause - make sure we synthesize an implicit one */
1677 buf = "{ /* implicit finally clause */\n";
1678 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1679 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1680 buf += "}";
1681 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001682 }
1683 // Now emit the final closing curly brace...
1684 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1685 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001686 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001687 return 0;
1688}
1689
Steve Naroff44e81222008-04-14 22:03:09 +00001690Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001691 return 0;
1692}
1693
Steve Naroff44e81222008-04-14 22:03:09 +00001694Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001695 return 0;
1696}
1697
Chris Lattnerb1548372008-01-31 19:37:57 +00001698// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001699// the throw expression is typically a message expression that's already
1700// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001701Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001702 // Get the start location and compute the semi location.
1703 SourceLocation startLoc = S->getLocStart();
1704 const char *startBuf = SM->getCharacterData(startLoc);
1705
1706 assert((*startBuf == '@') && "bogus @throw location");
1707
1708 std::string buf;
1709 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001710 if (S->getThrowExpr())
1711 buf = "objc_exception_throw(";
1712 else // add an implicit argument
1713 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001714
1715 // handle "@ throw" correctly.
1716 const char *wBuf = strchr(startBuf, 'w');
1717 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1718 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1719
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001720 const char *semiBuf = strchr(startBuf, ';');
1721 assert((*semiBuf == ';') && "@throw: can't find ';'");
1722 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1723 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001724 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001725 return 0;
1726}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001727
Steve Naroff44e81222008-04-14 22:03:09 +00001728Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001729 // Create a new string expression.
1730 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001731 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001732 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattneraa491192009-02-18 06:40:38 +00001733 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1734 StrEncoding.length(), false,StrType,
1735 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001736 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001737
Chris Lattner4478db92007-11-30 22:53:43 +00001738 // Replace this subexpr in the parent.
Steve Naroff102c3f22008-12-04 23:50:32 +00001739 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner0021f452007-10-24 16:57:36 +00001740 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001741}
1742
Steve Naroff44e81222008-04-14 22:03:09 +00001743Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff95f6bce2008-12-22 22:16:07 +00001744 if (!SelGetUidFunctionDecl)
1745 SynthSelGetUidFunctionDecl();
Steve Naroff296b74f2007-11-05 14:50:49 +00001746 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1747 // Create a call to sel_registerName("selName").
1748 llvm::SmallVector<Expr*, 8> SelExprs;
1749 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00001750 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00001751 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00001752 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00001753 false, argType, SourceLocation()));
Steve Naroff296b74f2007-11-05 14:50:49 +00001754 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1755 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001756 ReplaceStmt(Exp, SelExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00001757 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff296b74f2007-11-05 14:50:49 +00001758 return SelExp;
1759}
1760
Steve Naroff44e81222008-04-14 22:03:09 +00001761CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001762 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001763 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001764 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001765
1766 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001767 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001768
1769 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001770 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001771 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregor70d26122008-11-12 17:17:38 +00001772 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001773
1774 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001775
Ted Kremenek362abcd2009-02-09 20:51:47 +00001776 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1777 SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001778}
1779
Steve Naroffc8a92d12007-11-01 13:24:47 +00001780static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1781 const char *&startRef, const char *&endRef) {
1782 while (startBuf < endBuf) {
1783 if (*startBuf == '<')
1784 startRef = startBuf; // mark the start.
1785 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001786 if (startRef && *startRef == '<') {
1787 endRef = startBuf; // mark the end.
1788 return true;
1789 }
1790 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001791 }
1792 startBuf++;
1793 }
1794 return false;
1795}
1796
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001797static void scanToNextArgument(const char *&argRef) {
1798 int angle = 0;
1799 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1800 if (*argRef == '<')
1801 angle++;
1802 else if (*argRef == '>')
1803 angle--;
1804 argRef++;
1805 }
1806 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1807}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001808
Steve Naroff44e81222008-04-14 22:03:09 +00001809bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001810
Ted Kremenek42730c52008-01-07 19:49:32 +00001811 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001812 return true;
1813
Steve Naroffc8a92d12007-11-01 13:24:47 +00001814 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001815 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001816 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001817 return true; // we have "Class <Protocol> *".
1818 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001819 return false;
1820}
1821
Steve Naroffd06c88d2008-07-29 18:15:38 +00001822void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1823 QualType Type = E->getType();
1824 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001825 SourceLocation Loc, EndLoc;
1826
1827 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1828 Loc = ECE->getLParenLoc();
1829 EndLoc = ECE->getRParenLoc();
1830 } else {
1831 Loc = E->getLocStart();
1832 EndLoc = E->getLocEnd();
1833 }
1834 // This will defend against trying to rewrite synthesized expressions.
1835 if (Loc.isInvalid() || EndLoc.isInvalid())
1836 return;
1837
Steve Naroffd06c88d2008-07-29 18:15:38 +00001838 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001839 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001840 const char *startRef = 0, *endRef = 0;
1841 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1842 // Get the locations of the startRef, endRef.
1843 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1844 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1845 // Comment out the protocol references.
1846 InsertText(LessLoc, "/*", 2);
1847 InsertText(GreaterLoc, "*/", 2);
1848 }
1849 }
1850}
1851
Steve Naroff44e81222008-04-14 22:03:09 +00001852void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001853 SourceLocation Loc;
1854 QualType Type;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001855 const FunctionProtoType *proto = 0;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001856 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1857 Loc = VD->getLocation();
1858 Type = VD->getType();
1859 }
1860 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1861 Loc = FD->getLocation();
1862 // Check for ObjC 'id' and class types that have been adorned with protocol
1863 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1864 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1865 assert(funcType && "missing function type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00001866 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001867 if (!proto)
1868 return;
1869 Type = proto->getResultType();
1870 }
1871 else
1872 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001873
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001874 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001875 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001876
1877 const char *endBuf = SM->getCharacterData(Loc);
1878 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001879 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001880 startBuf--; // scan backward (from the decl location) for return type.
1881 const char *startRef = 0, *endRef = 0;
1882 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1883 // Get the locations of the startRef, endRef.
1884 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1885 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1886 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001887 InsertText(LessLoc, "/*", 2);
1888 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001889 }
1890 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001891 if (!proto)
1892 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001893 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001894 const char *startBuf = SM->getCharacterData(Loc);
1895 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001896 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1897 if (needToScanForQualifiers(proto->getArgType(i))) {
1898 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001899
Steve Naroffc8a92d12007-11-01 13:24:47 +00001900 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001901 // scan forward (from the decl location) for argument types.
1902 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001903 const char *startRef = 0, *endRef = 0;
1904 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1905 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001906 SourceLocation LessLoc =
1907 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1908 SourceLocation GreaterLoc =
1909 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001910 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001911 InsertText(LessLoc, "/*", 2);
1912 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001913 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001914 startBuf = ++endBuf;
1915 }
1916 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001917 // If the function name is derived from a macro expansion, then the
1918 // argument buffer will not follow the name. Need to speak with Chris.
1919 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001920 startBuf++; // scan forward (from the decl location) for argument types.
1921 startBuf++;
1922 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001923 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001924}
1925
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001926// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001927void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001928 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1929 llvm::SmallVector<QualType, 16> ArgTys;
1930 ArgTys.push_back(Context->getPointerType(
1931 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001932 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001933 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001934 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001935 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001936 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001937 SelGetUidIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001938 FunctionDecl::Extern, false);
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001939}
1940
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001941// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001942void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001943 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1944 llvm::SmallVector<QualType, 16> ArgTys;
1945 ArgTys.push_back(Context->getPointerType(
1946 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001947 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001948 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001949 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001950 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001951 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001952 SelGetProtoIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001953 FunctionDecl::Extern, false);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001954}
1955
Steve Naroff44e81222008-04-14 22:03:09 +00001956void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001957 // declared in <objc/objc.h>
Douglas Gregor7339c9e2009-01-09 01:47:02 +00001958 if (FD->getIdentifier() &&
1959 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001960 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001961 return;
1962 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001963 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001964}
1965
Steve Naroffbec4bf52008-03-11 17:37:02 +00001966// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001967void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001968 if (SuperContructorFunctionDecl)
1969 return;
Steve Naroff12673622008-12-23 20:11:22 +00001970 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffbec4bf52008-03-11 17:37:02 +00001971 llvm::SmallVector<QualType, 16> ArgTys;
1972 QualType argT = Context->getObjCIdType();
1973 assert(!argT.isNull() && "Can't find 'id' type");
1974 ArgTys.push_back(argT);
1975 ArgTys.push_back(argT);
1976 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1977 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001978 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001979 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001980 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001981 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001982 FunctionDecl::Extern, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00001983}
1984
Steve Naroff02a82aa2007-10-30 23:14:51 +00001985// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001986void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001987 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1988 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001989 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001990 assert(!argT.isNull() && "Can't find 'id' type");
1991 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001992 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001993 assert(!argT.isNull() && "Can't find 'SEL' type");
1994 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001995 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001996 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001997 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001998 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001999 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002000 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002001 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002002}
2003
Steve Naroff764c1ae2007-11-15 10:28:18 +00002004// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002005void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002006 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2007 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002008 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002009 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002010 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002011 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2012 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2013 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002014 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002015 assert(!argT.isNull() && "Can't find 'SEL' type");
2016 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002017 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002018 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002019 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002020 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002021 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002022 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002023 FunctionDecl::Extern, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002024}
2025
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002026// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002027void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002028 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2029 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002030 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002031 assert(!argT.isNull() && "Can't find 'id' type");
2032 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002033 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002034 assert(!argT.isNull() && "Can't find 'SEL' type");
2035 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002036 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002037 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002038 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002039 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002040 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002041 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002042 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002043}
2044
2045// SynthMsgSendSuperStretFunctionDecl -
2046// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002047void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002048 IdentifierInfo *msgSendIdent =
2049 &Context->Idents.get("objc_msgSendSuper_stret");
2050 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002051 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002052 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002053 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002054 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2055 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2056 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002057 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002058 assert(!argT.isNull() && "Can't find 'SEL' type");
2059 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002060 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002061 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002062 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002063 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00002064 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002065 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002066 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002067}
2068
Steve Naroff31316a12008-05-08 22:02:18 +00002069// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002070void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002071 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2072 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002073 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002074 assert(!argT.isNull() && "Can't find 'id' type");
2075 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002076 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002077 assert(!argT.isNull() && "Can't find 'SEL' type");
2078 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00002079 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002080 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002081 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002082 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002083 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002084 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002085 FunctionDecl::Extern, false);
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002086}
2087
Steve Naroff02a82aa2007-10-30 23:14:51 +00002088// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002089void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00002090 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2091 llvm::SmallVector<QualType, 16> ArgTys;
2092 ArgTys.push_back(Context->getPointerType(
2093 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002094 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002095 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002096 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002097 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002098 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002099 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002100 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002101}
2102
Steve Naroff3b1caac2007-12-07 03:50:46 +00002103// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002104void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002105 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2106 llvm::SmallVector<QualType, 16> ArgTys;
2107 ArgTys.push_back(Context->getPointerType(
2108 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002109 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002110 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002111 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002112 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002113 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002114 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002115 FunctionDecl::Extern, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002116}
2117
Steve Naroff44e81222008-04-14 22:03:09 +00002118Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002119 QualType strType = getConstantStringStructType();
2120
2121 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00002122
2123 std::string tmpName = InFileName;
2124 unsigned i;
2125 for (i=0; i < tmpName.length(); i++) {
2126 char c = tmpName.at(i);
2127 // replace any non alphanumeric characters with '_'.
2128 if (!isalpha(c) && (c < '0' || c > '9'))
2129 tmpName[i] = '_';
2130 }
2131 S += tmpName;
2132 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002133 S += utostr(NumObjCStringLiterals++);
2134
Steve Narofffef037c2008-03-27 22:29:16 +00002135 Preamble += "static __NSConstantStringImpl " + S;
2136 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2137 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00002138 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00002139 std::string prettyBufS;
2140 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002141 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00002142 Preamble += prettyBuf.str();
2143 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00002144 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00002145 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002146
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002147 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002148 &Context->Idents.get(S.c_str()), strType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002149 VarDecl::Static);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002150 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2151 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroff47e7fa22008-03-15 00:55:56 +00002152 Context->getPointerType(DRE->getType()),
2153 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00002154 // cast to NSConstantString *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002155 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroff7f1412d2008-11-03 23:29:32 +00002156 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00002157 ReplaceStmt(Exp, cast);
Steve Naroff102c3f22008-12-04 23:50:32 +00002158 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffabb96362007-11-08 14:30:50 +00002159 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00002160}
2161
Steve Naroff44e81222008-04-14 22:03:09 +00002162ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002163 // check if we are sending a message to 'super'
Douglas Gregor5d764842009-01-09 17:18:27 +00002164 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00002165
Douglas Gregord8606632008-11-04 14:56:14 +00002166 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2167 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner4423d372008-06-21 18:04:54 +00002168 assert(PT);
2169 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2170 return IT->getDecl();
2171 }
2172 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002173}
2174
2175// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00002176QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002177 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002178 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002179 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002180 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002181 QualType FieldTypes[2];
2182
2183 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00002184 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002185 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00002186 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002187
Steve Naroff764c1ae2007-11-15 10:28:18 +00002188 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002189 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002190 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002191 SourceLocation(), 0,
2192 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002193 /*Mutable=*/false));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002194 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002195
Douglas Gregor8acb7272008-12-11 16:49:14 +00002196 SuperStructDecl->completeDefinition(*Context);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002197 }
2198 return Context->getTagDeclType(SuperStructDecl);
2199}
2200
Steve Naroff44e81222008-04-14 22:03:09 +00002201QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002202 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002203 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002204 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002205 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002206 QualType FieldTypes[4];
2207
2208 // struct objc_object *receiver;
2209 FieldTypes[0] = Context->getObjCIdType();
2210 // int flags;
2211 FieldTypes[1] = Context->IntTy;
2212 // char *str;
2213 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2214 // long length;
2215 FieldTypes[3] = Context->LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002216
Steve Naroff47e7fa22008-03-15 00:55:56 +00002217 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002218 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002219 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002220 ConstantStringDecl,
2221 SourceLocation(), 0,
2222 FieldTypes[i],
2223 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002224 /*Mutable=*/true));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002225 }
2226
2227 ConstantStringDecl->completeDefinition(*Context);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002228 }
2229 return Context->getTagDeclType(ConstantStringDecl);
2230}
2231
Steve Naroff44e81222008-04-14 22:03:09 +00002232Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002233 if (!SelGetUidFunctionDecl)
2234 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002235 if (!MsgSendFunctionDecl)
2236 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002237 if (!MsgSendSuperFunctionDecl)
2238 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002239 if (!MsgSendStretFunctionDecl)
2240 SynthMsgSendStretFunctionDecl();
2241 if (!MsgSendSuperStretFunctionDecl)
2242 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002243 if (!MsgSendFpretFunctionDecl)
2244 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002245 if (!GetClassFunctionDecl)
2246 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002247 if (!GetMetaClassFunctionDecl)
2248 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002249
Steve Naroff764c1ae2007-11-15 10:28:18 +00002250 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002251 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2252 // May need to use objc_msgSend_stret() as well.
2253 FunctionDecl *MsgSendStretFlavor = 0;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002254 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2255 QualType resultType = OMD->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002256 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002257 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002258 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002259 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002260 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002261
Steve Naroff71226032007-10-24 22:48:43 +00002262 // Synthesize a call to objc_msgSend().
2263 llvm::SmallVector<Expr*, 8> MsgExprs;
2264 IdentifierInfo *clsName = Exp->getClassName();
2265
2266 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2267 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002268 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2269 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002270 if (!strcmp(clsName->getName(), "super")) {
2271 MsgSendFlavor = MsgSendSuperFunctionDecl;
2272 if (MsgSendStretFlavor)
2273 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2274 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2275
Ted Kremenek42730c52008-01-07 19:49:32 +00002276 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002277 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002278
2279 llvm::SmallVector<Expr*, 4> InitExprs;
2280
2281 // set the receiver to self, the first argument to all methods.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002282 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002283 CurMethodDef->getSelfDecl(),
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002284 Context->getObjCIdType(),
2285 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002286 llvm::SmallVector<Expr*, 8> ClsExprs;
2287 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002288 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002289 SuperDecl->getIdentifier()->getName(),
2290 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002291 false, argType, SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002292 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2293 &ClsExprs[0],
2294 ClsExprs.size());
2295 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002296 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002297 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002298 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002299 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002300 // struct objc_super
2301 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002302 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002303
Steve Naroffdee066b2008-03-11 18:14:26 +00002304 if (LangOpts.Microsoft) {
2305 SynthSuperContructorFunctionDecl();
2306 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002307 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffdee066b2008-03-11 18:14:26 +00002308 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002309 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2310 InitExprs.size(),
2311 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002312 // The code for super is a little tricky to prevent collision with
2313 // the structure definition in the header. The rewriter has it's own
2314 // internal definition (__rw_objc_super) that is uses. This is why
2315 // we need the cast below. For example:
2316 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2317 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002318 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002319 Context->getPointerType(SuperRep->getType()),
2320 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002321 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002322 SuperRep, Context->getPointerType(superType),
2323 SourceLocation(), SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002324 } else {
2325 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002326 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffdee066b2008-03-11 18:14:26 +00002327 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002328 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002329 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner71ca8c82008-10-26 23:43:26 +00002330 false);
Steve Naroff12673622008-12-23 20:11:22 +00002331 // struct objc_super *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002332 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002333 Context->getPointerType(SuperRep->getType()),
2334 SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002335 }
Steve Naroff12673622008-12-23 20:11:22 +00002336 MsgExprs.push_back(SuperRep);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002337 } else {
2338 llvm::SmallVector<Expr*, 8> ClsExprs;
2339 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002340 ClsExprs.push_back(StringLiteral::Create(*Context,
2341 clsName->getName(),
2342 clsName->getLength(),
2343 false, argType,
2344 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002345 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2346 &ClsExprs[0],
2347 ClsExprs.size());
2348 MsgExprs.push_back(Cls);
2349 }
Steve Naroff885e2122007-11-14 23:54:14 +00002350 } else { // instance message.
2351 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002352
Ted Kremenek42730c52008-01-07 19:49:32 +00002353 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002354 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002355 if (MsgSendStretFlavor)
2356 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002357 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2358
2359 llvm::SmallVector<Expr*, 4> InitExprs;
2360
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002361 InitExprs.push_back(
Ted Kremenek0c97e042009-02-07 01:47:29 +00002362 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2363 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002364 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002365 SourceLocation()),
2366 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002367 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002368
2369 llvm::SmallVector<Expr*, 8> ClsExprs;
2370 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002371 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002372 SuperDecl->getIdentifier()->getName(),
2373 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002374 false, argType, SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002375 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002376 &ClsExprs[0],
2377 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002378 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002379 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002380 // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002381 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002382 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002383 // struct objc_super
2384 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002385 Expr *SuperRep;
2386
2387 if (LangOpts.Microsoft) {
2388 SynthSuperContructorFunctionDecl();
2389 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002390 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffbec4bf52008-03-11 17:37:02 +00002391 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002392 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2393 InitExprs.size(),
2394 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002395 // The code for super is a little tricky to prevent collision with
2396 // the structure definition in the header. The rewriter has it's own
2397 // internal definition (__rw_objc_super) that is uses. This is why
2398 // we need the cast below. For example:
2399 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2400 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002401 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002402 Context->getPointerType(SuperRep->getType()),
2403 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002404 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002405 SuperRep, Context->getPointerType(superType),
2406 SourceLocation(), SourceLocation());
Steve Naroffbec4bf52008-03-11 17:37:02 +00002407 } else {
2408 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002409 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00002410 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002411 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002412 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002413 }
Steve Naroff12673622008-12-23 20:11:22 +00002414 MsgExprs.push_back(SuperRep);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002415 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002416 // Remove all type-casts because it may contain objc-style types; e.g.
2417 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002418 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002419 recExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002420 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002421 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002422 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002423 MsgExprs.push_back(recExpr);
2424 }
Steve Naroff885e2122007-11-14 23:54:14 +00002425 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002426 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002427 llvm::SmallVector<Expr*, 8> SelExprs;
2428 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002429 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002430 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00002431 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002432 false, argType, SourceLocation()));
Steve Naroff71226032007-10-24 22:48:43 +00002433 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2434 &SelExprs[0], SelExprs.size());
2435 MsgExprs.push_back(SelExp);
2436
2437 // Now push any user supplied arguments.
2438 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002439 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002440 // Make all implicit casts explicit...ICE comes in handy:-)
2441 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2442 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002443 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002444 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002445 : ICE->getType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002446 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002447 }
2448 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002449 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002450 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002451 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002452 userExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002453 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002454 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002455 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002456 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002457 }
Steve Naroff885e2122007-11-14 23:54:14 +00002458 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002459 // We've transferred the ownership to MsgExprs. Null out the argument in
2460 // the original expression, since we will delete it below.
2461 Exp->setArg(i, 0);
2462 }
Steve Naroff0744c472007-11-04 22:37:50 +00002463 // Generate the funky cast.
2464 CastExpr *cast;
2465 llvm::SmallVector<QualType, 8> ArgTypes;
2466 QualType returnType;
2467
2468 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002469 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2470 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2471 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002472 ArgTypes.push_back(Context->getObjCIdType());
2473 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002474 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002475 // Push any user argument types.
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002476 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2477 E = OMD->param_end(); PI != E; ++PI) {
2478 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002479 ? Context->getObjCIdType()
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002480 : (*PI)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002481 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00002482 if (isTopLevelBlockPointerType(t)) {
Steve Naroff66c842f2008-10-29 14:49:46 +00002483 const BlockPointerType *BPT = t->getAsBlockPointerType();
2484 t = Context->getPointerType(BPT->getPointeeType());
2485 }
Steve Naroff4242b972007-11-05 14:36:37 +00002486 ArgTypes.push_back(t);
2487 }
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002488 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2489 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002490 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002491 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002492 }
2493 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002494 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002495
2496 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002497 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002498 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002499
2500 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2501 // If we don't do this cast, we get the following bizarre warning/note:
2502 // xx.m:13: warning: function called through a non-compatible type
2503 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek0c97e042009-02-07 01:47:29 +00002504 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002505 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002506 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002507
Steve Naroff0744c472007-11-04 22:37:50 +00002508 // Now do the "normal" pointer to function cast.
2509 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002510 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002511 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002512 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002513 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002514 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002515
2516 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002517 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroff0744c472007-11-04 22:37:50 +00002518
2519 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002520 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2521 MsgExprs.size(),
2522 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002523 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002524 if (MsgSendStretFlavor) {
2525 // We have the method which returns a struct/union. Must also generate
2526 // call to objc_msgSend_stret and hang both varieties on a conditional
2527 // expression which dictate which one to envoke depending on size of
2528 // method's return type.
2529
2530 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002531 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002532 SourceLocation());
2533 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek0c97e042009-02-07 01:47:29 +00002534 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002535 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002536 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002537 // Now do the "normal" pointer to function cast.
2538 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002539 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002540 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002541 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002542 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002543
2544 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002545 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002546
2547 FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002548 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2549 MsgExprs.size(),
2550 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002551
2552 // Build sizeof(returnType)
Douglas Gregor396f1142009-03-13 21:01:28 +00002553 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2554 returnType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002555 Context->getSizeType(),
2556 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002557 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2558 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2559 // For X86 it is more complicated and some kind of target specific routine
2560 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002561 unsigned IntSize =
2562 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek0c97e042009-02-07 01:47:29 +00002563 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002564 Context->IntTy,
2565 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002566 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002567 BinaryOperator::LE,
2568 Context->IntTy,
2569 SourceLocation());
2570 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2571 ConditionalOperator *CondExpr =
Ted Kremenek0c97e042009-02-07 01:47:29 +00002572 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2573 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002574 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002575 return ReplacingStmt;
2576}
2577
Steve Naroff44e81222008-04-14 22:03:09 +00002578Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002579 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002580
Steve Naroff0e948412008-12-04 16:24:46 +00002581 //ReplacingStmt->dump();
Steve Naroff71226032007-10-24 22:48:43 +00002582 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002583 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002584
Steve Naroff102c3f22008-12-04 23:50:32 +00002585 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002586 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002587}
2588
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002589/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2590/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002591Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002592 if (!GetProtocolFunctionDecl)
2593 SynthGetProtocolFunctionDecl();
2594 // Create a call to objc_getProtocol("ProtocolName").
2595 llvm::SmallVector<Expr*, 8> ProtoExprs;
2596 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002597 ProtoExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002598 Exp->getProtocol()->getNameAsCString(),
2599 strlen(Exp->getProtocol()->getNameAsCString()),
Chris Lattnerc3144742009-02-18 05:49:11 +00002600 false, argType, SourceLocation()));
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002601 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2602 &ProtoExprs[0],
2603 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002604 ReplaceStmt(Exp, ProtoExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00002605 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002606 return ProtoExp;
2607
2608}
2609
Steve Naroffef82b742008-05-31 14:15:04 +00002610bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2611 const char *endBuf) {
2612 while (startBuf < endBuf) {
2613 if (*startBuf == '#') {
2614 // Skip whitespace.
2615 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2616 ;
2617 if (!strncmp(startBuf, "if", strlen("if")) ||
2618 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2619 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2620 !strncmp(startBuf, "define", strlen("define")) ||
2621 !strncmp(startBuf, "undef", strlen("undef")) ||
2622 !strncmp(startBuf, "else", strlen("else")) ||
2623 !strncmp(startBuf, "elif", strlen("elif")) ||
2624 !strncmp(startBuf, "endif", strlen("endif")) ||
2625 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2626 !strncmp(startBuf, "include", strlen("include")) ||
2627 !strncmp(startBuf, "import", strlen("import")) ||
2628 !strncmp(startBuf, "include_next", strlen("include_next")))
2629 return true;
2630 }
2631 startBuf++;
2632 }
2633 return false;
2634}
2635
Ted Kremenek42730c52008-01-07 19:49:32 +00002636/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002637/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002638void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002639 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002640 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002641 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002642 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002643 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002644 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002645 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002646 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002647 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002648 SourceLocation LocStart = CDecl->getLocStart();
2649 SourceLocation LocEnd = CDecl->getLocEnd();
2650
2651 const char *startBuf = SM->getCharacterData(LocStart);
2652 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002653
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002654 // If no ivars and no root or if its root, directly or indirectly,
2655 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002656 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2657 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002658 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002659 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002660 return;
2661 }
2662
2663 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002664 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002665 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002666 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002667 if (LangOpts.Microsoft)
2668 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002669
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002670 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002671 const char *cursor = strchr(startBuf, '{');
2672 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002673 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002674 // If the buffer contains preprocessor directives, we do more fine-grained
2675 // rewrites. This is intended to fix code that looks like (which occurs in
2676 // NSURL.h, for example):
2677 //
2678 // #ifdef XYZ
2679 // @interface Foo : NSObject
2680 // #else
2681 // @interface FooBar : NSObject
2682 // #endif
2683 // {
2684 // int i;
2685 // }
2686 // @end
2687 //
2688 // This clause is segregated to avoid breaking the common case.
2689 if (BufferContainsPPDirectives(startBuf, cursor)) {
2690 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2691 CDecl->getClassLoc();
2692 const char *endHeader = SM->getCharacterData(L);
2693 endHeader += Lexer::MeasureTokenLength(L, *SM);
2694
Chris Lattner179fd522009-02-20 18:18:36 +00002695 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002696 // advance to the end of the referenced protocols.
2697 while (endHeader < cursor && *endHeader != '>') endHeader++;
2698 endHeader++;
2699 }
2700 // rewrite the original header
2701 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2702 } else {
2703 // rewrite the original header *without* disturbing the '{'
2704 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2705 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002706 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002707 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002708 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002709 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002710 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002711 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002712
2713 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002714 SourceLocation OnePastCurly =
2715 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2716 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002717 }
2718 cursor++; // past '{'
2719
2720 // Now comment out any visibility specifiers.
2721 while (cursor < endBuf) {
2722 if (*cursor == '@') {
2723 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002724 // Skip whitespace.
2725 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2726 /*scan*/;
2727
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002728 // FIXME: presence of @public, etc. inside comment results in
2729 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002730 if (!strncmp(cursor, "public", strlen("public")) ||
2731 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002732 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002733 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002734 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002735 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002736 // FIXME: If there are cases where '<' is used in ivar declaration part
2737 // of user code, then scan the ivar list and use needToScanForQualifiers
2738 // for type checking.
2739 else if (*cursor == '<') {
2740 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002741 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002742 cursor = strchr(cursor, '>');
2743 cursor++;
2744 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002745 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002746 } else if (*cursor == '^') { // rewrite block specifier.
2747 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2748 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002749 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002750 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002751 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002752 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002753 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002754 } else { // we don't have any instance variables - insert super struct.
2755 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2756 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002757 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002758 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002759 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002760 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002761 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002762 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002763 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002764 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002765 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002766}
2767
Ted Kremenek42730c52008-01-07 19:49:32 +00002768// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002769/// class methods.
Steve Naroff44e81222008-04-14 22:03:09 +00002770void RewriteObjC::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002771 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002772 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002773 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002774 const char *ClassName,
2775 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002776 if (MethodBegin == MethodEnd) return;
2777
Fariborz Jahanian04455192007-10-22 21:41:37 +00002778 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002779 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002780 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002781 SEL _cmd;
2782 char *method_types;
2783 void *_imp;
2784 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002785 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002786 Result += "\nstruct _objc_method {\n";
2787 Result += "\tSEL _cmd;\n";
2788 Result += "\tchar *method_types;\n";
2789 Result += "\tvoid *_imp;\n";
2790 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002791
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002792 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002793 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002794
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002795 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002796
2797 /* struct {
2798 struct _objc_method_list *next_method;
2799 int method_count;
2800 struct _objc_method method_list[];
2801 }
2802 */
2803 Result += "\nstatic struct {\n";
2804 Result += "\tstruct _objc_method_list *next_method;\n";
2805 Result += "\tint method_count;\n";
2806 Result += "\tstruct _objc_method method_list[";
2807 Result += utostr(MethodEnd-MethodBegin);
2808 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002809 Result += prefix;
2810 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2811 Result += "_METHODS_";
2812 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002813 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002814 Result += IsInstanceMethod ? "inst" : "cls";
2815 Result += "_meth\")))= ";
2816 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002817
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002818 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002819 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002820 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002821 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002822 Result += "\", \"";
2823 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002824 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002825 Result += MethodInternalNames[*MethodBegin];
2826 Result += "}\n";
2827 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2828 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002829 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002830 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002831 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002832 Result += "\", \"";
2833 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002834 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002835 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002836 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002837 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002838 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002839}
2840
Ted Kremenek42730c52008-01-07 19:49:32 +00002841/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002842void RewriteObjC::
2843RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2844 const char *prefix,
2845 const char *ClassName,
2846 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002847 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002848 if (Protocols.empty()) return;
2849
2850 for (unsigned i = 0; i != Protocols.size(); i++) {
2851 ObjCProtocolDecl *PDecl = Protocols[i];
2852 // Output struct protocol_methods holder of method selector and type.
2853 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2854 /* struct protocol_methods {
2855 SEL _cmd;
2856 char *method_types;
2857 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002858 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002859 Result += "\nstruct protocol_methods {\n";
2860 Result += "\tSEL _cmd;\n";
2861 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002862 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002863
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002864 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002865 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002866 // Do not synthesize the protocol more than once.
2867 if (ObjCSynthesizedProtocols.count(PDecl))
2868 continue;
2869
2870 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Chris Lattner179fd522009-02-20 18:18:36 +00002871 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
2872 PDecl->instmeth_end());
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002873 /* struct _objc_protocol_method_list {
2874 int protocol_method_count;
2875 struct protocol_methods protocols[];
2876 }
2877 */
2878 Result += "\nstatic struct {\n";
2879 Result += "\tint protocol_method_count;\n";
2880 Result += "\tstruct protocol_methods protocols[";
2881 Result += utostr(NumMethods);
2882 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002883 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002884 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2885 "{\n\t" + utostr(NumMethods) + "\n";
2886
2887 // Output instance methods declared in this protocol.
2888 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
2889 E = PDecl->instmeth_end(); I != E; ++I) {
2890 if (I == PDecl->instmeth_begin())
2891 Result += "\t ,{{(SEL)\"";
2892 else
2893 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002894 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002895 std::string MethodTypeString;
2896 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2897 Result += "\", \"";
2898 Result += MethodTypeString;
2899 Result += "\"}\n";
2900 }
2901 Result += "\t }\n};\n";
2902 }
2903
2904 // Output class methods declared in this protocol.
Chris Lattner179fd522009-02-20 18:18:36 +00002905 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
2906 PDecl->classmeth_end());
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002907 if (NumMethods > 0) {
2908 /* struct _objc_protocol_method_list {
2909 int protocol_method_count;
2910 struct protocol_methods protocols[];
2911 }
2912 */
2913 Result += "\nstatic struct {\n";
2914 Result += "\tint protocol_method_count;\n";
2915 Result += "\tstruct protocol_methods protocols[";
2916 Result += utostr(NumMethods);
2917 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002918 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002919 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2920 "{\n\t";
2921 Result += utostr(NumMethods);
2922 Result += "\n";
2923
2924 // Output instance methods declared in this protocol.
2925 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
2926 E = PDecl->classmeth_end(); I != E; ++I) {
2927 if (I == PDecl->classmeth_begin())
2928 Result += "\t ,{{(SEL)\"";
2929 else
2930 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002931 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002932 std::string MethodTypeString;
2933 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2934 Result += "\", \"";
2935 Result += MethodTypeString;
2936 Result += "\"}\n";
2937 }
2938 Result += "\t }\n};\n";
2939 }
2940
2941 // Output:
2942 /* struct _objc_protocol {
2943 // Objective-C 1.0 extensions
2944 struct _objc_protocol_extension *isa;
2945 char *protocol_name;
2946 struct _objc_protocol **protocol_list;
2947 struct _objc_protocol_method_list *instance_methods;
2948 struct _objc_protocol_method_list *class_methods;
2949 };
Steve Naroff27429432008-03-12 01:06:30 +00002950 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002951 static bool objc_protocol = false;
2952 if (!objc_protocol) {
2953 Result += "\nstruct _objc_protocol {\n";
2954 Result += "\tstruct _objc_protocol_extension *isa;\n";
2955 Result += "\tchar *protocol_name;\n";
2956 Result += "\tstruct _objc_protocol **protocol_list;\n";
2957 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2958 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2959 Result += "};\n";
2960
2961 objc_protocol = true;
2962 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002963
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002964 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002965 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002966 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2967 "{\n\t0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002968 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002969 Result += "\", 0, ";
2970 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
2971 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002972 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002973 Result += ", ";
2974 }
2975 else
2976 Result += "0, ";
Chris Lattner179fd522009-02-20 18:18:36 +00002977 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002978 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002979 Result += PDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002980 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002981 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002982 else
2983 Result += "0\n";
2984 Result += "};\n";
2985
2986 // Mark this protocol as having been generated.
2987 if (!ObjCSynthesizedProtocols.insert(PDecl))
2988 assert(false && "protocol already synthesized");
2989 }
2990 // Output the top lovel protocol meta-data for the class.
2991 /* struct _objc_protocol_list {
2992 struct _objc_protocol_list *next;
2993 int protocol_count;
2994 struct _objc_protocol *class_protocols[];
2995 }
2996 */
2997 Result += "\nstatic struct {\n";
2998 Result += "\tstruct _objc_protocol_list *next;\n";
2999 Result += "\tint protocol_count;\n";
3000 Result += "\tstruct _objc_protocol *class_protocols[";
3001 Result += utostr(Protocols.size());
3002 Result += "];\n} _OBJC_";
3003 Result += prefix;
3004 Result += "_PROTOCOLS_";
3005 Result += ClassName;
3006 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3007 "{\n\t0, ";
3008 Result += utostr(Protocols.size());
3009 Result += "\n";
3010
3011 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003012 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003013 Result += " \n";
3014
3015 for (unsigned i = 1; i != Protocols.size(); i++) {
3016 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003017 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003018 Result += "\n";
3019 }
3020 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003021}
3022
Ted Kremenek42730c52008-01-07 19:49:32 +00003023/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003024/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00003025void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003026 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003027 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003028 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003029 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003030 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3031 CDecl = CDecl->getNextClassCategory())
3032 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3033 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003034
Chris Lattner271d4c22008-11-24 05:29:24 +00003035 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003036 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00003037 FullCategoryName += IDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003038
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003039 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003040 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003041 true, "CATEGORY_", FullCategoryName.c_str(),
3042 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003043
3044 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003045 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003046 false, "CATEGORY_", FullCategoryName.c_str(),
3047 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003048
3049 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00003050 // Null CDecl is case of a category implementation with no category interface
3051 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00003052 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00003053 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003054
3055 /* struct _objc_category {
3056 char *category_name;
3057 char *class_name;
3058 struct _objc_method_list *instance_methods;
3059 struct _objc_method_list *class_methods;
3060 struct _objc_protocol_list *protocols;
3061 // Objective-C 1.0 extensions
3062 uint32_t size; // sizeof (struct _objc_category)
3063 struct _objc_property_list *instance_properties; // category's own
3064 // @property decl.
3065 };
3066 */
3067
3068 static bool objc_category = false;
3069 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003070 Result += "\nstruct _objc_category {\n";
3071 Result += "\tchar *category_name;\n";
3072 Result += "\tchar *class_name;\n";
3073 Result += "\tstruct _objc_method_list *instance_methods;\n";
3074 Result += "\tstruct _objc_method_list *class_methods;\n";
3075 Result += "\tstruct _objc_protocol_list *protocols;\n";
3076 Result += "\tunsigned int size;\n";
3077 Result += "\tstruct _objc_property_list *instance_properties;\n";
3078 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003079 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00003080 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003081 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3082 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00003083 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003084 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003085 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003086 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003087 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003088
Chris Lattner179fd522009-02-20 18:18:36 +00003089 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003090 Result += "\t, (struct _objc_method_list *)"
3091 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3092 Result += FullCategoryName;
3093 Result += "\n";
3094 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003095 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003096 Result += "\t, 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003097 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003098 Result += "\t, (struct _objc_method_list *)"
3099 "&_OBJC_CATEGORY_CLASS_METHODS_";
3100 Result += FullCategoryName;
3101 Result += "\n";
3102 }
3103 else
3104 Result += "\t, 0\n";
3105
Chris Lattner179fd522009-02-20 18:18:36 +00003106 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003107 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3108 Result += FullCategoryName;
3109 Result += "\n";
3110 }
3111 else
3112 Result += "\t, 0\n";
3113 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003114}
3115
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003116/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3117/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00003118void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00003119 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003120 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00003121 if (ivar->isBitField()) {
3122 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3123 // place all bitfields at offset 0.
3124 Result += "0";
3125 } else {
3126 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003127 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003128 if (LangOpts.Microsoft)
3129 Result += "_IMPL";
3130 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003131 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003132 Result += ")";
3133 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003134}
3135
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003136//===----------------------------------------------------------------------===//
3137// Meta Data Emission
3138//===----------------------------------------------------------------------===//
3139
Steve Naroff44e81222008-04-14 22:03:09 +00003140void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003141 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003142 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003143
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003144 // Explictly declared @interface's are already synthesized.
3145 if (CDecl->ImplicitInterfaceDecl()) {
3146 // FIXME: Implementation of a class with no @interface (legacy) doese not
3147 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00003148 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003149 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003150
Chris Lattnerc7b06752007-12-12 07:56:42 +00003151 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00003152 unsigned NumIvars = !IDecl->ivar_empty()
3153 ? IDecl->ivar_size()
3154 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003155 if (NumIvars > 0) {
3156 static bool objc_ivar = false;
3157 if (!objc_ivar) {
3158 /* struct _objc_ivar {
3159 char *ivar_name;
3160 char *ivar_type;
3161 int ivar_offset;
3162 };
3163 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003164 Result += "\nstruct _objc_ivar {\n";
3165 Result += "\tchar *ivar_name;\n";
3166 Result += "\tchar *ivar_type;\n";
3167 Result += "\tint ivar_offset;\n";
3168 Result += "};\n";
3169
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003170 objc_ivar = true;
3171 }
3172
Steve Naroffc723eec2008-03-11 00:12:29 +00003173 /* struct {
3174 int ivar_count;
3175 struct _objc_ivar ivar_list[nIvars];
3176 };
3177 */
3178 Result += "\nstatic struct {\n";
3179 Result += "\tint ivar_count;\n";
3180 Result += "\tstruct _objc_ivar ivar_list[";
3181 Result += utostr(NumIvars);
3182 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003183 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003184 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003185 "{\n\t";
3186 Result += utostr(NumIvars);
3187 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003188
Ted Kremenek42730c52008-01-07 19:49:32 +00003189 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00003190 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00003191 IVI = IDecl->ivar_begin();
3192 IVE = IDecl->ivar_end();
3193 } else {
3194 IVI = CDecl->ivar_begin();
3195 IVE = CDecl->ivar_end();
3196 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003197 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003198 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003199 Result += "\", \"";
3200 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003201 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003202 Result += StrEncoding;
3203 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003204 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003205 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003206 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003207 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003208 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003209 Result += "\", \"";
3210 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003211 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003212 Result += StrEncoding;
3213 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003214 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003215 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003216 }
3217
3218 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003219 }
3220
3221 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003222 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003223 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003224
3225 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00003226 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003227 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003228
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003229 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00003230 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003231 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003232
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003233
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003234 // Declaration of class/meta-class metadata
3235 /* struct _objc_class {
3236 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003237 const char *super_class_name;
3238 char *name;
3239 long version;
3240 long info;
3241 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003242 struct _objc_ivar_list *ivars;
3243 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003244 struct objc_cache *cache;
3245 struct objc_protocol_list *protocols;
3246 const char *ivar_layout;
3247 struct _objc_class_ext *ext;
3248 };
3249 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003250 static bool objc_class = false;
3251 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003252 Result += "\nstruct _objc_class {\n";
3253 Result += "\tstruct _objc_class *isa;\n";
3254 Result += "\tconst char *super_class_name;\n";
3255 Result += "\tchar *name;\n";
3256 Result += "\tlong version;\n";
3257 Result += "\tlong info;\n";
3258 Result += "\tlong instance_size;\n";
3259 Result += "\tstruct _objc_ivar_list *ivars;\n";
3260 Result += "\tstruct _objc_method_list *methods;\n";
3261 Result += "\tstruct objc_cache *cache;\n";
3262 Result += "\tstruct _objc_protocol_list *protocols;\n";
3263 Result += "\tconst char *ivar_layout;\n";
3264 Result += "\tstruct _objc_class_ext *ext;\n";
3265 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003266 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003267 }
3268
3269 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003270 ObjCInterfaceDecl *RootClass = 0;
3271 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003272 while (SuperClass) {
3273 RootClass = SuperClass;
3274 SuperClass = SuperClass->getSuperClass();
3275 }
3276 SuperClass = CDecl->getSuperClass();
3277
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003278 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003279 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003280 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003281 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003282 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003283 Result += "\"";
3284
3285 if (SuperClass) {
3286 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003287 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003288 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003289 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003290 Result += "\"";
3291 }
3292 else {
3293 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003294 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003295 Result += "\"";
3296 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003297 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003298 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003299 Result += ", 0,2, sizeof(struct _objc_class), 0";
Chris Lattner5c6b2c62009-02-20 18:43:26 +00003300 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003301 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003302 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003303 Result += "\n";
3304 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003305 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003306 Result += ", 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003307 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003308 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003309 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003310 Result += ",0,0\n";
3311 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003312 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003313 Result += "\t,0,0,0,0\n";
3314 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003315
3316 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003317 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003318 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003319 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003320 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003321 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003322 if (SuperClass) {
3323 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003324 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003325 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003326 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003327 Result += "\"";
3328 }
3329 else {
3330 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003331 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003332 Result += "\"";
3333 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003334 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003335 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003336 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003337 Result += ",0";
3338 else {
3339 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003340 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003341 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003342 if (LangOpts.Microsoft)
3343 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003344 Result += ")";
3345 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003346 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003347 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003348 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003349 Result += "\n\t";
3350 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003351 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003352 Result += ",0";
Chris Lattner5c6b2c62009-02-20 18:43:26 +00003353 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003354 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003355 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003356 Result += ", 0\n\t";
3357 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003358 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003359 Result += ",0,0";
Chris Lattner179fd522009-02-20 18:18:36 +00003360 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003361 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003362 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003363 Result += ", 0,0\n";
3364 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003365 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003366 Result += ",0,0,0\n";
3367 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003368}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003369
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003370/// RewriteImplementations - This routine rewrites all method implementations
3371/// and emits meta-data.
3372
Steve Naroff21658f62008-11-13 20:07:04 +00003373void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003374 int ClsDefCount = ClassImplementation.size();
3375 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003376
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003377 // Rewrite implemented methods
3378 for (int i = 0; i < ClsDefCount; i++)
3379 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003380
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003381 for (int i = 0; i < CatDefCount; i++)
3382 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003383}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003384
Steve Naroff21658f62008-11-13 20:07:04 +00003385void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3386 int ClsDefCount = ClassImplementation.size();
3387 int CatDefCount = CategoryImplementation.size();
3388
Steve Naroff5bf10222008-05-07 21:23:49 +00003389 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003390 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003391 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003392 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003393 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003394
3395 // For each implemented category, write out all its meta data.
3396 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003397 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003398
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003399 // Write objc_symtab metadata
3400 /*
3401 struct _objc_symtab
3402 {
3403 long sel_ref_cnt;
3404 SEL *refs;
3405 short cls_def_cnt;
3406 short cat_def_cnt;
3407 void *defs[cls_def_cnt + cat_def_cnt];
3408 };
3409 */
3410
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003411 Result += "\nstruct _objc_symtab {\n";
3412 Result += "\tlong sel_ref_cnt;\n";
3413 Result += "\tSEL *refs;\n";
3414 Result += "\tshort cls_def_cnt;\n";
3415 Result += "\tshort cat_def_cnt;\n";
3416 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3417 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003418
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003419 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003420 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003421 Result += "\t0, 0, " + utostr(ClsDefCount)
3422 + ", " + utostr(CatDefCount) + "\n";
3423 for (int i = 0; i < ClsDefCount; i++) {
3424 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003425 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003426 Result += "\n";
3427 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003428
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003429 for (int i = 0; i < CatDefCount; i++) {
3430 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003431 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003432 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003433 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003434 Result += "\n";
3435 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003436
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003437 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003438
3439 // Write objc_module metadata
3440
3441 /*
3442 struct _objc_module {
3443 long version;
3444 long size;
3445 const char *name;
3446 struct _objc_symtab *symtab;
3447 }
3448 */
3449
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003450 Result += "\nstruct _objc_module {\n";
3451 Result += "\tlong version;\n";
3452 Result += "\tlong size;\n";
3453 Result += "\tconst char *name;\n";
3454 Result += "\tstruct _objc_symtab *symtab;\n";
3455 Result += "};\n\n";
3456 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003457 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003458 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3459 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003460 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003461
3462 if (LangOpts.Microsoft) {
3463 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003464 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003465 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3466 Result += "&_OBJC_MODULES;\n";
3467 Result += "#pragma data_seg(pop)\n\n";
3468 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003469}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003470
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003471std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3472 const char *funcName,
3473 std::string Tag) {
3474 const FunctionType *AFT = CE->getFunctionType();
3475 QualType RT = AFT->getResultType();
3476 std::string StructRef = "struct " + Tag;
3477 std::string S = "static " + RT.getAsString() + " __" +
3478 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003479
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003480 BlockDecl *BD = CE->getBlockDecl();
3481
Douglas Gregor4fa58902009-02-26 23:50:07 +00003482 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff16478cf2009-02-02 17:19:26 +00003483 // No user-supplied arguments. Still need to pass in a pointer to the
3484 // block (to reference imported block decl refs).
3485 S += "(" + StructRef + " *__cself)";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003486 } else if (BD->param_empty()) {
3487 S += "(" + StructRef + " *__cself)";
3488 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003489 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003490 assert(FT && "SynthesizeBlockFunc: No function proto");
3491 S += '(';
3492 // first add the implicit argument.
3493 S += StructRef + " *__cself, ";
3494 std::string ParamStr;
3495 for (BlockDecl::param_iterator AI = BD->param_begin(),
3496 E = BD->param_end(); AI != E; ++AI) {
3497 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003498 ParamStr = (*AI)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003499 (*AI)->getType().getAsStringInternal(ParamStr);
3500 S += ParamStr;
3501 }
3502 if (FT->isVariadic()) {
3503 if (!BD->param_empty()) S += ", ";
3504 S += "...";
3505 }
3506 S += ')';
3507 }
3508 S += " {\n";
3509
3510 // Create local declarations to avoid rewriting all closure decl ref exprs.
3511 // First, emit a declaration for all "by ref" decls.
3512 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3513 E = BlockByRefDecls.end(); I != E; ++I) {
3514 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003515 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003516 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003517 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003518 }
3519 // Next, emit a declaration for all "by copy" declarations.
3520 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3521 E = BlockByCopyDecls.end(); I != E; ++I) {
3522 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003523 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003524 // Handle nested closure invocation. For example:
3525 //
3526 // void (^myImportedClosure)(void);
3527 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3528 //
3529 // void (^anotherClosure)(void);
3530 // anotherClosure = ^(void) {
3531 // myImportedClosure(); // import and invoke the closure
3532 // };
3533 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003534 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003535 S += "struct __block_impl *";
3536 else
3537 (*I)->getType().getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003538 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003539 }
3540 std::string RewrittenStr = RewrittenBlockExprs[CE];
3541 const char *cstr = RewrittenStr.c_str();
3542 while (*cstr++ != '{') ;
3543 S += cstr;
3544 S += "\n";
3545 return S;
3546}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003547
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003548std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3549 const char *funcName,
3550 std::string Tag) {
3551 std::string StructRef = "struct " + Tag;
3552 std::string S = "static void __";
3553
3554 S += funcName;
3555 S += "_block_copy_" + utostr(i);
3556 S += "(" + StructRef;
3557 S += "*dst, " + StructRef;
3558 S += "*src) {";
3559 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3560 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003561 S += "_Block_object_assign((void*)&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003562 S += (*I)->getNameAsString();
Steve Naroff1d56d9e2008-12-11 20:51:38 +00003563 S += ", (void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003564 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003565 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003566 }
3567 S += "\nstatic void __";
3568 S += funcName;
3569 S += "_block_dispose_" + utostr(i);
3570 S += "(" + StructRef;
3571 S += "*src) {";
3572 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3573 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003574 S += "_Block_object_dispose((void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003575 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003576 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003577 }
3578 S += "}\n";
3579 return S;
3580}
3581
3582std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3583 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003584 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003585 std::string Constructor = " " + Tag;
3586
3587 S += " {\n struct __block_impl impl;\n";
3588
3589 if (hasCopyDisposeHelpers)
3590 S += " void *copy;\n void *dispose;\n";
3591
3592 Constructor += "(void *fp";
3593
3594 if (hasCopyDisposeHelpers)
3595 Constructor += ", void *copyHelp, void *disposeHelp";
3596
3597 if (BlockDeclRefs.size()) {
3598 // Output all "by copy" declarations.
3599 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3600 E = BlockByCopyDecls.end(); I != E; ++I) {
3601 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003602 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003603 std::string ArgName = "_" + FieldName;
3604 // Handle nested closure invocation. For example:
3605 //
3606 // void (^myImportedBlock)(void);
3607 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3608 //
3609 // void (^anotherBlock)(void);
3610 // anotherBlock = ^(void) {
3611 // myImportedBlock(); // import and invoke the closure
3612 // };
3613 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003614 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003615 S += "struct __block_impl *";
3616 Constructor += ", void *" + ArgName;
3617 } else {
3618 (*I)->getType().getAsStringInternal(FieldName);
3619 (*I)->getType().getAsStringInternal(ArgName);
3620 Constructor += ", " + ArgName;
3621 }
3622 S += FieldName + ";\n";
3623 }
3624 // Output all "by ref" declarations.
3625 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3626 E = BlockByRefDecls.end(); I != E; ++I) {
3627 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003628 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003629 std::string ArgName = "_" + FieldName;
3630 // Handle nested closure invocation. For example:
3631 //
3632 // void (^myImportedBlock)(void);
3633 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3634 //
3635 // void (^anotherBlock)(void);
3636 // anotherBlock = ^(void) {
3637 // myImportedBlock(); // import and invoke the closure
3638 // };
3639 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003640 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003641 S += "struct __block_impl *";
3642 Constructor += ", void *" + ArgName;
3643 } else {
3644 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3645 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3646 Constructor += ", " + ArgName;
3647 }
3648 S += FieldName + "; // by ref\n";
3649 }
3650 // Finish writing the constructor.
3651 // FIXME: handle NSConcreteGlobalBlock.
3652 Constructor += ", int flags=0) {\n";
3653 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3654 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3655
3656 if (hasCopyDisposeHelpers)
3657 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3658
3659 // Initialize all "by copy" arguments.
3660 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3661 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003662 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003663 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003664 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003665 Constructor += Name + " = (struct __block_impl *)_";
3666 else
3667 Constructor += Name + " = _";
3668 Constructor += Name + ";\n";
3669 }
3670 // Initialize all "by ref" arguments.
3671 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3672 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003673 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003674 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003675 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003676 Constructor += Name + " = (struct __block_impl *)_";
3677 else
3678 Constructor += Name + " = _";
3679 Constructor += Name + ";\n";
3680 }
3681 } else {
3682 // Finish writing the constructor.
3683 // FIXME: handle NSConcreteGlobalBlock.
3684 Constructor += ", int flags=0) {\n";
3685 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3686 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3687 if (hasCopyDisposeHelpers)
3688 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3689 }
3690 Constructor += " ";
3691 Constructor += "}\n";
3692 S += Constructor;
3693 S += "};\n";
3694 return S;
3695}
3696
3697void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3698 const char *FunName) {
3699 // Insert closures that were part of the function.
3700 for (unsigned i = 0; i < Blocks.size(); i++) {
3701
3702 CollectBlockDeclRefInfo(Blocks[i]);
3703
3704 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3705
3706 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3707 ImportedBlockDecls.size() > 0);
3708
3709 InsertText(FunLocStart, CI.c_str(), CI.size());
3710
3711 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3712
3713 InsertText(FunLocStart, CF.c_str(), CF.size());
3714
3715 if (ImportedBlockDecls.size()) {
3716 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3717 InsertText(FunLocStart, HF.c_str(), HF.size());
3718 }
3719
3720 BlockDeclRefs.clear();
3721 BlockByRefDecls.clear();
3722 BlockByCopyDecls.clear();
3723 BlockCallExprs.clear();
3724 ImportedBlockDecls.clear();
3725 }
3726 Blocks.clear();
3727 RewrittenBlockExprs.clear();
3728}
3729
3730void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3731 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003732 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003733
3734 SynthesizeBlockLiterals(FunLocStart, FuncName);
3735}
3736
3737void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003738 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3739 //SourceLocation FunLocStart = MD->getLocStart();
3740 // FIXME: This hack works around a bug in Rewrite.InsertText().
3741 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003742 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003743 // Convert colons to underscores.
3744 std::string::size_type loc = 0;
3745 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3746 FuncName.replace(loc, 1, "_");
3747
3748 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3749}
3750
3751void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3752 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3753 CI != E; ++CI)
3754 if (*CI) {
3755 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3756 GetBlockDeclRefExprs(CBE->getBody());
3757 else
3758 GetBlockDeclRefExprs(*CI);
3759 }
3760 // Handle specific things.
3761 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3762 // FIXME: Handle enums.
3763 if (!isa<FunctionDecl>(CDRE->getDecl()))
3764 BlockDeclRefs.push_back(CDRE);
3765 return;
3766}
3767
3768void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3769 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3770 CI != E; ++CI)
3771 if (*CI) {
3772 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3773 GetBlockCallExprs(CBE->getBody());
3774 else
3775 GetBlockCallExprs(*CI);
3776 }
3777
3778 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3779 if (CE->getCallee()->getType()->isBlockPointerType()) {
3780 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3781 }
3782 }
3783 return;
3784}
3785
Steve Naroff85eb17b2008-10-30 10:07:53 +00003786Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003787 // Navigate to relevant type information.
3788 const char *closureName = 0;
3789 const BlockPointerType *CPT = 0;
3790
3791 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003792 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003793 CPT = DRE->getType()->getAsBlockPointerType();
3794 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003795 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003796 CPT = CDRE->getType()->getAsBlockPointerType();
3797 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003798 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003799 CPT = MExpr->getType()->getAsBlockPointerType();
3800 } else {
3801 assert(1 && "RewriteBlockClass: Bad type");
3802 }
3803 assert(CPT && "RewriteBlockClass: Bad type");
3804 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3805 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003806 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003807 // FTP will be null for closures that don't take arguments.
3808
Steve Naroff85eb17b2008-10-30 10:07:53 +00003809 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3810 SourceLocation(),
3811 &Context->Idents.get("__block_impl"));
3812 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003813
Steve Naroff85eb17b2008-10-30 10:07:53 +00003814 // Generate a funky cast.
3815 llvm::SmallVector<QualType, 8> ArgTypes;
3816
3817 // Push the block argument type.
3818 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003819 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003820 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003821 E = FTP->arg_type_end(); I && (I != E); ++I) {
3822 QualType t = *I;
3823 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00003824 if (isTopLevelBlockPointerType(t)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003825 const BlockPointerType *BPT = t->getAsBlockPointerType();
3826 t = Context->getPointerType(BPT->getPointeeType());
3827 }
3828 ArgTypes.push_back(t);
3829 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003830 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003831 // Now do the pointer to function cast.
3832 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3833 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3834
3835 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003836
Ted Kremenek0c97e042009-02-07 01:47:29 +00003837 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3838 PtrBlock, SourceLocation(),
3839 SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003840 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003841 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3842 BlkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003843 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003844
Douglas Gregor8acb7272008-12-11 16:49:14 +00003845 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3846 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003847 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek0c97e042009-02-07 01:47:29 +00003848 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3849 FD->getType());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003850
Ted Kremenek0c97e042009-02-07 01:47:29 +00003851 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3852 PtrToFuncCastType,
3853 SourceLocation(),
3854 SourceLocation());
3855 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003856
3857 llvm::SmallVector<Expr*, 8> BlkExprs;
3858 // Add the implicit argument.
3859 BlkExprs.push_back(BlkCast);
3860 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003861 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3862 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003863 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003864 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00003865 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3866 BlkExprs.size(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003867 Exp->getType(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003868 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003869}
3870
3871void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003872 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3873 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003874}
3875
3876void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3877 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003878 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroff16478cf2009-02-02 17:19:26 +00003879 Context->getPointerType(BDRE->getType()),
3880 SourceLocation());
3881 // Need parens to enforce precedence.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003882 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroff16478cf2009-02-02 17:19:26 +00003883 ReplaceStmt(BDRE, PE);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003884}
3885
Steve Naroff7f1412d2008-11-03 23:29:32 +00003886void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3887 SourceLocation LocStart = CE->getLParenLoc();
3888 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003889
3890 // Need to avoid trying to rewrite synthesized casts.
3891 if (LocStart.isInvalid())
3892 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00003893 // Need to avoid trying to rewrite casts contained in macros.
3894 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3895 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003896
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003897 const char *startBuf = SM->getCharacterData(LocStart);
3898 const char *endBuf = SM->getCharacterData(LocEnd);
3899
3900 // advance the location to startArgList.
3901 const char *argPtr = startBuf;
3902
3903 while (*argPtr++ && (argPtr < endBuf)) {
3904 switch (*argPtr) {
3905 case '^':
3906 // Replace the '^' with '*'.
3907 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3908 ReplaceText(LocStart, 1, "*", 1);
3909 break;
3910 }
3911 }
3912 return;
3913}
3914
3915void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3916 SourceLocation DeclLoc = FD->getLocation();
3917 unsigned parenCount = 0;
3918
3919 // We have 1 or more arguments that have closure pointers.
3920 const char *startBuf = SM->getCharacterData(DeclLoc);
3921 const char *startArgList = strchr(startBuf, '(');
3922
3923 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3924
3925 parenCount++;
3926 // advance the location to startArgList.
3927 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3928 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3929
3930 const char *argPtr = startArgList;
3931
3932 while (*argPtr++ && parenCount) {
3933 switch (*argPtr) {
3934 case '^':
3935 // Replace the '^' with '*'.
3936 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3937 ReplaceText(DeclLoc, 1, "*", 1);
3938 break;
3939 case '(':
3940 parenCount++;
3941 break;
3942 case ')':
3943 parenCount--;
3944 break;
3945 }
3946 }
3947 return;
3948}
3949
3950bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003951 const FunctionProtoType *FTP;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003952 const PointerType *PT = QT->getAsPointerType();
3953 if (PT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003954 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003955 } else {
3956 const BlockPointerType *BPT = QT->getAsBlockPointerType();
3957 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003958 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003959 }
3960 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003961 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003962 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +00003963 if (isTopLevelBlockPointerType(*I))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003964 return true;
3965 }
3966 return false;
3967}
3968
Ted Kremenek0c97e042009-02-07 01:47:29 +00003969void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
3970 const char *&RParen) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003971 const char *argPtr = strchr(Name, '(');
3972 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
3973
3974 LParen = argPtr; // output the start.
3975 argPtr++; // skip past the left paren.
3976 unsigned parenCount = 1;
3977
3978 while (*argPtr && parenCount) {
3979 switch (*argPtr) {
3980 case '(': parenCount++; break;
3981 case ')': parenCount--; break;
3982 default: break;
3983 }
3984 if (parenCount) argPtr++;
3985 }
3986 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
3987 RParen = argPtr; // output the end
3988}
3989
3990void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
3991 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3992 RewriteBlockPointerFunctionArgs(FD);
3993 return;
3994 }
3995 // Handle Variables and Typedefs.
3996 SourceLocation DeclLoc = ND->getLocation();
3997 QualType DeclT;
3998 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3999 DeclT = VD->getType();
4000 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4001 DeclT = TDD->getUnderlyingType();
4002 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4003 DeclT = FD->getType();
4004 else
4005 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4006
4007 const char *startBuf = SM->getCharacterData(DeclLoc);
4008 const char *endBuf = startBuf;
4009 // scan backward (from the decl location) for the end of the previous decl.
4010 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4011 startBuf--;
4012
4013 // *startBuf != '^' if we are dealing with a pointer to function that
4014 // may take block argument types (which will be handled below).
4015 if (*startBuf == '^') {
4016 // Replace the '^' with '*', computing a negative offset.
4017 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4018 ReplaceText(DeclLoc, 1, "*", 1);
4019 }
4020 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4021 // Replace the '^' with '*' for arguments.
4022 DeclLoc = ND->getLocation();
4023 startBuf = SM->getCharacterData(DeclLoc);
4024 const char *argListBegin, *argListEnd;
4025 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4026 while (argListBegin < argListEnd) {
4027 if (*argListBegin == '^') {
4028 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4029 ReplaceText(CaretLoc, 1, "*", 1);
4030 }
4031 argListBegin++;
4032 }
4033 }
4034 return;
4035}
4036
4037void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4038 // Add initializers for any closure decl refs.
4039 GetBlockDeclRefExprs(Exp->getBody());
4040 if (BlockDeclRefs.size()) {
4041 // Unique all "by copy" declarations.
4042 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4043 if (!BlockDeclRefs[i]->isByRef())
4044 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4045 // Unique all "by ref" declarations.
4046 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4047 if (BlockDeclRefs[i]->isByRef()) {
4048 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4049 }
4050 // Find any imported blocks...they will need special attention.
4051 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff1d56d9e2008-12-11 20:51:38 +00004052 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00004053 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004054 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4055 }
4056 }
4057}
4058
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004059FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4060 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004061 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004062 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor1f88aa72009-02-25 16:33:18 +00004063 ID, FType, FunctionDecl::Extern, false,
4064 false);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004065}
4066
Steve Naroff80c54752008-10-29 18:15:37 +00004067Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004068 Blocks.push_back(Exp);
4069
4070 CollectBlockDeclRefInfo(Exp);
4071 std::string FuncName;
4072
4073 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00004074 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004075 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00004076 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004077 // Convert colons to underscores.
4078 std::string::size_type loc = 0;
4079 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4080 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00004081 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00004082 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004083
4084 std::string BlockNumber = utostr(Blocks.size()-1);
4085
4086 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4087 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4088
4089 // Get a pointer to the function type so we can cast appropriately.
4090 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4091
4092 FunctionDecl *FD;
4093 Expr *NewRep;
4094
4095 // Simulate a contructor call...
4096 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004097 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004098
4099 llvm::SmallVector<Expr*, 4> InitExprs;
4100
Steve Naroffd0419d62008-10-29 21:23:59 +00004101 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004102 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004103 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4104 SourceLocation());
4105 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4106 Context->VoidPtrTy, SourceLocation(),
4107 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004108 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004109
4110 if (ImportedBlockDecls.size()) {
4111 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004112 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004113 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4114 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4115 Context->VoidPtrTy, SourceLocation(),
4116 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004117 InitExprs.push_back(castExpr);
4118
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004119 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004120 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004121 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4122 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4123 Context->VoidPtrTy, SourceLocation(),
4124 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004125 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004126 }
4127 // Add initializers for any closure decl refs.
4128 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004129 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004130 // Output all "by copy" declarations.
4131 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4132 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004133 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004134 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004135 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004136 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffd896f4b2008-12-11 21:05:33 +00004137 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004138 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004139 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4140 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4141 Context->VoidPtrTy, SourceLocation(),
4142 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004143 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004144 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004145 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004146 }
Steve Naroffd0419d62008-10-29 21:23:59 +00004147 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004148 }
4149 // Output all "by ref" declarations.
4150 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4151 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004152 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004153 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4154 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Naroffd0419d62008-10-29 21:23:59 +00004155 Context->getPointerType(Exp->getType()),
4156 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00004157 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004158 }
4159 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00004160 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4161 FType, SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004162 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004163 Context->getPointerType(NewRep->getType()),
4164 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004165 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4166 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004167 BlockDeclRefs.clear();
4168 BlockByRefDecls.clear();
4169 BlockByCopyDecls.clear();
4170 ImportedBlockDecls.clear();
4171 return NewRep;
4172}
4173
4174//===----------------------------------------------------------------------===//
4175// Function Body / Expression rewriting
4176//===----------------------------------------------------------------------===//
4177
Steve Naroff0e948412008-12-04 16:24:46 +00004178// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4179// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4180// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4181// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4182// Since the rewriter isn't capable of rewriting rewritten code, it's important
4183// we get this right.
4184void RewriteObjC::CollectPropertySetters(Stmt *S) {
4185 // Perform a bottom up traversal of all children.
4186 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4187 CI != E; ++CI)
4188 if (*CI)
4189 CollectPropertySetters(*CI);
4190
4191 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4192 if (BinOp->isAssignmentOp()) {
4193 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4194 PropSetters[PRE] = BinOp;
4195 }
4196 }
4197}
4198
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004199Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4200 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4201 isa<DoStmt>(S) || isa<ForStmt>(S))
4202 Stmts.push_back(S);
4203 else if (isa<ObjCForCollectionStmt>(S)) {
4204 Stmts.push_back(S);
4205 ObjCBcLabelNo.push_back(++BcLabelCount);
4206 }
4207
4208 SourceRange OrigStmtRange = S->getSourceRange();
4209
4210 // Perform a bottom up rewrite of all children.
4211 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4212 CI != E; ++CI)
4213 if (*CI) {
4214 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4215 if (newStmt)
4216 *CI = newStmt;
4217 }
4218
4219 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4220 // Rewrite the block body in place.
4221 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4222
4223 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00004224 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4225 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004226
4227 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4228 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00004229 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004230 return blockTranscribed;
4231 }
4232 // Handle specific things.
4233 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4234 return RewriteAtEncode(AtEncode);
4235
4236 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4237 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4238
Steve Naroff0e948412008-12-04 16:24:46 +00004239 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4240 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4241 if (BinOp) {
4242 // Because the rewriter doesn't allow us to rewrite rewritten code,
4243 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffedb4bc92008-12-09 12:56:34 +00004244 DisableReplaceStmt = true;
4245 // Save the source range. Even if we disable the replacement, the
4246 // rewritten node will have been inserted into the tree. If the synthesized
4247 // node is at the 'end', the rewriter will fail. Consider this:
4248 // self.errorHandler = handler ? handler :
4249 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4250 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff0e948412008-12-04 16:24:46 +00004251 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffedb4bc92008-12-09 12:56:34 +00004252 DisableReplaceStmt = false;
Steve Naroff102c3f22008-12-04 23:50:32 +00004253 //
4254 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4255 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4256 // to see the original expression). Consider this example:
4257 //
4258 // Foo *obj1, *obj2;
4259 //
4260 // obj1.i = [obj2 rrrr];
4261 //
4262 // 'BinOp' for the previous expression looks like:
4263 //
4264 // (BinaryOperator 0x231ccf0 'int' '='
4265 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4266 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4267 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4268 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4269 //
4270 // 'newStmt' represents the rewritten message expression. For example:
4271 //
4272 // (CallExpr 0x231d300 'id':'struct objc_object *'
4273 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4274 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4275 // (CStyleCastExpr 0x231d220 'void *'
4276 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4277 //
4278 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4279 // can be used as the setter argument. ReplaceStmt() will still 'see'
4280 // the original RHS (since we haven't altered BinOp).
4281 //
4282 // This implies the Rewrite* routines can no longer delete the original
4283 // node. As a result, we now leak the original AST nodes.
4284 //
Steve Naroffedb4bc92008-12-09 12:56:34 +00004285 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff0e948412008-12-04 16:24:46 +00004286 } else {
4287 return RewritePropertyGetter(PropRefExpr);
Steve Narofff6ce8a12008-12-03 00:56:33 +00004288 }
4289 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004290 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4291 return RewriteAtSelector(AtSelector);
4292
4293 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4294 return RewriteObjCStringLiteral(AtString);
4295
4296 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff0e948412008-12-04 16:24:46 +00004297#if 0
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004298 // Before we rewrite it, put the original message expression in a comment.
4299 SourceLocation startLoc = MessExpr->getLocStart();
4300 SourceLocation endLoc = MessExpr->getLocEnd();
4301
4302 const char *startBuf = SM->getCharacterData(startLoc);
4303 const char *endBuf = SM->getCharacterData(endLoc);
4304
4305 std::string messString;
4306 messString += "// ";
4307 messString.append(startBuf, endBuf-startBuf+1);
4308 messString += "\n";
4309
4310 // FIXME: Missing definition of
4311 // InsertText(clang::SourceLocation, char const*, unsigned int).
4312 // InsertText(startLoc, messString.c_str(), messString.size());
4313 // Tried this, but it didn't work either...
4314 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff0e948412008-12-04 16:24:46 +00004315#endif
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004316 return RewriteMessageExpr(MessExpr);
4317 }
4318
4319 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4320 return RewriteObjCTryStmt(StmtTry);
4321
4322 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4323 return RewriteObjCSynchronizedStmt(StmtTry);
4324
4325 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4326 return RewriteObjCThrowStmt(StmtThrow);
4327
4328 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4329 return RewriteObjCProtocolExpr(ProtocolExp);
4330
4331 if (ObjCForCollectionStmt *StmtForCollection =
4332 dyn_cast<ObjCForCollectionStmt>(S))
4333 return RewriteObjCForCollectionStmt(StmtForCollection,
4334 OrigStmtRange.getEnd());
4335 if (BreakStmt *StmtBreakStmt =
4336 dyn_cast<BreakStmt>(S))
4337 return RewriteBreakStmt(StmtBreakStmt);
4338 if (ContinueStmt *StmtContinueStmt =
4339 dyn_cast<ContinueStmt>(S))
4340 return RewriteContinueStmt(StmtContinueStmt);
4341
4342 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4343 // and cast exprs.
4344 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4345 // FIXME: What we're doing here is modifying the type-specifier that
4346 // precedes the first Decl. In the future the DeclGroup should have
4347 // a separate type-specifier that we can rewrite.
4348 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4349
4350 // Blocks rewrite rules.
4351 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4352 DI != DE; ++DI) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00004353 Decl *SD = *DI;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004354 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004355 if (isTopLevelBlockPointerType(ND->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004356 RewriteBlockPointerDecl(ND);
4357 else if (ND->getType()->isFunctionPointerType())
4358 CheckFunctionPointerDecl(ND->getType(), ND);
4359 }
4360 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004361 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004362 RewriteBlockPointerDecl(TD);
4363 else if (TD->getUnderlyingType()->isFunctionPointerType())
4364 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4365 }
4366 }
4367 }
4368
4369 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4370 RewriteObjCQualifiedInterfaceTypes(CE);
4371
4372 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4373 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4374 assert(!Stmts.empty() && "Statement stack is empty");
4375 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4376 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4377 && "Statement stack mismatch");
4378 Stmts.pop_back();
4379 }
4380 // Handle blocks rewriting.
4381 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4382 if (BDRE->isByRef())
4383 RewriteBlockDeclRefExpr(BDRE);
4384 }
4385 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004386 if (CE->getCallee()->getType()->isBlockPointerType()) {
4387 Stmt *BlockCall = SynthesizeBlockCall(CE);
4388 ReplaceStmt(S, BlockCall);
4389 return BlockCall;
4390 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004391 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004392 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004393 RewriteCastExpr(CE);
4394 }
4395#if 0
4396 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004397 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004398 // Get the new text.
4399 std::string SStr;
4400 llvm::raw_string_ostream Buf(SStr);
4401 Replacement->printPretty(Buf);
4402 const std::string &Str = Buf.str();
4403
4404 printf("CAST = %s\n", &Str[0]);
4405 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4406 delete S;
4407 return Replacement;
4408 }
4409#endif
4410 // Return this stmt unmodified.
4411 return S;
4412}
4413
4414/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4415/// main file of the input.
4416void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4417 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffee8d4972008-12-17 00:20:22 +00004418 if (FD->isOverloadedOperator())
4419 return;
4420
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004421 // Since function prototypes don't have ParmDecl's, we check the function
4422 // prototype. This enables us to rewrite function declarations and
4423 // definitions using the same code.
Douglas Gregor4fa58902009-02-26 23:50:07 +00004424 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004425
Ted Kremenek30916072009-03-12 18:33:24 +00004426 if (CompoundStmt *Body = FD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004427 CurFunctionDef = FD;
Steve Naroff0e948412008-12-04 16:24:46 +00004428 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004429 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004430 Body =
4431 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4432 FD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004433 CurrentBody = 0;
4434 if (PropParentMap) {
4435 delete PropParentMap;
4436 PropParentMap = 0;
4437 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004438 // This synthesizes and inserts the block "impl" struct, invoke function,
4439 // and any copy/dispose helper functions.
4440 InsertBlockLiteralsWithinFunction(FD);
4441 CurFunctionDef = 0;
4442 }
4443 return;
4444 }
4445 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenek30916072009-03-12 18:33:24 +00004446 if (CompoundStmt *Body = MD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004447 CurMethodDef = MD;
Steve Naroff0e948412008-12-04 16:24:46 +00004448 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004449 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004450 Body =
4451 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4452 MD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004453 CurrentBody = 0;
4454 if (PropParentMap) {
4455 delete PropParentMap;
4456 PropParentMap = 0;
4457 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004458 InsertBlockLiteralsWithinMethod(MD);
4459 CurMethodDef = 0;
4460 }
4461 }
4462 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4463 ClassImplementation.push_back(CI);
4464 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4465 CategoryImplementation.push_back(CI);
4466 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4467 RewriteForwardClassDecl(CD);
4468 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4469 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffd896f4b2008-12-11 21:05:33 +00004470 if (isTopLevelBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004471 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004472 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004473 CheckFunctionPointerDecl(VD->getType(), VD);
4474 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004475 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004476 RewriteCastExpr(CE);
4477 }
4478 }
4479 }
Steve Naroff80c54752008-10-29 18:15:37 +00004480 if (VD->getInit()) {
4481 GlobalVarDecl = VD;
Steve Naroff0e948412008-12-04 16:24:46 +00004482 CollectPropertySetters(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004483 CurrentBody = VD->getInit();
Steve Naroff80c54752008-10-29 18:15:37 +00004484 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004485 CurrentBody = 0;
4486 if (PropParentMap) {
4487 delete PropParentMap;
4488 PropParentMap = 0;
4489 }
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004490 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004491 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004492 GlobalVarDecl = 0;
4493
4494 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004495 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004496 RewriteCastExpr(CE);
4497 }
4498 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004499 return;
4500 }
4501 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004502 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004503 RewriteBlockPointerDecl(TD);
4504 else if (TD->getUnderlyingType()->isFunctionPointerType())
4505 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4506 return;
4507 }
4508 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4509 if (RD->isDefinition()) {
Douglas Gregor640a04b2008-12-11 17:59:21 +00004510 for (RecordDecl::field_iterator i = RD->field_begin(),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004511 e = RD->field_end(); i != e; ++i) {
4512 FieldDecl *FD = *i;
Steve Naroffd896f4b2008-12-11 21:05:33 +00004513 if (isTopLevelBlockPointerType(FD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004514 RewriteBlockPointerDecl(FD);
4515 }
4516 }
4517 return;
4518 }
4519 // Nothing yet.
4520}
4521
Chris Lattner2a594d02009-03-28 04:11:33 +00004522void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004523 // Get the top-level buffer that this corresponds to.
4524
4525 // Rewrite tabs if we care.
4526 //RewriteTabs();
4527
4528 if (Diags.hasErrorOccurred())
4529 return;
4530
4531 // Create the output file.
4532
4533 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4534 llvm::raw_ostream *OutFile;
4535 if (OutFileName == "-") {
4536 OutFile = &llvm::outs();
4537 } else if (!OutFileName.empty()) {
4538 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004539 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4540 // set binary mode (critical for Windoze)
4541 true,
4542 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004543 OwnedStream.reset(OutFile);
4544 } else if (InFileName == "-") {
4545 OutFile = &llvm::outs();
4546 } else {
4547 llvm::sys::Path Path(InFileName);
4548 Path.eraseSuffix();
4549 Path.appendSuffix("cpp");
4550 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004551 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4552 // set binary mode (critical for Windoze)
4553 true,
4554 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004555 OwnedStream.reset(OutFile);
4556 }
4557
4558 RewriteInclude();
4559
Chris Lattnerf4f776a2009-01-17 06:22:33 +00004560 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004561 Preamble.c_str(), Preamble.size(), false);
4562
Steve Naroff901d8fd2008-11-14 14:10:01 +00004563 if (ClassImplementation.size() || CategoryImplementation.size())
4564 RewriteImplementations();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004565
4566 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4567 // we are done.
4568 if (const RewriteBuffer *RewriteBuf =
4569 Rewrite.getRewriteBufferFor(MainFileID)) {
4570 //printf("Changed:\n");
4571 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4572 } else {
4573 fprintf(stderr, "No changes\n");
4574 }
Steve Naroff21658f62008-11-13 20:07:04 +00004575
Steve Naroff901d8fd2008-11-14 14:10:01 +00004576 if (ClassImplementation.size() || CategoryImplementation.size()) {
4577 // Rewrite Objective-c meta data*
4578 std::string ResultStr;
4579 SynthesizeMetaDataIntoBuffer(ResultStr);
4580 // Emit metadata.
4581 *OutFile << ResultStr;
4582 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004583 OutFile->flush();
4584}
4585