blob: f31e5ccf5f9e0e520e0b73725359144fc4b4e256 [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
Douglas Gregorcd19b572009-04-23 01:02:12 +0000289 template<typename MethodIterator>
290 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
291 MethodIterator 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 Lattnere1be6022009-04-14 23:22:57 +0000458 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
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
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000587 for (DeclContext::decl_iterator DI = LSD->decls_begin(*Context),
588 DIEnd = LSD->decls_end(*Context);
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000589 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
Steve Naroff121ed222008-12-02 15:48:25 +0000702 if (PD->isReadOnly())
703 return;
704
705 // Generate the 'setter' function.
706 std::string Setr;
707 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff121ed222008-12-02 15:48:25 +0000708 Setr += "{ ";
Steve Naroff1e7b7962008-12-02 16:05:55 +0000709 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff11671e72008-12-02 17:54:50 +0000710 // FIXME: deal with code generation implications for various property
711 // attributes (copy, retain, nonatomic).
Steve Narofff6ce8a12008-12-03 00:56:33 +0000712 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff1e7b7962008-12-02 16:05:55 +0000713 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff20f67392008-12-11 19:29:16 +0000714 Setr += PD->getNameAsCString();
Steve Naroff1e7b7962008-12-02 16:05:55 +0000715 Setr += "; }";
Steve Naroff121ed222008-12-02 15:48:25 +0000716 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroff110be842008-12-01 20:33:01 +0000717}
Chris Lattner569faa62007-10-11 18:38:32 +0000718
Steve Naroff44e81222008-04-14 22:03:09 +0000719void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000720 // Get the start location and compute the semi location.
721 SourceLocation startLoc = ClassDecl->getLocation();
722 const char *startBuf = SM->getCharacterData(startLoc);
723 const char *semiPtr = strchr(startBuf, ';');
724
725 // Translate to typedef's that forward reference structs with the same name
726 // as the class. As a convenience, we include the original declaration
727 // as a comment.
728 std::string typedefString;
729 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000730 typedefString.append(startBuf, semiPtr-startBuf+1);
731 typedefString += "\n";
Chris Lattner6a028742009-02-20 18:04:31 +0000732 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
733 I != E; ++I) {
734 ObjCInterfaceDecl *ForwardDecl = *I;
Steve Naroff2aeae312007-11-09 12:50:28 +0000735 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000736 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000737 typedefString += "\n";
738 typedefString += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +0000739 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000740 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000741 typedefString += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000742 typedefString += ForwardDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +0000743 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000744 }
745
746 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000747 ReplaceText(startLoc, semiPtr-startBuf+1,
748 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000749}
750
Steve Naroff44e81222008-04-14 22:03:09 +0000751void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000752 SourceLocation LocStart = Method->getLocStart();
753 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000754
Chris Lattner2d89c562009-02-04 01:06:56 +0000755 if (SM->getInstantiationLineNumber(LocEnd) >
756 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff99f50fe2008-10-21 13:37:27 +0000757 InsertText(LocStart, "#if 0\n", 6);
758 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000759 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000760 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000761 }
762}
763
Steve Naroff56af2002009-01-11 01:06:09 +0000764void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000765{
Steve Naroff56af2002009-01-11 01:06:09 +0000766 SourceLocation Loc = prop->getLocation();
767
768 ReplaceText(Loc, 0, "// ", 3);
769
770 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000771}
772
Steve Naroff44e81222008-04-14 22:03:09 +0000773void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000774 SourceLocation LocStart = CatDecl->getLocStart();
775
776 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000777 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000778
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000779 for (ObjCCategoryDecl::instmeth_iterator
780 I = CatDecl->instmeth_begin(*Context),
781 E = CatDecl->instmeth_end(*Context);
782 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000783 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000784 for (ObjCCategoryDecl::classmeth_iterator
785 I = CatDecl->classmeth_begin(*Context),
786 E = CatDecl->classmeth_end(*Context);
787 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000788 RewriteMethodDeclaration(*I);
789
Steve Naroff667f1682007-10-30 13:30:57 +0000790 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000791 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000792}
793
Steve Naroff44e81222008-04-14 22:03:09 +0000794void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000795 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000796
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000797 SourceLocation LocStart = PDecl->getLocStart();
798
799 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000800 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000801
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000802 for (ObjCProtocolDecl::instmeth_iterator
803 I = PDecl->instmeth_begin(*Context),
804 E = PDecl->instmeth_end(*Context);
805 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000806 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000807 for (ObjCProtocolDecl::classmeth_iterator
808 I = PDecl->classmeth_begin(*Context),
809 E = PDecl->classmeth_end(*Context);
810 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +0000811 RewriteMethodDeclaration(*I);
812
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000813 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000814 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000815 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000816
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000817 // Must comment out @optional/@required
818 const char *startBuf = SM->getCharacterData(LocStart);
819 const char *endBuf = SM->getCharacterData(LocEnd);
820 for (const char *p = startBuf; p < endBuf; p++) {
821 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
822 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000823 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000824 ReplaceText(OptionalLoc, strlen("@optional"),
825 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000826
827 }
828 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
829 std::string CommentedRequired = "/* @required */";
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("@required"),
832 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000833
834 }
835 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000836}
837
Steve Naroff44e81222008-04-14 22:03:09 +0000838void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000839 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000840 if (LocStart.isInvalid())
841 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000842 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000843 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000844}
845
Steve Naroff44e81222008-04-14 22:03:09 +0000846void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000847 std::string &ResultStr) {
Steve Naroff6449c6c2008-10-30 12:09:33 +0000848 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff91044cf2008-07-16 14:40:40 +0000849 const FunctionType *FPRetType = 0;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000850 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000851 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000852 ResultStr += "id";
Steve Naroff20f67392008-12-11 19:29:16 +0000853 else if (OMD->getResultType()->isFunctionPointerType() ||
854 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000855 // needs special handling, since pointer-to-functions have special
856 // syntax (where a decaration models use).
857 QualType retType = OMD->getResultType();
Steve Naroff20f67392008-12-11 19:29:16 +0000858 QualType PointeeTy;
859 if (const PointerType* PT = retType->getAsPointerType())
860 PointeeTy = PT->getPointeeType();
861 else if (const BlockPointerType *BPT = retType->getAsBlockPointerType())
862 PointeeTy = BPT->getPointeeType();
863 if ((FPRetType = PointeeTy->getAsFunctionType())) {
864 ResultStr += FPRetType->getResultType().getAsString();
865 ResultStr += "(*";
Steve Naroff91044cf2008-07-16 14:40:40 +0000866 }
867 } else
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000868 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000869 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000870
871 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000872 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000873
Douglas Gregor5d764842009-01-09 17:18:27 +0000874 if (OMD->isInstanceMethod())
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000875 NameStr += "_I_";
876 else
877 NameStr += "_C_";
878
Chris Lattner271d4c22008-11-24 05:29:24 +0000879 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000880 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000881
Ted Kremenek42730c52008-01-07 19:49:32 +0000882 if (ObjCCategoryImplDecl *CID =
Steve Naroff438be772009-01-08 19:41:02 +0000883 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000884 NameStr += CID->getNameAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000885 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000886 }
Steve Naroff5cb1e6e2008-04-04 22:23:44 +0000887 // Append selector names, replacing ':' with '_'
Chris Lattner3a8f2942008-11-24 03:33:13 +0000888 {
889 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000890 int len = selString.size();
891 for (int i = 0; i < len; i++)
892 if (selString[i] == ':')
893 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000894 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000895 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000896 // Remember this name for metadata emission
897 MethodInternalNames[OMD] = NameStr;
898 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000899
900 // Rewrite arguments
901 ResultStr += "(";
902
903 // invisible arguments
Douglas Gregor5d764842009-01-09 17:18:27 +0000904 if (OMD->isInstanceMethod()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000905 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000906 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000907 if (!LangOpts.Microsoft) {
908 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
909 ResultStr += "struct ";
910 }
911 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattner271d4c22008-11-24 05:29:24 +0000912 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +0000913 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000914 }
915 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000916 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000917
918 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000919 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000920 ResultStr += " _cmd";
921
922 // Method arguments.
Chris Lattner5c6b2c62009-02-20 18:43:26 +0000923 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
924 E = OMD->param_end(); PI != E; ++PI) {
925 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000926 ResultStr += ", ";
Steve Naroff133dfda2008-04-18 21:13:19 +0000927 if (PDecl->getType()->isObjCQualifiedIdType()) {
928 ResultStr += "id ";
Chris Lattner271d4c22008-11-24 05:29:24 +0000929 ResultStr += PDecl->getNameAsString();
Steve Naroff133dfda2008-04-18 21:13:19 +0000930 } else {
Chris Lattner271d4c22008-11-24 05:29:24 +0000931 std::string Name = PDecl->getNameAsString();
Steve Naroffd896f4b2008-12-11 21:05:33 +0000932 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff4e2ae512008-10-30 14:45:29 +0000933 // Make sure we convert "t (^)(...)" to "t (*)(...)".
934 const BlockPointerType *BPT = PDecl->getType()->getAsBlockPointerType();
935 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name);
936 } else
937 PDecl->getType().getAsStringInternal(Name);
Steve Naroff133dfda2008-04-18 21:13:19 +0000938 ResultStr += Name;
939 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000940 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000941 if (OMD->isVariadic())
942 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000943 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000944
Steve Naroff91044cf2008-07-16 14:40:40 +0000945 if (FPRetType) {
946 ResultStr += ")"; // close the precedence "scope" for "*".
947
948 // Now, emit the argument types (if any).
Douglas Gregor4fa58902009-02-26 23:50:07 +0000949 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff91044cf2008-07-16 14:40:40 +0000950 ResultStr += "(";
951 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
952 if (i) ResultStr += ", ";
953 std::string ParamStr = FT->getArgType(i).getAsString();
954 ResultStr += ParamStr;
955 }
956 if (FT->isVariadic()) {
957 if (FT->getNumArgs()) ResultStr += ", ";
958 ResultStr += "...";
959 }
960 ResultStr += ")";
961 } else {
962 ResultStr += "()";
963 }
964 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000965}
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000966void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000967 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
968 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000969
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000970 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000971 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000972 else
Chris Lattner6216f292008-01-31 19:42:41 +0000973 InsertText(CID->getLocStart(), "// ", 3);
Steve Naroff21658f62008-11-13 20:07:04 +0000974
Ted Kremenek42730c52008-01-07 19:49:32 +0000975 for (ObjCCategoryImplDecl::instmeth_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +0000976 I = IMD ? IMD->instmeth_begin(*Context) : CID->instmeth_begin(*Context),
977 E = IMD ? IMD->instmeth_end(*Context) : CID->instmeth_end(*Context);
978 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000979 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000980 ObjCMethodDecl *OMD = *I;
981 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000982 SourceLocation LocStart = OMD->getLocStart();
Douglas Gregore3241e92009-04-18 00:02:19 +0000983 SourceLocation LocEnd = OMD->getBody(*Context)->getLocStart();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000984
985 const char *startBuf = SM->getCharacterData(LocStart);
986 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000987 ReplaceText(LocStart, endBuf-startBuf,
988 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000989 }
990
Ted Kremenek42730c52008-01-07 19:49:32 +0000991 for (ObjCCategoryImplDecl::classmeth_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +0000992 I = IMD ? IMD->classmeth_begin(*Context) : CID->classmeth_begin(*Context),
993 E = IMD ? IMD->classmeth_end(*Context) : CID->classmeth_end(*Context);
994 I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000995 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000996 ObjCMethodDecl *OMD = *I;
997 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000998 SourceLocation LocStart = OMD->getLocStart();
Douglas Gregore3241e92009-04-18 00:02:19 +0000999 SourceLocation LocEnd = OMD->getBody(*Context)->getLocStart();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001000
1001 const char *startBuf = SM->getCharacterData(LocStart);
1002 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001003 ReplaceText(LocStart, endBuf-startBuf,
1004 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001005 }
Steve Naroff110be842008-12-01 20:33:01 +00001006 for (ObjCCategoryImplDecl::propimpl_iterator
Douglas Gregorcd19b572009-04-23 01:02:12 +00001007 I = IMD ? IMD->propimpl_begin(*Context) : CID->propimpl_begin(*Context),
1008 E = IMD ? IMD->propimpl_end(*Context) : CID->propimpl_end(*Context);
1009 I != E; ++I) {
Steve Naroffea6610f2008-12-02 17:36:43 +00001010 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroff110be842008-12-01 20:33:01 +00001011 }
1012
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001013 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +00001014 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +00001015 else
Chris Lattner6216f292008-01-31 19:42:41 +00001016 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +00001017}
1018
Steve Naroff44e81222008-04-14 22:03:09 +00001019void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +00001020 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +00001021 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +00001022 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +00001023 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001024 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001025 ResultStr += "\n";
1026 ResultStr += "#define _REWRITER_typedef_";
Chris Lattner271d4c22008-11-24 05:29:24 +00001027 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001028 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +00001029 ResultStr += "typedef struct objc_object ";
Chris Lattner271d4c22008-11-24 05:29:24 +00001030 ResultStr += ClassDecl->getNameAsString();
Steve Naroff2aeae312007-11-09 12:50:28 +00001031 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +00001032 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001033 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +00001034 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001035 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +00001036
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001037 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(*Context),
1038 E = ClassDecl->prop_end(*Context); I != E; ++I)
Steve Naroff56af2002009-01-11 01:06:09 +00001039 RewriteProperty(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001040 for (ObjCInterfaceDecl::instmeth_iterator
1041 I = ClassDecl->instmeth_begin(*Context),
1042 E = ClassDecl->instmeth_end(*Context);
1043 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001044 RewriteMethodDeclaration(*I);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001045 for (ObjCInterfaceDecl::classmeth_iterator
1046 I = ClassDecl->classmeth_begin(*Context),
1047 E = ClassDecl->classmeth_end(*Context);
1048 I != E; ++I)
Steve Naroff2ce399a2007-12-14 23:37:57 +00001049 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;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001139 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1140 D->getIdentifier(),
1141 clsDeclared);
Steve Naroffa9636222008-05-08 17:52:16 +00001142 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1143
1144 // Synthesize an explicit cast to gain access to the ivar.
1145 std::string RecName = clsDeclared->getIdentifier()->getName();
1146 RecName += "_IMPL";
1147 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001148 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001149 SourceLocation(), II);
Steve Naroffa9636222008-05-08 17:52:16 +00001150 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1151 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001152 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1153 castT,SourceLocation(),
1154 SourceLocation());
Steve Naroffa9636222008-05-08 17:52:16 +00001155 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001156 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1157 IV->getBase()->getLocEnd(),
1158 castExpr);
Steve Naroffa9636222008-05-08 17:52:16 +00001159 if (IV->isFreeIvar() &&
Steve Naroff38a9e3f2008-10-27 17:20:55 +00001160 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00001161 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1162 IV->getLocation(),
1163 D->getType());
Steve Naroffa9636222008-05-08 17:52:16 +00001164 ReplaceStmt(IV, ME);
Steve Naroff102c3f22008-12-04 23:50:32 +00001165 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffa9636222008-05-08 17:52:16 +00001166 return ME;
Steve Naroff292b7b92007-11-15 11:33:00 +00001167 }
Chris Lattner343c82b2008-05-23 20:40:52 +00001168
1169 ReplaceStmt(IV->getBase(), PE);
1170 // Cannot delete IV->getBase(), since PE points to it.
1171 // Replace the old base with the cast. This is important when doing
1172 // embedded rewrites. For example, [newInv->_container addObject:0].
1173 IV->setBase(PE);
1174 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +00001175 }
Steve Naroffe6155362008-04-18 21:55:08 +00001176 } else { // we are outside a method.
Steve Naroffd8d30b92008-05-06 23:20:07 +00001177 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
1178
1179 // Explicit ivar refs need to have a cast inserted.
1180 // FIXME: consider sharing some of this code with the code above.
1181 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Steve Naroffa9636222008-05-08 17:52:16 +00001182 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001183 // lookup which class implements the instance variable.
1184 ObjCInterfaceDecl *clsDeclared = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001185 iFaceDecl->getDecl()->lookupInstanceVariable(*Context,
1186 D->getIdentifier(),
1187 clsDeclared);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001188 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
1189
1190 // Synthesize an explicit cast to gain access to the ivar.
1191 std::string RecName = clsDeclared->getIdentifier()->getName();
1192 RecName += "_IMPL";
1193 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00001194 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek2c984042008-09-05 01:34:33 +00001195 SourceLocation(), II);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001196 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1197 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Ted Kremenek0c97e042009-02-07 01:47:29 +00001198 CastExpr *castExpr = new (Context) CStyleCastExpr(castT, IV->getBase(),
1199 castT, SourceLocation(),
1200 SourceLocation());
Steve Naroffd8d30b92008-05-06 23:20:07 +00001201 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001202 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner3cca6612008-05-28 16:38:23 +00001203 IV->getBase()->getLocEnd(), castExpr);
Steve Naroffd8d30b92008-05-06 23:20:07 +00001204 ReplaceStmt(IV->getBase(), PE);
1205 // Cannot delete IV->getBase(), since PE points to it.
1206 // Replace the old base with the cast. This is important when doing
1207 // embedded rewrites. For example, [newInv->_container addObject:0].
1208 IV->setBase(PE);
1209 return IV;
1210 }
Steve Naroff292b7b92007-11-15 11:33:00 +00001211 }
Steve Naroffe6155362008-04-18 21:55:08 +00001212 return IV;
Steve Naroff6b759ce2007-11-15 02:58:25 +00001213}
1214
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001215/// SynthCountByEnumWithState - To print:
1216/// ((unsigned int (*)
1217/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1218/// (void *)objc_msgSend)((id)l_collection,
1219/// sel_registerName(
1220/// "countByEnumeratingWithState:objects:count:"),
1221/// &enumState,
1222/// (id *)items, (unsigned int)16)
1223///
Steve Naroff44e81222008-04-14 22:03:09 +00001224void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001225 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1226 "id *, unsigned int))(void *)objc_msgSend)";
1227 buf += "\n\t\t";
1228 buf += "((id)l_collection,\n\t\t";
1229 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1230 buf += "\n\t\t";
1231 buf += "&enumState, "
1232 "(id *)items, (unsigned int)16)";
1233}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001234
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001235/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1236/// statement to exit to its outer synthesized loop.
1237///
Steve Naroff44e81222008-04-14 22:03:09 +00001238Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001239 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1240 return S;
1241 // replace break with goto __break_label
1242 std::string buf;
1243
1244 SourceLocation startLoc = S->getLocStart();
1245 buf = "goto __break_label_";
1246 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001247 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001248
1249 return 0;
1250}
1251
1252/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1253/// statement to continue with its inner synthesized loop.
1254///
Steve Naroff44e81222008-04-14 22:03:09 +00001255Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001256 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1257 return S;
1258 // replace continue with goto __continue_label
1259 std::string buf;
1260
1261 SourceLocation startLoc = S->getLocStart();
1262 buf = "goto __continue_label_";
1263 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001264 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001265
1266 return 0;
1267}
1268
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001269/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001270/// It rewrites:
1271/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001272
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001273/// Into:
1274/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001275/// type elem;
1276/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001277/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001278/// id l_collection = (id)collection;
1279/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1280/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001281/// if (limit) {
1282/// unsigned long startMutations = *enumState.mutationsPtr;
1283/// do {
1284/// unsigned long counter = 0;
1285/// do {
1286/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001287/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001288/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001289/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001290/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001291/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001292/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1293/// objects:items count:16]);
1294/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001295/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001296/// }
1297/// else
1298/// elem = nil;
1299/// }
1300///
Steve Naroff44e81222008-04-14 22:03:09 +00001301Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner2c022162008-01-31 05:10:40 +00001302 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001303 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1304 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1305 "ObjCForCollectionStmt Statement stack mismatch");
1306 assert(!ObjCBcLabelNo.empty() &&
1307 "ObjCForCollectionStmt - Label No stack empty");
1308
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001309 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001310 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001311 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001312 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001313 std::string buf;
1314 buf = "\n{\n\t";
1315 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1316 // type elem;
Chris Lattner4a9a85e2009-03-28 06:33:19 +00001317 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek91a2bd32008-10-06 22:16:13 +00001318 QualType ElementType = cast<ValueDecl>(D)->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001319 elementTypeAsString = ElementType.getAsString();
1320 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001321 buf += " ";
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001322 elementName = D->getNameAsCString();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001323 buf += elementName;
1324 buf += ";\n\t";
1325 }
Chris Lattner690c2872008-04-08 05:52:18 +00001326 else {
1327 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattnerd120b9e2008-11-24 03:54:41 +00001328 elementName = DR->getDecl()->getNameAsCString();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001329 elementTypeAsString
1330 = cast<ValueDecl>(DR->getDecl())->getType().getAsString();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001331 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001332
1333 // struct __objcFastEnumerationState enumState = { 0 };
1334 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1335 // id items[16];
1336 buf += "id items[16];\n\t";
1337 // id l_collection = (id)
1338 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001339 // Find start location of 'collection' the hard way!
1340 const char *startCollectionBuf = startBuf;
1341 startCollectionBuf += 3; // skip 'for'
1342 startCollectionBuf = strchr(startCollectionBuf, '(');
1343 startCollectionBuf++; // skip '('
1344 // find 'in' and skip it.
1345 while (*startCollectionBuf != ' ' ||
1346 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1347 (*(startCollectionBuf+3) != ' ' &&
1348 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1349 startCollectionBuf++;
1350 startCollectionBuf += 3;
1351
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001352 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001353 ReplaceText(startLoc, startCollectionBuf - startBuf,
1354 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001355 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001356 SourceLocation rightParenLoc = S->getRParenLoc();
1357 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1358 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001359 buf = ";\n\t";
1360
1361 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1362 // objects:items count:16];
1363 // which is synthesized into:
1364 // unsigned int limit =
1365 // ((unsigned int (*)
1366 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1367 // (void *)objc_msgSend)((id)l_collection,
1368 // sel_registerName(
1369 // "countByEnumeratingWithState:objects:count:"),
1370 // (struct __objcFastEnumerationState *)&state,
1371 // (id *)items, (unsigned int)16);
1372 buf += "unsigned long limit =\n\t\t";
1373 SynthCountByEnumWithState(buf);
1374 buf += ";\n\t";
1375 /// if (limit) {
1376 /// unsigned long startMutations = *enumState.mutationsPtr;
1377 /// do {
1378 /// unsigned long counter = 0;
1379 /// do {
1380 /// if (startMutations != *enumState.mutationsPtr)
1381 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001382 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001383 buf += "if (limit) {\n\t";
1384 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1385 buf += "do {\n\t\t";
1386 buf += "unsigned long counter = 0;\n\t\t";
1387 buf += "do {\n\t\t\t";
1388 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1389 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1390 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001391 buf += " = (";
1392 buf += elementTypeAsString;
1393 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001394 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001395 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001396
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001397 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001398 /// } while (counter < limit);
1399 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1400 /// objects:items count:16]);
1401 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001402 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001403 /// }
1404 /// else
1405 /// elem = nil;
1406 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001407 ///
1408 buf = ";\n\t";
1409 buf += "__continue_label_";
1410 buf += utostr(ObjCBcLabelNo.back());
1411 buf += ": ;";
1412 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001413 buf += "} while (counter < limit);\n\t";
1414 buf += "} while (limit = ";
1415 SynthCountByEnumWithState(buf);
1416 buf += ");\n\t";
1417 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001418 buf += " = ((id)0);\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001419 buf += "__break_label_";
1420 buf += utostr(ObjCBcLabelNo.back());
1421 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001422 buf += "}\n\t";
1423 buf += "else\n\t\t";
1424 buf += elementName;
Steve Naroffa9dc0262008-12-17 14:24:39 +00001425 buf += " = ((id)0);\n";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001426 buf += "}\n";
Steve Naroff5f238fe2008-07-21 18:26:02 +00001427
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001428 // Insert all these *after* the statement body.
Steve Naroff5f238fe2008-07-21 18:26:02 +00001429 if (isa<CompoundStmt>(S->getBody())) {
1430 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1431 InsertText(endBodyLoc, buf.c_str(), buf.size());
1432 } else {
1433 /* Need to treat single statements specially. For example:
1434 *
1435 * for (A *a in b) if (stuff()) break;
1436 * for (A *a in b) xxxyy;
1437 *
1438 * The following code simply scans ahead to the semi to find the actual end.
1439 */
1440 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1441 const char *semiBuf = strchr(stmtBuf, ';');
1442 assert(semiBuf && "Can't find ';'");
1443 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1444 InsertText(endBodyLoc, buf.c_str(), buf.size());
1445 }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001446 Stmts.pop_back();
1447 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001448 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001449}
1450
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001451/// RewriteObjCSynchronizedStmt -
1452/// This routine rewrites @synchronized(expr) stmt;
1453/// into:
1454/// objc_sync_enter(expr);
1455/// @try stmt @finally { objc_sync_exit(expr); }
1456///
Steve Naroff44e81222008-04-14 22:03:09 +00001457Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001458 // Get the start location and compute the semi location.
1459 SourceLocation startLoc = S->getLocStart();
1460 const char *startBuf = SM->getCharacterData(startLoc);
1461
1462 assert((*startBuf == '@') && "bogus @synchronized location");
1463
1464 std::string buf;
Steve Naroffc1656a62008-08-21 13:03:03 +00001465 buf = "objc_sync_enter((id)";
1466 const char *lparenBuf = startBuf;
1467 while (*lparenBuf != '(') lparenBuf++;
1468 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Steve Naroff027cd0b2008-08-19 13:04:19 +00001469 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1470 // the sync expression is typically a message expression that's already
1471 // been rewritten! (which implies the SourceLocation's are invalid).
1472 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001473 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroff027cd0b2008-08-19 13:04:19 +00001474 while (*endBuf != ')') endBuf--;
1475 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001476 buf = ");\n";
1477 // declare a new scope with two variables, _stack and _rethrow.
1478 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1479 buf += "int buf[18/*32-bit i386*/];\n";
1480 buf += "char *pointers[4];} _stack;\n";
1481 buf += "id volatile _rethrow = 0;\n";
1482 buf += "objc_exception_try_enter(&_stack);\n";
1483 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001484 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001485 startLoc = S->getSynchBody()->getLocEnd();
1486 startBuf = SM->getCharacterData(startLoc);
1487
Steve Naroff027cd0b2008-08-19 13:04:19 +00001488 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001489 SourceLocation lastCurlyLoc = startLoc;
1490 buf = "}\nelse {\n";
1491 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1492 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroff17919b52008-07-16 19:47:39 +00001493 buf += " objc_sync_exit(";
Ted Kremenek0c97e042009-02-07 01:47:29 +00001494 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
1495 S->getSynchExpr(),
1496 Context->getObjCIdType(),
1497 SourceLocation(),
1498 SourceLocation());
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00001499 std::string syncExprBufS;
1500 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Steve Naroffc1656a62008-08-21 13:03:03 +00001501 syncExpr->printPretty(syncExprBuf);
Steve Naroff17919b52008-07-16 19:47:39 +00001502 buf += syncExprBuf.str();
1503 buf += ");\n";
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001504 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1505 buf += "}\n";
1506 buf += "}";
1507
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001508 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001509 return 0;
1510}
1511
Steve Naroff43964fb2008-12-05 17:03:39 +00001512void RewriteObjC::WarnAboutReturnGotoContinueOrBreakStmts(Stmt *S) {
1513 // Perform a bottom up traversal of all children.
1514 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1515 CI != E; ++CI)
1516 if (*CI)
1517 WarnAboutReturnGotoContinueOrBreakStmts(*CI);
1518
1519 if (isa<ReturnStmt>(S) || isa<ContinueStmt>(S) ||
1520 isa<BreakStmt>(S) || isa<GotoStmt>(S)) {
1521 Diags.Report(Context->getFullLoc(S->getLocStart()),
1522 TryFinallyContainsReturnDiag);
1523 }
1524 return;
1525}
1526
Steve Naroff44e81222008-04-14 22:03:09 +00001527Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001528 // Get the start location and compute the semi location.
1529 SourceLocation startLoc = S->getLocStart();
1530 const char *startBuf = SM->getCharacterData(startLoc);
1531
1532 assert((*startBuf == '@') && "bogus @try location");
1533
1534 std::string buf;
1535 // declare a new scope with two variables, _stack and _rethrow.
1536 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1537 buf += "int buf[18/*32-bit i386*/];\n";
1538 buf += "char *pointers[4];} _stack;\n";
1539 buf += "id volatile _rethrow = 0;\n";
1540 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001541 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001542
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001543 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001544
1545 startLoc = S->getTryBody()->getLocEnd();
1546 startBuf = SM->getCharacterData(startLoc);
1547
1548 assert((*startBuf == '}') && "bogus @try block");
Steve Naroff9d0ff352008-07-16 15:31:30 +00001549
Steve Naroffe9f69842007-11-07 04:08:17 +00001550 SourceLocation lastCurlyLoc = startLoc;
Steve Naroff9d0ff352008-07-16 15:31:30 +00001551 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1552 if (catchList) {
1553 startLoc = startLoc.getFileLocWithOffset(1);
1554 buf = " /* @catch begin */ else {\n";
1555 buf += " id _caught = objc_exception_extract(&_stack);\n";
1556 buf += " objc_exception_try_enter (&_stack);\n";
1557 buf += " if (_setjmp(_stack.buf))\n";
1558 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1559 buf += " else { /* @catch continue */";
1560
1561 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff36269d22008-09-09 19:59:12 +00001562 } else { /* no catch list */
1563 buf = "}\nelse {\n";
1564 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1565 buf += "}";
1566 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroff9d0ff352008-07-16 15:31:30 +00001567 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001568 bool sawIdTypedCatch = false;
1569 Stmt *lastCatchBody = 0;
Steve Naroffe9f69842007-11-07 04:08:17 +00001570 while (catchList) {
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001571 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffe9f69842007-11-07 04:08:17 +00001572
1573 if (catchList == S->getCatchStmts())
1574 buf = "if ("; // we are generating code for the first catch clause
1575 else
1576 buf = "else if (";
1577 startLoc = catchList->getLocStart();
1578 startBuf = SM->getCharacterData(startLoc);
1579
1580 assert((*startBuf == '@') && "bogus @catch location");
1581
1582 const char *lParenLoc = strchr(startBuf, '(');
1583
Steve Naroff397c4ce2008-02-01 22:08:12 +00001584 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001585 // Now rewrite the body...
1586 lastCatchBody = catchList->getCatchBody();
Steve Naroff929c77e2008-02-01 20:02:07 +00001587 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1588 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner690c2872008-04-08 05:52:18 +00001589 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1590 "bogus @catch paren location");
Steve Naroff929c77e2008-02-01 20:02:07 +00001591 assert((*bodyBuf == '{') && "bogus @catch body location");
1592
1593 buf += "1) { id _tmp = _caught;";
1594 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1595 buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001596 } else if (catchDecl) {
1597 QualType t = catchDecl->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001598 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001599 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001600 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001601 sawIdTypedCatch = true;
1602 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001603 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001604
Ted Kremenek42730c52008-01-07 19:49:32 +00001605 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001606 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001607 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00001608 buf += cls->getDecl()->getNameAsString();
Steve Naroffd3287d82007-11-07 18:43:40 +00001609 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001610 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001611 }
1612 }
1613 // Now rewrite the body...
1614 lastCatchBody = catchList->getCatchBody();
1615 SourceLocation rParenLoc = catchList->getRParenLoc();
1616 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1617 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1618 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1619 assert((*rParenBuf == ')') && "bogus @catch paren location");
1620 assert((*bodyBuf == '{') && "bogus @catch body location");
1621
1622 buf = " = _caught;";
1623 // Here we replace ") {" with "= _caught;" (which initializes and
1624 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001625 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff0e8b96a2009-03-03 19:52:17 +00001626 } else {
Steve Naroffe9f69842007-11-07 04:08:17 +00001627 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001628 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001629 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001630 catchList = catchList->getNextCatchStmt();
1631 }
1632 // Complete the catch list...
1633 if (lastCatchBody) {
1634 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001635 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1636 "bogus @catch body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001637
Steve Naroff31325c12008-09-11 15:29:03 +00001638 // Insert the last (implicit) else clause *before* the right curly brace.
1639 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1640 buf = "} /* last catch end */\n";
1641 buf += "else {\n";
1642 buf += " _rethrow = _caught;\n";
1643 buf += " objc_exception_try_exit(&_stack);\n";
1644 buf += "} } /* @catch end */\n";
1645 if (!S->getFinallyStmt())
1646 buf += "}\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001647 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001648
1649 // Set lastCurlyLoc
1650 lastCurlyLoc = lastCatchBody->getLocEnd();
1651 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001652 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001653 startLoc = finalStmt->getLocStart();
1654 startBuf = SM->getCharacterData(startLoc);
1655 assert((*startBuf == '@') && "bogus @finally start");
1656
1657 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001658 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001659
1660 Stmt *body = finalStmt->getFinallyBody();
1661 SourceLocation startLoc = body->getLocStart();
1662 SourceLocation endLoc = body->getLocEnd();
Chris Lattner690c2872008-04-08 05:52:18 +00001663 assert(*SM->getCharacterData(startLoc) == '{' &&
1664 "bogus @finally body location");
1665 assert(*SM->getCharacterData(endLoc) == '}' &&
1666 "bogus @finally body location");
Steve Naroffe9f69842007-11-07 04:08:17 +00001667
1668 startLoc = startLoc.getFileLocWithOffset(1);
1669 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001670 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001671 endLoc = endLoc.getFileLocWithOffset(-1);
1672 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001673 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001674
1675 // Set lastCurlyLoc
1676 lastCurlyLoc = body->getLocEnd();
Steve Naroff43964fb2008-12-05 17:03:39 +00001677
1678 // Now check for any return/continue/go statements within the @try.
1679 WarnAboutReturnGotoContinueOrBreakStmts(S->getTryBody());
Steve Naroff31325c12008-09-11 15:29:03 +00001680 } else { /* no finally clause - make sure we synthesize an implicit one */
1681 buf = "{ /* implicit finally clause */\n";
1682 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1683 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1684 buf += "}";
1685 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001686 }
1687 // Now emit the final closing curly brace...
1688 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1689 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001690 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001691 return 0;
1692}
1693
Steve Naroff44e81222008-04-14 22:03:09 +00001694Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001695 return 0;
1696}
1697
Steve Naroff44e81222008-04-14 22:03:09 +00001698Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001699 return 0;
1700}
1701
Chris Lattnerb1548372008-01-31 19:37:57 +00001702// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001703// the throw expression is typically a message expression that's already
1704// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff44e81222008-04-14 22:03:09 +00001705Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001706 // Get the start location and compute the semi location.
1707 SourceLocation startLoc = S->getLocStart();
1708 const char *startBuf = SM->getCharacterData(startLoc);
1709
1710 assert((*startBuf == '@') && "bogus @throw location");
1711
1712 std::string buf;
1713 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001714 if (S->getThrowExpr())
1715 buf = "objc_exception_throw(";
1716 else // add an implicit argument
1717 buf = "objc_exception_throw(_caught";
Steve Naroff3de6eaa2008-07-25 15:41:30 +00001718
1719 // handle "@ throw" correctly.
1720 const char *wBuf = strchr(startBuf, 'w');
1721 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1722 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
1723
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001724 const char *semiBuf = strchr(startBuf, ';');
1725 assert((*semiBuf == ';') && "@throw: can't find ';'");
1726 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1727 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001728 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001729 return 0;
1730}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001731
Steve Naroff44e81222008-04-14 22:03:09 +00001732Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001733 // Create a new string expression.
1734 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001735 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00001736 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattneraa491192009-02-18 06:40:38 +00001737 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1738 StrEncoding.length(), false,StrType,
1739 SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001740 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001741
Chris Lattner4478db92007-11-30 22:53:43 +00001742 // Replace this subexpr in the parent.
Steve Naroff102c3f22008-12-04 23:50:32 +00001743 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner0021f452007-10-24 16:57:36 +00001744 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001745}
1746
Steve Naroff44e81222008-04-14 22:03:09 +00001747Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff95f6bce2008-12-22 22:16:07 +00001748 if (!SelGetUidFunctionDecl)
1749 SynthSelGetUidFunctionDecl();
Steve Naroff296b74f2007-11-05 14:50:49 +00001750 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1751 // Create a call to sel_registerName("selName").
1752 llvm::SmallVector<Expr*, 8> SelExprs;
1753 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00001754 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00001755 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00001756 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00001757 false, argType, SourceLocation()));
Steve Naroff296b74f2007-11-05 14:50:49 +00001758 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1759 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001760 ReplaceStmt(Exp, SelExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00001761 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff296b74f2007-11-05 14:50:49 +00001762 return SelExp;
1763}
1764
Steve Naroff44e81222008-04-14 22:03:09 +00001765CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff71226032007-10-24 22:48:43 +00001766 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001767 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001768 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001769
1770 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001771 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001772
1773 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001774 QualType pToFunc = Context->getPointerType(msgSendType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00001775 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc, DRE,
Douglas Gregor70d26122008-11-12 17:17:38 +00001776 /*isLvalue=*/false);
Steve Naroffe9780582007-10-23 23:50:29 +00001777
1778 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001779
Ted Kremenek362abcd2009-02-09 20:51:47 +00001780 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1781 SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001782}
1783
Steve Naroffc8a92d12007-11-01 13:24:47 +00001784static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1785 const char *&startRef, const char *&endRef) {
1786 while (startBuf < endBuf) {
1787 if (*startBuf == '<')
1788 startRef = startBuf; // mark the start.
1789 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001790 if (startRef && *startRef == '<') {
1791 endRef = startBuf; // mark the end.
1792 return true;
1793 }
1794 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001795 }
1796 startBuf++;
1797 }
1798 return false;
1799}
1800
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001801static void scanToNextArgument(const char *&argRef) {
1802 int angle = 0;
1803 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1804 if (*argRef == '<')
1805 angle++;
1806 else if (*argRef == '>')
1807 angle--;
1808 argRef++;
1809 }
1810 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1811}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001812
Steve Naroff44e81222008-04-14 22:03:09 +00001813bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001814
Ted Kremenek42730c52008-01-07 19:49:32 +00001815 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001816 return true;
1817
Steve Naroffc8a92d12007-11-01 13:24:47 +00001818 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001819 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001820 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001821 return true; // we have "Class <Protocol> *".
1822 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001823 return false;
1824}
1825
Steve Naroffd06c88d2008-07-29 18:15:38 +00001826void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1827 QualType Type = E->getType();
1828 if (needToScanForQualifiers(Type)) {
Steve Narofff31ece92008-11-19 21:15:47 +00001829 SourceLocation Loc, EndLoc;
1830
1831 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1832 Loc = ECE->getLParenLoc();
1833 EndLoc = ECE->getRParenLoc();
1834 } else {
1835 Loc = E->getLocStart();
1836 EndLoc = E->getLocEnd();
1837 }
1838 // This will defend against trying to rewrite synthesized expressions.
1839 if (Loc.isInvalid() || EndLoc.isInvalid())
1840 return;
1841
Steve Naroffd06c88d2008-07-29 18:15:38 +00001842 const char *startBuf = SM->getCharacterData(Loc);
Steve Narofff31ece92008-11-19 21:15:47 +00001843 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroffd06c88d2008-07-29 18:15:38 +00001844 const char *startRef = 0, *endRef = 0;
1845 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1846 // Get the locations of the startRef, endRef.
1847 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1848 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1849 // Comment out the protocol references.
1850 InsertText(LessLoc, "/*", 2);
1851 InsertText(GreaterLoc, "*/", 2);
1852 }
1853 }
1854}
1855
Steve Naroff44e81222008-04-14 22:03:09 +00001856void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001857 SourceLocation Loc;
1858 QualType Type;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001859 const FunctionProtoType *proto = 0;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001860 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1861 Loc = VD->getLocation();
1862 Type = VD->getType();
1863 }
1864 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1865 Loc = FD->getLocation();
1866 // Check for ObjC 'id' and class types that have been adorned with protocol
1867 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1868 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1869 assert(funcType && "missing function type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00001870 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001871 if (!proto)
1872 return;
1873 Type = proto->getResultType();
1874 }
1875 else
1876 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001877
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001878 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001879 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001880
1881 const char *endBuf = SM->getCharacterData(Loc);
1882 const char *startBuf = endBuf;
Steve Naroffff2fa192008-05-31 05:02:17 +00001883 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001884 startBuf--; // scan backward (from the decl location) for return type.
1885 const char *startRef = 0, *endRef = 0;
1886 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1887 // Get the locations of the startRef, endRef.
1888 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1889 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1890 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001891 InsertText(LessLoc, "/*", 2);
1892 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001893 }
1894 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001895 if (!proto)
1896 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001897 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001898 const char *startBuf = SM->getCharacterData(Loc);
1899 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001900 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1901 if (needToScanForQualifiers(proto->getArgType(i))) {
1902 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001903
Steve Naroffc8a92d12007-11-01 13:24:47 +00001904 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001905 // scan forward (from the decl location) for argument types.
1906 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001907 const char *startRef = 0, *endRef = 0;
1908 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1909 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001910 SourceLocation LessLoc =
1911 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1912 SourceLocation GreaterLoc =
1913 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001914 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001915 InsertText(LessLoc, "/*", 2);
1916 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001917 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001918 startBuf = ++endBuf;
1919 }
1920 else {
Steve Naroff6a1d88b2008-08-06 15:58:23 +00001921 // If the function name is derived from a macro expansion, then the
1922 // argument buffer will not follow the name. Need to speak with Chris.
1923 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001924 startBuf++; // scan forward (from the decl location) for argument types.
1925 startBuf++;
1926 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001927 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001928}
1929
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001930// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff44e81222008-04-14 22:03:09 +00001931void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001932 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1933 llvm::SmallVector<QualType, 16> ArgTys;
1934 ArgTys.push_back(Context->getPointerType(
1935 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001936 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001937 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001938 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001939 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001940 SourceLocation(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001941 SelGetUidIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001942 FunctionDecl::Extern, false);
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001943}
1944
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001945// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
Steve Naroff44e81222008-04-14 22:03:09 +00001946void RewriteObjC::SynthGetProtocolFunctionDecl() {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001947 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1948 llvm::SmallVector<QualType, 16> ArgTys;
1949 ArgTys.push_back(Context->getPointerType(
1950 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001951 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001952 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001953 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001954 GetProtocolFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001955 SourceLocation(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001956 SelGetProtoIdent, getFuncType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001957 FunctionDecl::Extern, false);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001958}
1959
Steve Naroff44e81222008-04-14 22:03:09 +00001960void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001961 // declared in <objc/objc.h>
Douglas Gregor7339c9e2009-01-09 01:47:02 +00001962 if (FD->getIdentifier() &&
1963 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001964 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001965 return;
1966 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001967 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001968}
1969
Steve Naroffbec4bf52008-03-11 17:37:02 +00001970// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff44e81222008-04-14 22:03:09 +00001971void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffbec4bf52008-03-11 17:37:02 +00001972 if (SuperContructorFunctionDecl)
1973 return;
Steve Naroff12673622008-12-23 20:11:22 +00001974 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffbec4bf52008-03-11 17:37:02 +00001975 llvm::SmallVector<QualType, 16> ArgTys;
1976 QualType argT = Context->getObjCIdType();
1977 assert(!argT.isNull() && "Can't find 'id' type");
1978 ArgTys.push_back(argT);
1979 ArgTys.push_back(argT);
1980 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1981 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00001982 false, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00001983 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00001984 SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00001985 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001986 FunctionDecl::Extern, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00001987}
1988
Steve Naroff02a82aa2007-10-30 23:14:51 +00001989// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00001990void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001991 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1992 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001993 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001994 assert(!argT.isNull() && "Can't find 'id' type");
1995 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001996 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001997 assert(!argT.isNull() && "Can't find 'SEL' type");
1998 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001999 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002000 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002001 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002002 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002003 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002004 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002005 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002006}
2007
Steve Naroff764c1ae2007-11-15 10:28:18 +00002008// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002009void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002010 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2011 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002012 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002013 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002014 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002015 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2016 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2017 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002018 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002019 assert(!argT.isNull() && "Can't find 'SEL' type");
2020 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002021 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002022 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002023 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002024 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002025 SourceLocation(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00002026 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002027 FunctionDecl::Extern, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002028}
2029
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002030// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002031void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002032 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2033 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002034 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002035 assert(!argT.isNull() && "Can't find 'id' type");
2036 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002037 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002038 assert(!argT.isNull() && "Can't find 'SEL' type");
2039 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002040 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002041 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002042 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002043 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002044 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002045 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002046 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002047}
2048
2049// SynthMsgSendSuperStretFunctionDecl -
2050// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002051void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002052 IdentifierInfo *msgSendIdent =
2053 &Context->Idents.get("objc_msgSendSuper_stret");
2054 llvm::SmallVector<QualType, 16> ArgTys;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002055 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002056 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002057 &Context->Idents.get("objc_super"));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002058 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2059 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2060 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002061 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002062 assert(!argT.isNull() && "Can't find 'SEL' type");
2063 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002064 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002065 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002066 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002067 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner4c7802b2008-03-15 21:24:04 +00002068 SourceLocation(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002069 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002070 FunctionDecl::Extern, false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002071}
2072
Steve Naroff31316a12008-05-08 22:02:18 +00002073// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff44e81222008-04-14 22:03:09 +00002074void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002075 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2076 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00002077 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002078 assert(!argT.isNull() && "Can't find 'id' type");
2079 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00002080 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002081 assert(!argT.isNull() && "Can't find 'SEL' type");
2082 ArgTys.push_back(argT);
Steve Naroff31316a12008-05-08 22:02:18 +00002083 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002084 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002085 true /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002086 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002087 SourceLocation(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002088 msgSendIdent, msgSendType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002089 FunctionDecl::Extern, false);
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002090}
2091
Steve Naroff02a82aa2007-10-30 23:14:51 +00002092// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002093void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff02a82aa2007-10-30 23:14:51 +00002094 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2095 llvm::SmallVector<QualType, 16> ArgTys;
2096 ArgTys.push_back(Context->getPointerType(
2097 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002098 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002099 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002100 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002101 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002102 SourceLocation(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00002103 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002104 FunctionDecl::Extern, false);
Steve Naroff02a82aa2007-10-30 23:14:51 +00002105}
2106
Steve Naroff3b1caac2007-12-07 03:50:46 +00002107// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff44e81222008-04-14 22:03:09 +00002108void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002109 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2110 llvm::SmallVector<QualType, 16> ArgTys;
2111 ArgTys.push_back(Context->getPointerType(
2112 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00002113 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002114 &ArgTys[0], ArgTys.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002115 false /*isVariadic*/, 0);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002116 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnereee57c02008-04-04 06:12:32 +00002117 SourceLocation(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00002118 getClassIdent, getClassType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002119 FunctionDecl::Extern, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002120}
2121
Steve Naroff44e81222008-04-14 22:03:09 +00002122Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002123 QualType strType = getConstantStringStructType();
2124
2125 std::string S = "__NSConstantStringImpl_";
Steve Naroffa1f00992008-05-31 03:35:42 +00002126
2127 std::string tmpName = InFileName;
2128 unsigned i;
2129 for (i=0; i < tmpName.length(); i++) {
2130 char c = tmpName.at(i);
2131 // replace any non alphanumeric characters with '_'.
2132 if (!isalpha(c) && (c < '0' || c > '9'))
2133 tmpName[i] = '_';
2134 }
2135 S += tmpName;
2136 S += "_";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002137 S += utostr(NumObjCStringLiterals++);
2138
Steve Narofffef037c2008-03-27 22:29:16 +00002139 Preamble += "static __NSConstantStringImpl " + S;
2140 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2141 Preamble += "0x000007c8,"; // utf8_str
Steve Naroff47e7fa22008-03-15 00:55:56 +00002142 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek7b6f67b2008-09-13 05:16:45 +00002143 std::string prettyBufS;
2144 llvm::raw_string_ostream prettyBuf(prettyBufS);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002145 Exp->getString()->printPretty(prettyBuf);
Steve Narofffef037c2008-03-27 22:29:16 +00002146 Preamble += prettyBuf.str();
2147 Preamble += ",";
Steve Naroff64bce352008-03-15 01:36:04 +00002148 // The minus 2 removes the begin/end double quotes.
Steve Narofffef037c2008-03-27 22:29:16 +00002149 Preamble += utostr(prettyBuf.str().size()-2) + "};\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +00002150
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00002151 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002152 &Context->Idents.get(S.c_str()), strType,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002153 VarDecl::Static);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002154 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2155 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Steve Naroff47e7fa22008-03-15 00:55:56 +00002156 Context->getPointerType(DRE->getType()),
2157 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00002158 // cast to NSConstantString *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002159 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(), Unop,
Steve Naroff7f1412d2008-11-03 23:29:32 +00002160 Exp->getType(), SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00002161 ReplaceStmt(Exp, cast);
Steve Naroff102c3f22008-12-04 23:50:32 +00002162 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffabb96362007-11-08 14:30:50 +00002163 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00002164}
2165
Steve Naroff44e81222008-04-14 22:03:09 +00002166ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00002167 // check if we are sending a message to 'super'
Douglas Gregor5d764842009-01-09 17:18:27 +00002168 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Chris Lattnere4650482008-03-15 06:12:44 +00002169
Douglas Gregord8606632008-11-04 14:56:14 +00002170 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
2171 const PointerType *PT = Super->getType()->getAsPointerType();
Chris Lattner4423d372008-06-21 18:04:54 +00002172 assert(PT);
2173 ObjCInterfaceType *IT = cast<ObjCInterfaceType>(PT->getPointeeType());
2174 return IT->getDecl();
2175 }
2176 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002177}
2178
2179// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff44e81222008-04-14 22:03:09 +00002180QualType RewriteObjC::getSuperStructType() {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002181 if (!SuperStructDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002182 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002183 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002184 &Context->Idents.get("objc_super"));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002185 QualType FieldTypes[2];
2186
2187 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00002188 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002189 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00002190 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002191
Steve Naroff764c1ae2007-11-15 10:28:18 +00002192 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002193 for (unsigned i = 0; i < 2; ++i) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002194 SuperStructDecl->addDecl(*Context,
2195 FieldDecl::Create(*Context, SuperStructDecl,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002196 SourceLocation(), 0,
2197 FieldTypes[i], /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002198 /*Mutable=*/false));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002199 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002200
Douglas Gregor8acb7272008-12-11 16:49:14 +00002201 SuperStructDecl->completeDefinition(*Context);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002202 }
2203 return Context->getTagDeclType(SuperStructDecl);
2204}
2205
Steve Naroff44e81222008-04-14 22:03:09 +00002206QualType RewriteObjC::getConstantStringStructType() {
Steve Naroff47e7fa22008-03-15 00:55:56 +00002207 if (!ConstantStringDecl) {
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002208 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner58114f02008-03-15 21:32:50 +00002209 SourceLocation(),
Ted Kremenek2c984042008-09-05 01:34:33 +00002210 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroff47e7fa22008-03-15 00:55:56 +00002211 QualType FieldTypes[4];
2212
2213 // struct objc_object *receiver;
2214 FieldTypes[0] = Context->getObjCIdType();
2215 // int flags;
2216 FieldTypes[1] = Context->IntTy;
2217 // char *str;
2218 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2219 // long length;
2220 FieldTypes[3] = Context->LongTy;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002221
Steve Naroff47e7fa22008-03-15 00:55:56 +00002222 // Create fields
Douglas Gregor8acb7272008-12-11 16:49:14 +00002223 for (unsigned i = 0; i < 4; ++i) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002224 ConstantStringDecl->addDecl(*Context,
2225 FieldDecl::Create(*Context,
Douglas Gregor8acb7272008-12-11 16:49:14 +00002226 ConstantStringDecl,
2227 SourceLocation(), 0,
2228 FieldTypes[i],
2229 /*BitWidth=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002230 /*Mutable=*/true));
Douglas Gregor8acb7272008-12-11 16:49:14 +00002231 }
2232
2233 ConstantStringDecl->completeDefinition(*Context);
Steve Naroff47e7fa22008-03-15 00:55:56 +00002234 }
2235 return Context->getTagDeclType(ConstantStringDecl);
2236}
2237
Steve Naroff44e81222008-04-14 22:03:09 +00002238Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00002239 if (!SelGetUidFunctionDecl)
2240 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002241 if (!MsgSendFunctionDecl)
2242 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002243 if (!MsgSendSuperFunctionDecl)
2244 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002245 if (!MsgSendStretFunctionDecl)
2246 SynthMsgSendStretFunctionDecl();
2247 if (!MsgSendSuperStretFunctionDecl)
2248 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002249 if (!MsgSendFpretFunctionDecl)
2250 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00002251 if (!GetClassFunctionDecl)
2252 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002253 if (!GetMetaClassFunctionDecl)
2254 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002255
Steve Naroff764c1ae2007-11-15 10:28:18 +00002256 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002257 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2258 // May need to use objc_msgSend_stret() as well.
2259 FunctionDecl *MsgSendStretFlavor = 0;
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002260 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2261 QualType resultType = OMD->getResultType();
Chris Lattnerb724ab22008-07-26 22:36:27 +00002262 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002263 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattnerb724ab22008-07-26 22:36:27 +00002264 else if (resultType->isRealFloatingType())
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00002265 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002266 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00002267
Steve Naroff71226032007-10-24 22:48:43 +00002268 // Synthesize a call to objc_msgSend().
2269 llvm::SmallVector<Expr*, 8> MsgExprs;
2270 IdentifierInfo *clsName = Exp->getClassName();
2271
2272 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2273 if (clsName) { // class message.
Steve Naroff91a69202008-07-24 19:44:33 +00002274 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2275 // the 'super' idiom within a class method.
Steve Naroff3b1caac2007-12-07 03:50:46 +00002276 if (!strcmp(clsName->getName(), "super")) {
2277 MsgSendFlavor = MsgSendSuperFunctionDecl;
2278 if (MsgSendStretFlavor)
2279 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2280 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2281
Ted Kremenek42730c52008-01-07 19:49:32 +00002282 ObjCInterfaceDecl *SuperDecl =
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002283 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff3b1caac2007-12-07 03:50:46 +00002284
2285 llvm::SmallVector<Expr*, 4> InitExprs;
2286
2287 // set the receiver to self, the first argument to all methods.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002288 InitExprs.push_back(new (Context) DeclRefExpr(
Steve Naroff38a9e3f2008-10-27 17:20:55 +00002289 CurMethodDef->getSelfDecl(),
Chris Lattner8c7c6a12008-06-17 18:05:57 +00002290 Context->getObjCIdType(),
2291 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002292 llvm::SmallVector<Expr*, 8> ClsExprs;
2293 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002294 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002295 SuperDecl->getIdentifier()->getName(),
2296 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002297 false, argType, SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002298 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2299 &ClsExprs[0],
2300 ClsExprs.size());
2301 // To turn off a warning, type-cast to 'id'
Douglas Gregor21a04f32008-10-27 19:41:14 +00002302 InitExprs.push_back( // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002303 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002304 Cls, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002305 SourceLocation(), SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002306 // struct objc_super
2307 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00002308 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00002309
Steve Naroffdee066b2008-03-11 18:14:26 +00002310 if (LangOpts.Microsoft) {
2311 SynthSuperContructorFunctionDecl();
2312 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002313 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffdee066b2008-03-11 18:14:26 +00002314 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002315 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2316 InitExprs.size(),
2317 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002318 // The code for super is a little tricky to prevent collision with
2319 // the structure definition in the header. The rewriter has it's own
2320 // internal definition (__rw_objc_super) that is uses. This is why
2321 // we need the cast below. For example:
2322 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2323 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002324 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002325 Context->getPointerType(SuperRep->getType()),
2326 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002327 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002328 SuperRep, Context->getPointerType(superType),
2329 SourceLocation(), SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002330 } else {
2331 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002332 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffdee066b2008-03-11 18:14:26 +00002333 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002334 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002335 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner71ca8c82008-10-26 23:43:26 +00002336 false);
Steve Naroff12673622008-12-23 20:11:22 +00002337 // struct objc_super *
Ted Kremenek0c97e042009-02-07 01:47:29 +00002338 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002339 Context->getPointerType(SuperRep->getType()),
2340 SourceLocation());
Steve Naroffdee066b2008-03-11 18:14:26 +00002341 }
Steve Naroff12673622008-12-23 20:11:22 +00002342 MsgExprs.push_back(SuperRep);
Steve Naroff3b1caac2007-12-07 03:50:46 +00002343 } else {
2344 llvm::SmallVector<Expr*, 8> ClsExprs;
2345 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002346 ClsExprs.push_back(StringLiteral::Create(*Context,
2347 clsName->getName(),
2348 clsName->getLength(),
2349 false, argType,
2350 SourceLocation()));
Steve Naroff3b1caac2007-12-07 03:50:46 +00002351 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2352 &ClsExprs[0],
2353 ClsExprs.size());
2354 MsgExprs.push_back(Cls);
2355 }
Steve Naroff885e2122007-11-14 23:54:14 +00002356 } else { // instance message.
2357 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00002358
Ted Kremenek42730c52008-01-07 19:49:32 +00002359 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00002360 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002361 if (MsgSendStretFlavor)
2362 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00002363 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2364
2365 llvm::SmallVector<Expr*, 4> InitExprs;
2366
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002367 InitExprs.push_back(
Ted Kremenek0c97e042009-02-07 01:47:29 +00002368 new (Context) CStyleCastExpr(Context->getObjCIdType(),
2369 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff23528612008-07-16 22:35:27 +00002370 Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002371 SourceLocation()),
2372 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002373 SourceLocation(), SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002374
2375 llvm::SmallVector<Expr*, 8> ClsExprs;
2376 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002377 ClsExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002378 SuperDecl->getIdentifier()->getName(),
2379 SuperDecl->getIdentifier()->getLength(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002380 false, argType, SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002381 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002382 &ClsExprs[0],
2383 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00002384 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00002385 InitExprs.push_back(
Douglas Gregor21a04f32008-10-27 19:41:14 +00002386 // set 'super class', using objc_getClass().
Ted Kremenek0c97e042009-02-07 01:47:29 +00002387 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002388 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff764c1ae2007-11-15 10:28:18 +00002389 // struct objc_super
2390 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00002391 Expr *SuperRep;
2392
2393 if (LangOpts.Microsoft) {
2394 SynthSuperContructorFunctionDecl();
2395 // Simulate a contructor call...
Ted Kremenek0c97e042009-02-07 01:47:29 +00002396 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffbec4bf52008-03-11 17:37:02 +00002397 superType, SourceLocation());
Ted Kremenek362abcd2009-02-09 20:51:47 +00002398 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2399 InitExprs.size(),
2400 superType, SourceLocation());
Steve Naroff12673622008-12-23 20:11:22 +00002401 // The code for super is a little tricky to prevent collision with
2402 // the structure definition in the header. The rewriter has it's own
2403 // internal definition (__rw_objc_super) that is uses. This is why
2404 // we need the cast below. For example:
2405 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2406 //
Ted Kremenek0c97e042009-02-07 01:47:29 +00002407 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Steve Naroff12673622008-12-23 20:11:22 +00002408 Context->getPointerType(SuperRep->getType()),
2409 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002410 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Steve Naroff12673622008-12-23 20:11:22 +00002411 SuperRep, Context->getPointerType(superType),
2412 SourceLocation(), SourceLocation());
Steve Naroffbec4bf52008-03-11 17:37:02 +00002413 } else {
2414 // (struct objc_super) { <exprs from above> }
Ted Kremenek0c97e042009-02-07 01:47:29 +00002415 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
Steve Naroffbec4bf52008-03-11 17:37:02 +00002416 &InitExprs[0], InitExprs.size(),
Douglas Gregorf603b472009-01-28 21:54:33 +00002417 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002418 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroffbec4bf52008-03-11 17:37:02 +00002419 }
Steve Naroff12673622008-12-23 20:11:22 +00002420 MsgExprs.push_back(SuperRep);
Steve Naroff764c1ae2007-11-15 10:28:18 +00002421 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002422 // Remove all type-casts because it may contain objc-style types; e.g.
2423 // Foo<Proto> *.
Douglas Gregor035d0882008-10-28 15:36:24 +00002424 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00002425 recExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002426 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(), recExpr,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002427 Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002428 SourceLocation(), SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00002429 MsgExprs.push_back(recExpr);
2430 }
Steve Naroff885e2122007-11-14 23:54:14 +00002431 }
Steve Naroff0add5d22007-11-03 11:27:19 +00002432 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00002433 llvm::SmallVector<Expr*, 8> SelExprs;
2434 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002435 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002436 Exp->getSelector().getAsString().c_str(),
Chris Lattner3a8f2942008-11-24 03:33:13 +00002437 Exp->getSelector().getAsString().size(),
Chris Lattnerc3144742009-02-18 05:49:11 +00002438 false, argType, SourceLocation()));
Steve Naroff71226032007-10-24 22:48:43 +00002439 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2440 &SelExprs[0], SelExprs.size());
2441 MsgExprs.push_back(SelExp);
2442
2443 // Now push any user supplied arguments.
2444 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002445 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002446 // Make all implicit casts explicit...ICE comes in handy:-)
2447 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2448 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor21a04f32008-10-27 19:41:14 +00002449 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002450 ? Context->getObjCIdType()
Douglas Gregor21a04f32008-10-27 19:41:14 +00002451 : ICE->getType();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002452 userExpr = new (Context) CStyleCastExpr(type, userExpr, type, SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002453 }
2454 // Make id<P...> cast into an 'id' cast.
Douglas Gregor035d0882008-10-28 15:36:24 +00002455 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002456 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor035d0882008-10-28 15:36:24 +00002457 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002458 userExpr = CE->getSubExpr();
Ted Kremenek0c97e042009-02-07 01:47:29 +00002459 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Douglas Gregor21a04f32008-10-27 19:41:14 +00002460 userExpr, Context->getObjCIdType(),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002461 SourceLocation(), SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002462 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002463 }
Steve Naroff885e2122007-11-14 23:54:14 +00002464 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002465 // We've transferred the ownership to MsgExprs. Null out the argument in
2466 // the original expression, since we will delete it below.
2467 Exp->setArg(i, 0);
2468 }
Steve Naroff0744c472007-11-04 22:37:50 +00002469 // Generate the funky cast.
2470 CastExpr *cast;
2471 llvm::SmallVector<QualType, 8> ArgTypes;
2472 QualType returnType;
2473
2474 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002475 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2476 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2477 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002478 ArgTypes.push_back(Context->getObjCIdType());
2479 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002480 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002481 // Push any user argument types.
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002482 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2483 E = OMD->param_end(); PI != E; ++PI) {
2484 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Ted Kremenek42730c52008-01-07 19:49:32 +00002485 ? Context->getObjCIdType()
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002486 : (*PI)->getType();
Steve Naroff66c842f2008-10-29 14:49:46 +00002487 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00002488 if (isTopLevelBlockPointerType(t)) {
Steve Naroff66c842f2008-10-29 14:49:46 +00002489 const BlockPointerType *BPT = t->getAsBlockPointerType();
2490 t = Context->getPointerType(BPT->getPointeeType());
2491 }
Steve Naroff4242b972007-11-05 14:36:37 +00002492 ArgTypes.push_back(t);
2493 }
Chris Lattner5c6b2c62009-02-20 18:43:26 +00002494 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2495 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002496 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002497 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002498 }
2499 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002500 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002501
2502 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002503 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002504 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002505
2506 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2507 // If we don't do this cast, we get the following bizarre warning/note:
2508 // xx.m:13: warning: function called through a non-compatible type
2509 // xx.m:13: note: if this code is reached, the program will abort
Ted Kremenek0c97e042009-02-07 01:47:29 +00002510 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), DRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002511 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002512 SourceLocation(), SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002513
Steve Naroff0744c472007-11-04 22:37:50 +00002514 // Now do the "normal" pointer to function cast.
2515 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002516 &ArgTypes[0], ArgTypes.size(),
Steve Naroff3b8b4e32008-03-18 02:02:04 +00002517 // If we don't have a method decl, force a variadic cast.
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002518 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroff0744c472007-11-04 22:37:50 +00002519 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002520 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002521
2522 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002523 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Steve Naroff0744c472007-11-04 22:37:50 +00002524
2525 const FunctionType *FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002526 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2527 MsgExprs.size(),
2528 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002529 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002530 if (MsgSendStretFlavor) {
2531 // We have the method which returns a struct/union. Must also generate
2532 // call to objc_msgSend_stret and hang both varieties on a conditional
2533 // expression which dictate which one to envoke depending on size of
2534 // method's return type.
2535
2536 // Create a reference to the objc_msgSend_stret() declaration.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002537 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002538 SourceLocation());
2539 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Ted Kremenek0c97e042009-02-07 01:47:29 +00002540 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy), STDRE,
Douglas Gregor21a04f32008-10-27 19:41:14 +00002541 Context->getPointerType(Context->VoidTy),
Steve Naroff7f1412d2008-11-03 23:29:32 +00002542 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002543 // Now do the "normal" pointer to function cast.
2544 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002545 &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00002546 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002547 castType = Context->getPointerType(castType);
Ted Kremenek0c97e042009-02-07 01:47:29 +00002548 cast = new (Context) CStyleCastExpr(castType, cast, castType, SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002549
2550 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002551 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002552
2553 FT = msgSendType->getAsFunctionType();
Ted Kremenek362abcd2009-02-09 20:51:47 +00002554 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2555 MsgExprs.size(),
2556 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002557
2558 // Build sizeof(returnType)
Douglas Gregor396f1142009-03-13 21:01:28 +00002559 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
2560 returnType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002561 Context->getSizeType(),
2562 SourceLocation(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002563 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2564 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2565 // For X86 it is more complicated and some kind of target specific routine
2566 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002567 unsigned IntSize =
2568 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Ted Kremenek0c97e042009-02-07 01:47:29 +00002569 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002570 Context->IntTy,
2571 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00002572 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002573 BinaryOperator::LE,
2574 Context->IntTy,
2575 SourceLocation());
2576 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2577 ConditionalOperator *CondExpr =
Ted Kremenek0c97e042009-02-07 01:47:29 +00002578 new (Context) ConditionalOperator(lessThanExpr, CE, STCE, returnType);
2579 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002580 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002581 return ReplacingStmt;
2582}
2583
Steve Naroff44e81222008-04-14 22:03:09 +00002584Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002585 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroffe8efe892008-10-27 20:54:44 +00002586
Steve Naroff0e948412008-12-04 16:24:46 +00002587 //ReplacingStmt->dump();
Steve Naroff71226032007-10-24 22:48:43 +00002588 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002589 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002590
Steve Naroff102c3f22008-12-04 23:50:32 +00002591 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002592 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002593}
2594
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002595/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2596/// call to objc_getProtocol("proto-name").
Steve Naroff44e81222008-04-14 22:03:09 +00002597Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002598 if (!GetProtocolFunctionDecl)
2599 SynthGetProtocolFunctionDecl();
2600 // Create a call to objc_getProtocol("ProtocolName").
2601 llvm::SmallVector<Expr*, 8> ProtoExprs;
2602 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattneraa491192009-02-18 06:40:38 +00002603 ProtoExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek4f530a92009-02-06 19:55:15 +00002604 Exp->getProtocol()->getNameAsCString(),
2605 strlen(Exp->getProtocol()->getNameAsCString()),
Chris Lattnerc3144742009-02-18 05:49:11 +00002606 false, argType, SourceLocation()));
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002607 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2608 &ProtoExprs[0],
2609 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002610 ReplaceStmt(Exp, ProtoExp);
Steve Naroff102c3f22008-12-04 23:50:32 +00002611 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002612 return ProtoExp;
2613
2614}
2615
Steve Naroffef82b742008-05-31 14:15:04 +00002616bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
2617 const char *endBuf) {
2618 while (startBuf < endBuf) {
2619 if (*startBuf == '#') {
2620 // Skip whitespace.
2621 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2622 ;
2623 if (!strncmp(startBuf, "if", strlen("if")) ||
2624 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2625 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2626 !strncmp(startBuf, "define", strlen("define")) ||
2627 !strncmp(startBuf, "undef", strlen("undef")) ||
2628 !strncmp(startBuf, "else", strlen("else")) ||
2629 !strncmp(startBuf, "elif", strlen("elif")) ||
2630 !strncmp(startBuf, "endif", strlen("endif")) ||
2631 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2632 !strncmp(startBuf, "include", strlen("include")) ||
2633 !strncmp(startBuf, "import", strlen("import")) ||
2634 !strncmp(startBuf, "include_next", strlen("include_next")))
2635 return true;
2636 }
2637 startBuf++;
2638 }
2639 return false;
2640}
2641
Ted Kremenek42730c52008-01-07 19:49:32 +00002642/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002643/// an objective-c class with ivars.
Steve Naroff44e81222008-04-14 22:03:09 +00002644void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002645 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002646 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Chris Lattnerd120b9e2008-11-24 03:54:41 +00002647 assert(CDecl->getNameAsCString() &&
Douglas Gregor24afd4a2008-11-17 14:58:09 +00002648 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002649 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002650 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002651 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002652 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerec4979b2008-03-16 21:08:55 +00002653 int NumIvars = CDecl->ivar_size();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002654 SourceLocation LocStart = CDecl->getLocStart();
2655 SourceLocation LocEnd = CDecl->getLocEnd();
2656
2657 const char *startBuf = SM->getCharacterData(LocStart);
2658 const char *endBuf = SM->getCharacterData(LocEnd);
Steve Naroffef82b742008-05-31 14:15:04 +00002659
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002660 // If no ivars and no root or if its root, directly or indirectly,
2661 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerec4979b2008-03-16 21:08:55 +00002662 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2663 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattnere1be6022009-04-14 23:22:57 +00002664 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002665 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002666 return;
2667 }
2668
2669 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002670 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002671 Result += "\nstruct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002672 Result += CDecl->getNameAsString();
Steve Naroffde0da102008-03-10 23:16:54 +00002673 if (LangOpts.Microsoft)
2674 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002675
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002676 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002677 const char *cursor = strchr(startBuf, '{');
2678 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002679 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffef82b742008-05-31 14:15:04 +00002680 // If the buffer contains preprocessor directives, we do more fine-grained
2681 // rewrites. This is intended to fix code that looks like (which occurs in
2682 // NSURL.h, for example):
2683 //
2684 // #ifdef XYZ
2685 // @interface Foo : NSObject
2686 // #else
2687 // @interface FooBar : NSObject
2688 // #endif
2689 // {
2690 // int i;
2691 // }
2692 // @end
2693 //
2694 // This clause is segregated to avoid breaking the common case.
2695 if (BufferContainsPPDirectives(startBuf, cursor)) {
2696 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
2697 CDecl->getClassLoc();
2698 const char *endHeader = SM->getCharacterData(L);
Chris Lattnere1be6022009-04-14 23:22:57 +00002699 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffef82b742008-05-31 14:15:04 +00002700
Chris Lattner179fd522009-02-20 18:18:36 +00002701 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffef82b742008-05-31 14:15:04 +00002702 // advance to the end of the referenced protocols.
2703 while (endHeader < cursor && *endHeader != '>') endHeader++;
2704 endHeader++;
2705 }
2706 // rewrite the original header
2707 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2708 } else {
2709 // rewrite the original header *without* disturbing the '{'
2710 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
2711 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002712 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002713 Result = "\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002714 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002715 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002716 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002717 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002718
2719 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002720 SourceLocation OnePastCurly =
2721 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2722 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002723 }
2724 cursor++; // past '{'
2725
2726 // Now comment out any visibility specifiers.
2727 while (cursor < endBuf) {
2728 if (*cursor == '@') {
2729 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002730 // Skip whitespace.
2731 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2732 /*scan*/;
2733
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002734 // FIXME: presence of @public, etc. inside comment results in
2735 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002736 if (!strncmp(cursor, "public", strlen("public")) ||
2737 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffa93924a2008-04-04 22:34:24 +00002738 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002739 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002740 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002741 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002742 // FIXME: If there are cases where '<' is used in ivar declaration part
2743 // of user code, then scan the ivar list and use needToScanForQualifiers
2744 // for type checking.
2745 else if (*cursor == '<') {
2746 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002747 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002748 cursor = strchr(cursor, '>');
2749 cursor++;
2750 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002751 InsertText(atLoc, " */", 3);
Steve Naroff6449c6c2008-10-30 12:09:33 +00002752 } else if (*cursor == '^') { // rewrite block specifier.
2753 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2754 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002755 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002756 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002757 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002758 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002759 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002760 } else { // we don't have any instance variables - insert super struct.
Chris Lattnere1be6022009-04-14 23:22:57 +00002761 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002762 Result += " {\n struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002763 Result += RCDecl->getNameAsString();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002764 Result += "_IMPL ";
Chris Lattner271d4c22008-11-24 05:29:24 +00002765 Result += RCDecl->getNameAsString();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002766 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002767 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002768 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002769 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002770 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff04eaa192008-05-06 18:26:51 +00002771 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002772}
2773
Ted Kremenek42730c52008-01-07 19:49:32 +00002774// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002775/// class methods.
Douglas Gregorcd19b572009-04-23 01:02:12 +00002776template<typename MethodIterator>
2777void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2778 MethodIterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002779 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002780 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002781 const char *ClassName,
2782 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002783 if (MethodBegin == MethodEnd) return;
2784
Fariborz Jahanian04455192007-10-22 21:41:37 +00002785 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002786 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002787 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002788 SEL _cmd;
2789 char *method_types;
2790 void *_imp;
2791 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002792 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002793 Result += "\nstruct _objc_method {\n";
2794 Result += "\tSEL _cmd;\n";
2795 Result += "\tchar *method_types;\n";
2796 Result += "\tvoid *_imp;\n";
2797 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002798
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002799 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002800 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002801
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002802 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002803
2804 /* struct {
2805 struct _objc_method_list *next_method;
2806 int method_count;
2807 struct _objc_method method_list[];
2808 }
2809 */
Douglas Gregorcd19b572009-04-23 01:02:12 +00002810 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc723eec2008-03-11 00:12:29 +00002811 Result += "\nstatic struct {\n";
2812 Result += "\tstruct _objc_method_list *next_method;\n";
2813 Result += "\tint method_count;\n";
2814 Result += "\tstruct _objc_method method_list[";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002815 Result += utostr(NumMethods);
Steve Naroffc723eec2008-03-11 00:12:29 +00002816 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002817 Result += prefix;
2818 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2819 Result += "_METHODS_";
2820 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002821 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002822 Result += IsInstanceMethod ? "inst" : "cls";
2823 Result += "_meth\")))= ";
Douglas Gregorcd19b572009-04-23 01:02:12 +00002824 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002825
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002826 Result += "\t,{{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002827 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002828 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002829 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002830 Result += "\", \"";
2831 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002832 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002833 Result += MethodInternalNames[*MethodBegin];
2834 Result += "}\n";
2835 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2836 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002837 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002838 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002839 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002840 Result += "\", \"";
2841 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002842 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002843 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002844 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002845 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002846 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002847}
2848
Ted Kremenek42730c52008-01-07 19:49:32 +00002849/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
Chris Lattner0be08822008-07-21 21:32:27 +00002850void RewriteObjC::
2851RewriteObjCProtocolsMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
2852 const char *prefix,
2853 const char *ClassName,
2854 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002855 static bool objc_protocol_methods = false;
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002856 if (Protocols.empty()) return;
2857
2858 for (unsigned i = 0; i != Protocols.size(); i++) {
2859 ObjCProtocolDecl *PDecl = Protocols[i];
2860 // Output struct protocol_methods holder of method selector and type.
2861 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2862 /* struct protocol_methods {
2863 SEL _cmd;
2864 char *method_types;
2865 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002866 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002867 Result += "\nstruct protocol_methods {\n";
2868 Result += "\tSEL _cmd;\n";
2869 Result += "\tchar *method_types;\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002870 Result += "};\n";
Steve Naroff04eaa192008-05-06 18:26:51 +00002871
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002872 objc_protocol_methods = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002873 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002874 // Do not synthesize the protocol more than once.
2875 if (ObjCSynthesizedProtocols.count(PDecl))
2876 continue;
2877
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002878 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
2879 unsigned NumMethods = std::distance(PDecl->instmeth_begin(*Context),
2880 PDecl->instmeth_end(*Context));
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002881 /* struct _objc_protocol_method_list {
2882 int protocol_method_count;
2883 struct protocol_methods protocols[];
2884 }
2885 */
2886 Result += "\nstatic struct {\n";
2887 Result += "\tint protocol_method_count;\n";
2888 Result += "\tstruct protocol_methods protocols[";
2889 Result += utostr(NumMethods);
2890 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002891 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002892 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
2893 "{\n\t" + utostr(NumMethods) + "\n";
2894
2895 // Output instance methods declared in this protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002896 for (ObjCProtocolDecl::instmeth_iterator
2897 I = PDecl->instmeth_begin(*Context),
2898 E = PDecl->instmeth_end(*Context);
2899 I != E; ++I) {
2900 if (I == PDecl->instmeth_begin(*Context))
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002901 Result += "\t ,{{(SEL)\"";
2902 else
2903 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002904 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002905 std::string MethodTypeString;
2906 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2907 Result += "\", \"";
2908 Result += MethodTypeString;
2909 Result += "\"}\n";
2910 }
2911 Result += "\t }\n};\n";
2912 }
2913
2914 // Output class methods declared in this protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002915 unsigned NumMethods = std::distance(PDecl->classmeth_begin(*Context),
2916 PDecl->classmeth_end(*Context));
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002917 if (NumMethods > 0) {
2918 /* struct _objc_protocol_method_list {
2919 int protocol_method_count;
2920 struct protocol_methods protocols[];
2921 }
2922 */
2923 Result += "\nstatic struct {\n";
2924 Result += "\tint protocol_method_count;\n";
2925 Result += "\tstruct protocol_methods protocols[";
2926 Result += utostr(NumMethods);
2927 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002928 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002929 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
2930 "{\n\t";
2931 Result += utostr(NumMethods);
2932 Result += "\n";
2933
2934 // Output instance methods declared in this protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002935 for (ObjCProtocolDecl::classmeth_iterator
2936 I = PDecl->classmeth_begin(*Context),
2937 E = PDecl->classmeth_end(*Context);
2938 I != E; ++I) {
2939 if (I == PDecl->classmeth_begin(*Context))
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002940 Result += "\t ,{{(SEL)\"";
2941 else
2942 Result += "\t ,{(SEL)\"";
Chris Lattner3a8f2942008-11-24 03:33:13 +00002943 Result += (*I)->getSelector().getAsString().c_str();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002944 std::string MethodTypeString;
2945 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
2946 Result += "\", \"";
2947 Result += MethodTypeString;
2948 Result += "\"}\n";
2949 }
2950 Result += "\t }\n};\n";
2951 }
2952
2953 // Output:
2954 /* struct _objc_protocol {
2955 // Objective-C 1.0 extensions
2956 struct _objc_protocol_extension *isa;
2957 char *protocol_name;
2958 struct _objc_protocol **protocol_list;
2959 struct _objc_protocol_method_list *instance_methods;
2960 struct _objc_protocol_method_list *class_methods;
2961 };
Steve Naroff27429432008-03-12 01:06:30 +00002962 */
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002963 static bool objc_protocol = false;
2964 if (!objc_protocol) {
2965 Result += "\nstruct _objc_protocol {\n";
2966 Result += "\tstruct _objc_protocol_extension *isa;\n";
2967 Result += "\tchar *protocol_name;\n";
2968 Result += "\tstruct _objc_protocol **protocol_list;\n";
2969 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2970 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2971 Result += "};\n";
2972
2973 objc_protocol = true;
2974 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002975
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002976 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002977 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002978 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
2979 "{\n\t0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00002980 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002981 Result += "\", 0, ";
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002982 if (PDecl->instmeth_begin(*Context) != PDecl->instmeth_end(*Context)) {
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002983 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002984 Result += PDecl->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002985 Result += ", ";
2986 }
2987 else
2988 Result += "0, ";
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002989 if (PDecl->classmeth_begin(*Context) != PDecl->classmeth_end(*Context)) {
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002990 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00002991 Result += PDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002992 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002993 }
Chris Lattnera19b5ec2008-07-21 21:33:21 +00002994 else
2995 Result += "0\n";
2996 Result += "};\n";
2997
2998 // Mark this protocol as having been generated.
2999 if (!ObjCSynthesizedProtocols.insert(PDecl))
3000 assert(false && "protocol already synthesized");
3001 }
3002 // Output the top lovel protocol meta-data for the class.
3003 /* struct _objc_protocol_list {
3004 struct _objc_protocol_list *next;
3005 int protocol_count;
3006 struct _objc_protocol *class_protocols[];
3007 }
3008 */
3009 Result += "\nstatic struct {\n";
3010 Result += "\tstruct _objc_protocol_list *next;\n";
3011 Result += "\tint protocol_count;\n";
3012 Result += "\tstruct _objc_protocol *class_protocols[";
3013 Result += utostr(Protocols.size());
3014 Result += "];\n} _OBJC_";
3015 Result += prefix;
3016 Result += "_PROTOCOLS_";
3017 Result += ClassName;
3018 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3019 "{\n\t0, ";
3020 Result += utostr(Protocols.size());
3021 Result += "\n";
3022
3023 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003024 Result += Protocols[0]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003025 Result += " \n";
3026
3027 for (unsigned i = 1; i != Protocols.size(); i++) {
3028 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003029 Result += Protocols[i]->getNameAsString();
Chris Lattnera19b5ec2008-07-21 21:33:21 +00003030 Result += "\n";
3031 }
3032 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003033}
3034
Ted Kremenek42730c52008-01-07 19:49:32 +00003035/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003036/// implementation.
Steve Naroff44e81222008-04-14 22:03:09 +00003037void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003038 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003039 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003040 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003041 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003042 for (CDecl = ClassDecl->getCategoryList(); CDecl;
3043 CDecl = CDecl->getNextClassCategory())
3044 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3045 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003046
Chris Lattner271d4c22008-11-24 05:29:24 +00003047 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnera661a4d2007-12-23 01:40:15 +00003048 FullCategoryName += '_';
Chris Lattner271d4c22008-11-24 05:29:24 +00003049 FullCategoryName += IDecl->getNameAsString();
Douglas Gregorcd19b572009-04-23 01:02:12 +00003050
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003051 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003052 llvm::SmallVector<ObjCMethodDecl *, 32>
3053 InstanceMethods(IDecl->instmeth_begin(*Context),
3054 IDecl->instmeth_end(*Context));
3055
3056 // If any of our property implementations have associated getters or
3057 // setters, produce metadata for them as well.
3058 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3059 PropEnd = IDecl->propimpl_end(*Context);
3060 Prop != PropEnd; ++Prop) {
3061 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3062 continue;
3063 if (!(*Prop)->getPropertyIvarDecl())
3064 continue;
3065 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3066 if (!PD)
3067 continue;
3068 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3069 InstanceMethods.push_back(Getter);
3070 if (PD->isReadOnly())
3071 continue;
3072 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3073 InstanceMethods.push_back(Setter);
3074 }
3075 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003076 true, "CATEGORY_", FullCategoryName.c_str(),
3077 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003078
3079 // Build _objc_method_list for class's class methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003080 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3081 IDecl->classmeth_end(*Context),
Chris Lattnera661a4d2007-12-23 01:40:15 +00003082 false, "CATEGORY_", FullCategoryName.c_str(),
3083 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003084
3085 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00003086 // Null CDecl is case of a category implementation with no category interface
3087 if (CDecl)
Chris Lattner0be08822008-07-21 21:32:27 +00003088 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00003089 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003090
3091 /* struct _objc_category {
3092 char *category_name;
3093 char *class_name;
3094 struct _objc_method_list *instance_methods;
3095 struct _objc_method_list *class_methods;
3096 struct _objc_protocol_list *protocols;
3097 // Objective-C 1.0 extensions
3098 uint32_t size; // sizeof (struct _objc_category)
3099 struct _objc_property_list *instance_properties; // category's own
3100 // @property decl.
3101 };
3102 */
3103
3104 static bool objc_category = false;
3105 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003106 Result += "\nstruct _objc_category {\n";
3107 Result += "\tchar *category_name;\n";
3108 Result += "\tchar *class_name;\n";
3109 Result += "\tstruct _objc_method_list *instance_methods;\n";
3110 Result += "\tstruct _objc_method_list *class_methods;\n";
3111 Result += "\tstruct _objc_protocol_list *protocols;\n";
3112 Result += "\tunsigned int size;\n";
3113 Result += "\tstruct _objc_property_list *instance_properties;\n";
3114 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003115 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00003116 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003117 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3118 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00003119 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003120 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003121 Result += "\"\n\t, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003122 Result += ClassDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003123 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003124
Douglas Gregorcd19b572009-04-23 01:02:12 +00003125 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003126 Result += "\t, (struct _objc_method_list *)"
3127 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3128 Result += FullCategoryName;
3129 Result += "\n";
3130 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003131 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003132 Result += "\t, 0\n";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003133 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003134 Result += "\t, (struct _objc_method_list *)"
3135 "&_OBJC_CATEGORY_CLASS_METHODS_";
3136 Result += FullCategoryName;
3137 Result += "\n";
3138 }
3139 else
3140 Result += "\t, 0\n";
3141
Chris Lattner179fd522009-02-20 18:18:36 +00003142 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003143 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
3144 Result += FullCategoryName;
3145 Result += "\n";
3146 }
3147 else
3148 Result += "\t, 0\n";
3149 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003150}
3151
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003152/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3153/// ivar offset.
Steve Naroff44e81222008-04-14 22:03:09 +00003154void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
Ted Kremenek42730c52008-01-07 19:49:32 +00003155 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003156 std::string &Result) {
Steve Naroffd3354222008-07-16 18:22:22 +00003157 if (ivar->isBitField()) {
3158 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3159 // place all bitfields at offset 0.
3160 Result += "0";
3161 } else {
3162 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003163 Result += IDecl->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003164 if (LangOpts.Microsoft)
3165 Result += "_IMPL";
3166 Result += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003167 Result += ivar->getNameAsString();
Steve Naroffd3354222008-07-16 18:22:22 +00003168 Result += ")";
3169 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003170}
3171
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003172//===----------------------------------------------------------------------===//
3173// Meta Data Emission
3174//===----------------------------------------------------------------------===//
3175
Steve Naroff44e81222008-04-14 22:03:09 +00003176void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003177 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003178 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003179
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003180 // Explictly declared @interface's are already synthesized.
Steve Naroff7333b492009-04-20 20:09:33 +00003181 if (CDecl->isImplicitInterfaceDecl()) {
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003182 // FIXME: Implementation of a class with no @interface (legacy) doese not
3183 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00003184 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00003185 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003186
Chris Lattnerc7b06752007-12-12 07:56:42 +00003187 // Build _objc_ivar_list metadata for classes ivars if needed
Chris Lattnerec4979b2008-03-16 21:08:55 +00003188 unsigned NumIvars = !IDecl->ivar_empty()
3189 ? IDecl->ivar_size()
3190 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003191 if (NumIvars > 0) {
3192 static bool objc_ivar = false;
3193 if (!objc_ivar) {
3194 /* struct _objc_ivar {
3195 char *ivar_name;
3196 char *ivar_type;
3197 int ivar_offset;
3198 };
3199 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003200 Result += "\nstruct _objc_ivar {\n";
3201 Result += "\tchar *ivar_name;\n";
3202 Result += "\tchar *ivar_type;\n";
3203 Result += "\tint ivar_offset;\n";
3204 Result += "};\n";
3205
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003206 objc_ivar = true;
3207 }
3208
Steve Naroffc723eec2008-03-11 00:12:29 +00003209 /* struct {
3210 int ivar_count;
3211 struct _objc_ivar ivar_list[nIvars];
3212 };
3213 */
3214 Result += "\nstatic struct {\n";
3215 Result += "\tint ivar_count;\n";
3216 Result += "\tstruct _objc_ivar ivar_list[";
3217 Result += utostr(NumIvars);
3218 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003219 Result += IDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003220 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003221 "{\n\t";
3222 Result += utostr(NumIvars);
3223 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003224
Ted Kremenek42730c52008-01-07 19:49:32 +00003225 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerec4979b2008-03-16 21:08:55 +00003226 if (!IDecl->ivar_empty()) {
Chris Lattnerc7b06752007-12-12 07:56:42 +00003227 IVI = IDecl->ivar_begin();
3228 IVE = IDecl->ivar_end();
3229 } else {
3230 IVI = CDecl->ivar_begin();
3231 IVE = CDecl->ivar_end();
3232 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003233 Result += "\t,{{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003234 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003235 Result += "\", \"";
3236 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003237 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003238 Result += StrEncoding;
3239 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003240 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003241 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003242 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003243 Result += "\t ,{\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003244 Result += (*IVI)->getNameAsString();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003245 Result += "\", \"";
3246 std::string StrEncoding;
Daniel Dunbarc9197cd2008-10-17 20:21:44 +00003247 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00003248 Result += StrEncoding;
3249 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00003250 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003251 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003252 }
3253
3254 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003255 }
3256
3257 // Build _objc_method_list for class's instance methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003258 llvm::SmallVector<ObjCMethodDecl *, 32>
3259 InstanceMethods(IDecl->instmeth_begin(*Context),
3260 IDecl->instmeth_end(*Context));
3261
3262 // If any of our property implementations have associated getters or
3263 // setters, produce metadata for them as well.
3264 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(*Context),
3265 PropEnd = IDecl->propimpl_end(*Context);
3266 Prop != PropEnd; ++Prop) {
3267 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3268 continue;
3269 if (!(*Prop)->getPropertyIvarDecl())
3270 continue;
3271 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3272 if (!PD)
3273 continue;
3274 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3275 InstanceMethods.push_back(Getter);
3276 if (PD->isReadOnly())
3277 continue;
3278 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3279 InstanceMethods.push_back(Setter);
3280 }
3281 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003282 true, "", IDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003283
3284 // Build _objc_method_list for class's class methods if needed
Douglas Gregorcd19b572009-04-23 01:02:12 +00003285 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(*Context),
3286 IDecl->classmeth_end(*Context),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003287 false, "", IDecl->getNameAsCString(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003288
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003289 // Protocols referenced in class declaration?
Chris Lattner0be08822008-07-21 21:32:27 +00003290 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003291 "CLASS", CDecl->getNameAsCString(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003292
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003293
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003294 // Declaration of class/meta-class metadata
3295 /* struct _objc_class {
3296 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003297 const char *super_class_name;
3298 char *name;
3299 long version;
3300 long info;
3301 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003302 struct _objc_ivar_list *ivars;
3303 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003304 struct objc_cache *cache;
3305 struct objc_protocol_list *protocols;
3306 const char *ivar_layout;
3307 struct _objc_class_ext *ext;
3308 };
3309 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003310 static bool objc_class = false;
3311 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003312 Result += "\nstruct _objc_class {\n";
3313 Result += "\tstruct _objc_class *isa;\n";
3314 Result += "\tconst char *super_class_name;\n";
3315 Result += "\tchar *name;\n";
3316 Result += "\tlong version;\n";
3317 Result += "\tlong info;\n";
3318 Result += "\tlong instance_size;\n";
3319 Result += "\tstruct _objc_ivar_list *ivars;\n";
3320 Result += "\tstruct _objc_method_list *methods;\n";
3321 Result += "\tstruct objc_cache *cache;\n";
3322 Result += "\tstruct _objc_protocol_list *protocols;\n";
3323 Result += "\tconst char *ivar_layout;\n";
3324 Result += "\tstruct _objc_class_ext *ext;\n";
3325 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003326 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003327 }
3328
3329 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00003330 ObjCInterfaceDecl *RootClass = 0;
3331 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003332 while (SuperClass) {
3333 RootClass = SuperClass;
3334 SuperClass = SuperClass->getSuperClass();
3335 }
3336 SuperClass = CDecl->getSuperClass();
3337
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003338 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003339 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003340 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003341 "{\n\t(struct _objc_class *)\"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003342 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003343 Result += "\"";
3344
3345 if (SuperClass) {
3346 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003347 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003348 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003349 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003350 Result += "\"";
3351 }
3352 else {
3353 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003354 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003355 Result += "\"";
3356 }
Ted Kremenek42730c52008-01-07 19:49:32 +00003357 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003358 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003359 Result += ", 0,2, sizeof(struct _objc_class), 0";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003360 if (IDecl->classmeth_begin(*Context) != IDecl->classmeth_end(*Context)) {
Steve Naroffdee066b2008-03-11 18:14:26 +00003361 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003362 Result += IDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003363 Result += "\n";
3364 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003365 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003366 Result += ", 0\n";
Chris Lattner179fd522009-02-20 18:18:36 +00003367 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003368 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003369 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003370 Result += ",0,0\n";
3371 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00003372 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003373 Result += "\t,0,0,0,0\n";
3374 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003375
3376 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003377 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003378 Result += CDecl->getNameAsString();
Steve Naroff5ce4a242008-03-12 17:18:30 +00003379 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003380 "{\n\t&_OBJC_METACLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003381 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003382 if (SuperClass) {
3383 Result += ", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003384 Result += SuperClass->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003385 Result += "\", \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003386 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003387 Result += "\"";
3388 }
3389 else {
3390 Result += ", 0, \"";
Chris Lattner271d4c22008-11-24 05:29:24 +00003391 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003392 Result += "\"";
3393 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003394 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003395 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00003396 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003397 Result += ",0";
3398 else {
3399 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00003400 Result += ",sizeof(struct ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003401 Result += CDecl->getNameAsString();
Steve Naroffc302e5b2008-03-10 23:33:22 +00003402 if (LangOpts.Microsoft)
3403 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00003404 Result += ")";
3405 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003406 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00003407 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003408 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003409 Result += "\n\t";
3410 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003411 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003412 Result += ",0";
Douglas Gregorcd19b572009-04-23 01:02:12 +00003413 if (IDecl->instmeth_begin(*Context) != IDecl->instmeth_end(*Context)) {
Steve Naroffc723eec2008-03-11 00:12:29 +00003414 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003415 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003416 Result += ", 0\n\t";
3417 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003418 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003419 Result += ",0,0";
Chris Lattner179fd522009-02-20 18:18:36 +00003420 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff27429432008-03-12 01:06:30 +00003421 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003422 Result += CDecl->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003423 Result += ", 0,0\n";
3424 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00003425 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003426 Result += ",0,0,0\n";
3427 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00003428}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003429
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003430/// RewriteImplementations - This routine rewrites all method implementations
3431/// and emits meta-data.
3432
Steve Naroff21658f62008-11-13 20:07:04 +00003433void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003434 int ClsDefCount = ClassImplementation.size();
3435 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003436
Fariborz Jahanian8c664912007-11-13 19:21:13 +00003437 // Rewrite implemented methods
3438 for (int i = 0; i < ClsDefCount; i++)
3439 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003440
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003441 for (int i = 0; i < CatDefCount; i++)
3442 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Naroff21658f62008-11-13 20:07:04 +00003443}
Fariborz Jahanian0136e372007-11-13 20:04:28 +00003444
Steve Naroff21658f62008-11-13 20:07:04 +00003445void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3446 int ClsDefCount = ClassImplementation.size();
3447 int CatDefCount = CategoryImplementation.size();
3448
Steve Naroff5bf10222008-05-07 21:23:49 +00003449 // This is needed for determining instance variable offsets.
Steve Naroff314c1a62008-08-05 18:47:23 +00003450 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003451 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003452 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003453 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00003454
3455 // For each implemented category, write out all its meta data.
3456 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00003457 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00003458
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003459 // Write objc_symtab metadata
3460 /*
3461 struct _objc_symtab
3462 {
3463 long sel_ref_cnt;
3464 SEL *refs;
3465 short cls_def_cnt;
3466 short cat_def_cnt;
3467 void *defs[cls_def_cnt + cat_def_cnt];
3468 };
3469 */
3470
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003471 Result += "\nstruct _objc_symtab {\n";
3472 Result += "\tlong sel_ref_cnt;\n";
3473 Result += "\tSEL *refs;\n";
3474 Result += "\tshort cls_def_cnt;\n";
3475 Result += "\tshort cat_def_cnt;\n";
3476 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3477 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003478
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003479 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003480 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003481 Result += "\t0, 0, " + utostr(ClsDefCount)
3482 + ", " + utostr(CatDefCount) + "\n";
3483 for (int i = 0; i < ClsDefCount; i++) {
3484 Result += "\t,&_OBJC_CLASS_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003485 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003486 Result += "\n";
3487 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003488
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003489 for (int i = 0; i < CatDefCount; i++) {
3490 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003491 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003492 Result += "_";
Chris Lattner271d4c22008-11-24 05:29:24 +00003493 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003494 Result += "\n";
3495 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003496
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003497 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003498
3499 // Write objc_module metadata
3500
3501 /*
3502 struct _objc_module {
3503 long version;
3504 long size;
3505 const char *name;
3506 struct _objc_symtab *symtab;
3507 }
3508 */
3509
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003510 Result += "\nstruct _objc_module {\n";
3511 Result += "\tlong version;\n";
3512 Result += "\tlong size;\n";
3513 Result += "\tconst char *name;\n";
3514 Result += "\tstruct _objc_symtab *symtab;\n";
3515 Result += "};\n\n";
3516 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00003517 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00003518 Result += "\t" + utostr(OBJC_ABI_VERSION) +
3519 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00003520 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003521
3522 if (LangOpts.Microsoft) {
3523 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffbdd2dba2008-05-07 00:06:16 +00003524 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00003525 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3526 Result += "&_OBJC_MODULES;\n";
3527 Result += "#pragma data_seg(pop)\n\n";
3528 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00003529}
Chris Lattner6fe8b272007-10-16 22:36:42 +00003530
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003531std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3532 const char *funcName,
3533 std::string Tag) {
3534 const FunctionType *AFT = CE->getFunctionType();
3535 QualType RT = AFT->getResultType();
3536 std::string StructRef = "struct " + Tag;
3537 std::string S = "static " + RT.getAsString() + " __" +
3538 funcName + "_" + "block_func_" + utostr(i);
Argiris Kirtzidisd3586002008-04-17 14:40:12 +00003539
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003540 BlockDecl *BD = CE->getBlockDecl();
3541
Douglas Gregor4fa58902009-02-26 23:50:07 +00003542 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff16478cf2009-02-02 17:19:26 +00003543 // No user-supplied arguments. Still need to pass in a pointer to the
3544 // block (to reference imported block decl refs).
3545 S += "(" + StructRef + " *__cself)";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003546 } else if (BD->param_empty()) {
3547 S += "(" + StructRef + " *__cself)";
3548 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003549 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003550 assert(FT && "SynthesizeBlockFunc: No function proto");
3551 S += '(';
3552 // first add the implicit argument.
3553 S += StructRef + " *__cself, ";
3554 std::string ParamStr;
3555 for (BlockDecl::param_iterator AI = BD->param_begin(),
3556 E = BD->param_end(); AI != E; ++AI) {
3557 if (AI != BD->param_begin()) S += ", ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003558 ParamStr = (*AI)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003559 (*AI)->getType().getAsStringInternal(ParamStr);
3560 S += ParamStr;
3561 }
3562 if (FT->isVariadic()) {
3563 if (!BD->param_empty()) S += ", ";
3564 S += "...";
3565 }
3566 S += ')';
3567 }
3568 S += " {\n";
3569
3570 // Create local declarations to avoid rewriting all closure decl ref exprs.
3571 // First, emit a declaration for all "by ref" decls.
3572 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3573 E = BlockByRefDecls.end(); I != E; ++I) {
3574 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003575 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003576 Context->getPointerType((*I)->getType()).getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003577 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003578 }
3579 // Next, emit a declaration for all "by copy" declarations.
3580 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3581 E = BlockByCopyDecls.end(); I != E; ++I) {
3582 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003583 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003584 // Handle nested closure invocation. For example:
3585 //
3586 // void (^myImportedClosure)(void);
3587 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3588 //
3589 // void (^anotherClosure)(void);
3590 // anotherClosure = ^(void) {
3591 // myImportedClosure(); // import and invoke the closure
3592 // };
3593 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003594 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003595 S += "struct __block_impl *";
3596 else
3597 (*I)->getType().getAsStringInternal(Name);
Chris Lattner271d4c22008-11-24 05:29:24 +00003598 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003599 }
3600 std::string RewrittenStr = RewrittenBlockExprs[CE];
3601 const char *cstr = RewrittenStr.c_str();
3602 while (*cstr++ != '{') ;
3603 S += cstr;
3604 S += "\n";
3605 return S;
3606}
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003607
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003608std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3609 const char *funcName,
3610 std::string Tag) {
3611 std::string StructRef = "struct " + Tag;
3612 std::string S = "static void __";
3613
3614 S += funcName;
3615 S += "_block_copy_" + utostr(i);
3616 S += "(" + StructRef;
3617 S += "*dst, " + StructRef;
3618 S += "*src) {";
3619 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3620 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003621 S += "_Block_object_assign((void*)&dst->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003622 S += (*I)->getNameAsString();
Steve Naroff1d56d9e2008-12-11 20:51:38 +00003623 S += ", (void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003624 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003625 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003626 }
3627 S += "\nstatic void __";
3628 S += funcName;
3629 S += "_block_dispose_" + utostr(i);
3630 S += "(" + StructRef;
3631 S += "*src) {";
3632 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3633 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff44fe1e32008-12-16 15:50:30 +00003634 S += "_Block_object_dispose((void*)src->";
Chris Lattner271d4c22008-11-24 05:29:24 +00003635 S += (*I)->getNameAsString();
Steve Naroff44fe1e32008-12-16 15:50:30 +00003636 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003637 }
3638 S += "}\n";
3639 return S;
3640}
3641
3642std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3643 bool hasCopyDisposeHelpers) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003644 std::string S = "\nstruct " + Tag;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003645 std::string Constructor = " " + Tag;
3646
3647 S += " {\n struct __block_impl impl;\n";
3648
3649 if (hasCopyDisposeHelpers)
3650 S += " void *copy;\n void *dispose;\n";
3651
3652 Constructor += "(void *fp";
3653
3654 if (hasCopyDisposeHelpers)
3655 Constructor += ", void *copyHelp, void *disposeHelp";
3656
3657 if (BlockDeclRefs.size()) {
3658 // Output all "by copy" declarations.
3659 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3660 E = BlockByCopyDecls.end(); I != E; ++I) {
3661 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003662 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003663 std::string ArgName = "_" + FieldName;
3664 // Handle nested closure invocation. For example:
3665 //
3666 // void (^myImportedBlock)(void);
3667 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3668 //
3669 // void (^anotherBlock)(void);
3670 // anotherBlock = ^(void) {
3671 // myImportedBlock(); // import and invoke the closure
3672 // };
3673 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003674 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003675 S += "struct __block_impl *";
3676 Constructor += ", void *" + ArgName;
3677 } else {
3678 (*I)->getType().getAsStringInternal(FieldName);
3679 (*I)->getType().getAsStringInternal(ArgName);
3680 Constructor += ", " + ArgName;
3681 }
3682 S += FieldName + ";\n";
3683 }
3684 // Output all "by ref" declarations.
3685 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3686 E = BlockByRefDecls.end(); I != E; ++I) {
3687 S += " ";
Chris Lattner271d4c22008-11-24 05:29:24 +00003688 std::string FieldName = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003689 std::string ArgName = "_" + FieldName;
3690 // Handle nested closure invocation. For example:
3691 //
3692 // void (^myImportedBlock)(void);
3693 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3694 //
3695 // void (^anotherBlock)(void);
3696 // anotherBlock = ^(void) {
3697 // myImportedBlock(); // import and invoke the closure
3698 // };
3699 //
Steve Naroffd896f4b2008-12-11 21:05:33 +00003700 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003701 S += "struct __block_impl *";
3702 Constructor += ", void *" + ArgName;
3703 } else {
3704 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName);
3705 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName);
3706 Constructor += ", " + ArgName;
3707 }
3708 S += FieldName + "; // by ref\n";
3709 }
3710 // Finish writing the constructor.
3711 // FIXME: handle NSConcreteGlobalBlock.
3712 Constructor += ", int flags=0) {\n";
3713 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3714 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3715
3716 if (hasCopyDisposeHelpers)
3717 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3718
3719 // Initialize all "by copy" arguments.
3720 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3721 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003722 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003723 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003724 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003725 Constructor += Name + " = (struct __block_impl *)_";
3726 else
3727 Constructor += Name + " = _";
3728 Constructor += Name + ";\n";
3729 }
3730 // Initialize all "by ref" arguments.
3731 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3732 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner271d4c22008-11-24 05:29:24 +00003733 std::string Name = (*I)->getNameAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003734 Constructor += " ";
Steve Naroffd896f4b2008-12-11 21:05:33 +00003735 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003736 Constructor += Name + " = (struct __block_impl *)_";
3737 else
3738 Constructor += Name + " = _";
3739 Constructor += Name + ";\n";
3740 }
3741 } else {
3742 // Finish writing the constructor.
3743 // FIXME: handle NSConcreteGlobalBlock.
3744 Constructor += ", int flags=0) {\n";
3745 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
3746 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3747 if (hasCopyDisposeHelpers)
3748 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
3749 }
3750 Constructor += " ";
3751 Constructor += "}\n";
3752 S += Constructor;
3753 S += "};\n";
3754 return S;
3755}
3756
3757void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3758 const char *FunName) {
3759 // Insert closures that were part of the function.
3760 for (unsigned i = 0; i < Blocks.size(); i++) {
3761
3762 CollectBlockDeclRefInfo(Blocks[i]);
3763
3764 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3765
3766 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
3767 ImportedBlockDecls.size() > 0);
3768
3769 InsertText(FunLocStart, CI.c_str(), CI.size());
3770
3771 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
3772
3773 InsertText(FunLocStart, CF.c_str(), CF.size());
3774
3775 if (ImportedBlockDecls.size()) {
3776 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
3777 InsertText(FunLocStart, HF.c_str(), HF.size());
3778 }
3779
3780 BlockDeclRefs.clear();
3781 BlockByRefDecls.clear();
3782 BlockByCopyDecls.clear();
3783 BlockCallExprs.clear();
3784 ImportedBlockDecls.clear();
3785 }
3786 Blocks.clear();
3787 RewrittenBlockExprs.clear();
3788}
3789
3790void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3791 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003792 const char *FuncName = FD->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003793
3794 SynthesizeBlockLiterals(FunLocStart, FuncName);
3795}
3796
3797void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff6449c6c2008-10-30 12:09:33 +00003798 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3799 //SourceLocation FunLocStart = MD->getLocStart();
3800 // FIXME: This hack works around a bug in Rewrite.InsertText().
3801 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner3a8f2942008-11-24 03:33:13 +00003802 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003803 // Convert colons to underscores.
3804 std::string::size_type loc = 0;
3805 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3806 FuncName.replace(loc, 1, "_");
3807
3808 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
3809}
3810
3811void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3812 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3813 CI != E; ++CI)
3814 if (*CI) {
3815 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3816 GetBlockDeclRefExprs(CBE->getBody());
3817 else
3818 GetBlockDeclRefExprs(*CI);
3819 }
3820 // Handle specific things.
3821 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
3822 // FIXME: Handle enums.
3823 if (!isa<FunctionDecl>(CDRE->getDecl()))
3824 BlockDeclRefs.push_back(CDRE);
3825 return;
3826}
3827
3828void RewriteObjC::GetBlockCallExprs(Stmt *S) {
3829 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
3830 CI != E; ++CI)
3831 if (*CI) {
3832 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3833 GetBlockCallExprs(CBE->getBody());
3834 else
3835 GetBlockCallExprs(*CI);
3836 }
3837
3838 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
3839 if (CE->getCallee()->getType()->isBlockPointerType()) {
3840 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
3841 }
3842 }
3843 return;
3844}
3845
Steve Naroff85eb17b2008-10-30 10:07:53 +00003846Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003847 // Navigate to relevant type information.
3848 const char *closureName = 0;
3849 const BlockPointerType *CPT = 0;
3850
3851 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003852 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003853 CPT = DRE->getType()->getAsBlockPointerType();
3854 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003855 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003856 CPT = CDRE->getType()->getAsBlockPointerType();
3857 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00003858 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003859 CPT = MExpr->getType()->getAsBlockPointerType();
3860 } else {
3861 assert(1 && "RewriteBlockClass: Bad type");
3862 }
3863 assert(CPT && "RewriteBlockClass: Bad type");
3864 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
3865 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00003866 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003867 // FTP will be null for closures that don't take arguments.
3868
Steve Naroff85eb17b2008-10-30 10:07:53 +00003869 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
3870 SourceLocation(),
3871 &Context->Idents.get("__block_impl"));
3872 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003873
Steve Naroff85eb17b2008-10-30 10:07:53 +00003874 // Generate a funky cast.
3875 llvm::SmallVector<QualType, 8> ArgTypes;
3876
3877 // Push the block argument type.
3878 ArgTypes.push_back(PtrBlock);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003879 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00003880 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff85eb17b2008-10-30 10:07:53 +00003881 E = FTP->arg_type_end(); I && (I != E); ++I) {
3882 QualType t = *I;
3883 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffd896f4b2008-12-11 21:05:33 +00003884 if (isTopLevelBlockPointerType(t)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003885 const BlockPointerType *BPT = t->getAsBlockPointerType();
3886 t = Context->getPointerType(BPT->getPointeeType());
3887 }
3888 ArgTypes.push_back(t);
3889 }
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003890 }
Steve Naroff85eb17b2008-10-30 10:07:53 +00003891 // Now do the pointer to function cast.
3892 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
3893 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
3894
3895 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003896
Ted Kremenek0c97e042009-02-07 01:47:29 +00003897 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock, Exp->getCallee(),
3898 PtrBlock, SourceLocation(),
3899 SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003900 // Don't forget the parens to enforce the proper binding.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003901 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3902 BlkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003903 //PE->dump();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003904
Douglas Gregor8acb7272008-12-11 16:49:14 +00003905 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3906 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00003907 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek0c97e042009-02-07 01:47:29 +00003908 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3909 FD->getType());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003910
Ted Kremenek0c97e042009-02-07 01:47:29 +00003911 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType, ME,
3912 PtrToFuncCastType,
3913 SourceLocation(),
3914 SourceLocation());
3915 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Steve Naroff85eb17b2008-10-30 10:07:53 +00003916
3917 llvm::SmallVector<Expr*, 8> BlkExprs;
3918 // Add the implicit argument.
3919 BlkExprs.push_back(BlkCast);
3920 // Add the user arguments.
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003921 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3922 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003923 BlkExprs.push_back(*I);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003924 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00003925 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3926 BlkExprs.size(),
Ted Kremenek0c97e042009-02-07 01:47:29 +00003927 Exp->getType(), SourceLocation());
Steve Naroff85eb17b2008-10-30 10:07:53 +00003928 return CE;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003929}
3930
3931void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00003932 Stmt *BlockCall = SynthesizeBlockCall(Exp);
3933 ReplaceStmt(Exp, BlockCall);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003934}
3935
3936void RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
3937 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003938 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Naroff16478cf2009-02-02 17:19:26 +00003939 Context->getPointerType(BDRE->getType()),
3940 SourceLocation());
3941 // Need parens to enforce precedence.
Ted Kremenek0c97e042009-02-07 01:47:29 +00003942 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Naroff16478cf2009-02-02 17:19:26 +00003943 ReplaceStmt(BDRE, PE);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003944}
3945
Steve Naroff7f1412d2008-11-03 23:29:32 +00003946void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3947 SourceLocation LocStart = CE->getLParenLoc();
3948 SourceLocation LocEnd = CE->getRParenLoc();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003949
3950 // Need to avoid trying to rewrite synthesized casts.
3951 if (LocStart.isInvalid())
3952 return;
Steve Naroff1c53c022008-11-03 11:20:24 +00003953 // Need to avoid trying to rewrite casts contained in macros.
3954 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3955 return;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00003956
Steve Naroff38a9e3f2008-10-27 17:20:55 +00003957 const char *startBuf = SM->getCharacterData(LocStart);
3958 const char *endBuf = SM->getCharacterData(LocEnd);
3959
3960 // advance the location to startArgList.
3961 const char *argPtr = startBuf;
3962
3963 while (*argPtr++ && (argPtr < endBuf)) {
3964 switch (*argPtr) {
3965 case '^':
3966 // Replace the '^' with '*'.
3967 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
3968 ReplaceText(LocStart, 1, "*", 1);
3969 break;
3970 }
3971 }
3972 return;
3973}
3974
3975void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3976 SourceLocation DeclLoc = FD->getLocation();
3977 unsigned parenCount = 0;
3978
3979 // We have 1 or more arguments that have closure pointers.
3980 const char *startBuf = SM->getCharacterData(DeclLoc);
3981 const char *startArgList = strchr(startBuf, '(');
3982
3983 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3984
3985 parenCount++;
3986 // advance the location to startArgList.
3987 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
3988 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3989
3990 const char *argPtr = startArgList;
3991
3992 while (*argPtr++ && parenCount) {
3993 switch (*argPtr) {
3994 case '^':
3995 // Replace the '^' with '*'.
3996 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
3997 ReplaceText(DeclLoc, 1, "*", 1);
3998 break;
3999 case '(':
4000 parenCount++;
4001 break;
4002 case ')':
4003 parenCount--;
4004 break;
4005 }
4006 }
4007 return;
4008}
4009
4010bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004011 const FunctionProtoType *FTP;
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004012 const PointerType *PT = QT->getAsPointerType();
4013 if (PT) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004014 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004015 } else {
4016 const BlockPointerType *BPT = QT->getAsBlockPointerType();
4017 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor4fa58902009-02-26 23:50:07 +00004018 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004019 }
4020 if (FTP) {
Douglas Gregor4fa58902009-02-26 23:50:07 +00004021 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004022 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffd896f4b2008-12-11 21:05:33 +00004023 if (isTopLevelBlockPointerType(*I))
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004024 return true;
4025 }
4026 return false;
4027}
4028
Ted Kremenek0c97e042009-02-07 01:47:29 +00004029void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4030 const char *&RParen) {
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004031 const char *argPtr = strchr(Name, '(');
4032 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4033
4034 LParen = argPtr; // output the start.
4035 argPtr++; // skip past the left paren.
4036 unsigned parenCount = 1;
4037
4038 while (*argPtr && parenCount) {
4039 switch (*argPtr) {
4040 case '(': parenCount++; break;
4041 case ')': parenCount--; break;
4042 default: break;
4043 }
4044 if (parenCount) argPtr++;
4045 }
4046 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4047 RParen = argPtr; // output the end
4048}
4049
4050void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4051 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4052 RewriteBlockPointerFunctionArgs(FD);
4053 return;
4054 }
4055 // Handle Variables and Typedefs.
4056 SourceLocation DeclLoc = ND->getLocation();
4057 QualType DeclT;
4058 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4059 DeclT = VD->getType();
4060 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4061 DeclT = TDD->getUnderlyingType();
4062 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4063 DeclT = FD->getType();
4064 else
4065 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
4066
4067 const char *startBuf = SM->getCharacterData(DeclLoc);
4068 const char *endBuf = startBuf;
4069 // scan backward (from the decl location) for the end of the previous decl.
4070 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4071 startBuf--;
4072
4073 // *startBuf != '^' if we are dealing with a pointer to function that
4074 // may take block argument types (which will be handled below).
4075 if (*startBuf == '^') {
4076 // Replace the '^' with '*', computing a negative offset.
4077 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4078 ReplaceText(DeclLoc, 1, "*", 1);
4079 }
4080 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4081 // Replace the '^' with '*' for arguments.
4082 DeclLoc = ND->getLocation();
4083 startBuf = SM->getCharacterData(DeclLoc);
4084 const char *argListBegin, *argListEnd;
4085 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4086 while (argListBegin < argListEnd) {
4087 if (*argListBegin == '^') {
4088 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4089 ReplaceText(CaretLoc, 1, "*", 1);
4090 }
4091 argListBegin++;
4092 }
4093 }
4094 return;
4095}
4096
4097void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4098 // Add initializers for any closure decl refs.
4099 GetBlockDeclRefExprs(Exp->getBody());
4100 if (BlockDeclRefs.size()) {
4101 // Unique all "by copy" declarations.
4102 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4103 if (!BlockDeclRefs[i]->isByRef())
4104 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4105 // Unique all "by ref" declarations.
4106 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4107 if (BlockDeclRefs[i]->isByRef()) {
4108 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4109 }
4110 // Find any imported blocks...they will need special attention.
4111 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Steve Naroff1d56d9e2008-12-11 20:51:38 +00004112 if (BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroffe59c8b12008-11-13 17:40:07 +00004113 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff38a9e3f2008-10-27 17:20:55 +00004114 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4115 }
4116 }
4117}
4118
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004119FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4120 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor4fa58902009-02-26 23:50:07 +00004121 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004122 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor1f88aa72009-02-25 16:33:18 +00004123 ID, FType, FunctionDecl::Extern, false,
4124 false);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004125}
4126
Steve Naroff80c54752008-10-29 18:15:37 +00004127Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004128 Blocks.push_back(Exp);
4129
4130 CollectBlockDeclRefInfo(Exp);
4131 std::string FuncName;
4132
4133 if (CurFunctionDef)
Chris Lattner3a8f2942008-11-24 03:33:13 +00004134 FuncName = CurFunctionDef->getNameAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004135 else if (CurMethodDef) {
Chris Lattner3a8f2942008-11-24 03:33:13 +00004136 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004137 // Convert colons to underscores.
4138 std::string::size_type loc = 0;
4139 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4140 FuncName.replace(loc, 1, "_");
Steve Naroff80c54752008-10-29 18:15:37 +00004141 } else if (GlobalVarDecl)
Chris Lattner271d4c22008-11-24 05:29:24 +00004142 FuncName = std::string(GlobalVarDecl->getNameAsString());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004143
4144 std::string BlockNumber = utostr(Blocks.size()-1);
4145
4146 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4147 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4148
4149 // Get a pointer to the function type so we can cast appropriately.
4150 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4151
4152 FunctionDecl *FD;
4153 Expr *NewRep;
4154
4155 // Simulate a contructor call...
4156 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004157 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004158
4159 llvm::SmallVector<Expr*, 4> InitExprs;
4160
Steve Naroffd0419d62008-10-29 21:23:59 +00004161 // Initialize the block function.
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004162 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004163 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4164 SourceLocation());
4165 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4166 Context->VoidPtrTy, SourceLocation(),
4167 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004168 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004169
4170 if (ImportedBlockDecls.size()) {
4171 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004172 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004173 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4174 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4175 Context->VoidPtrTy, SourceLocation(),
4176 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004177 InitExprs.push_back(castExpr);
4178
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004179 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
Steve Naroffd0419d62008-10-29 21:23:59 +00004180 FD = SynthBlockInitFunctionDecl(Buf.c_str());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004181 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4182 castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4183 Context->VoidPtrTy, SourceLocation(),
4184 SourceLocation());
Steve Naroffd0419d62008-10-29 21:23:59 +00004185 InitExprs.push_back(castExpr);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004186 }
4187 // Add initializers for any closure decl refs.
4188 if (BlockDeclRefs.size()) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004189 Expr *Exp;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004190 // Output all "by copy" declarations.
4191 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4192 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004193 if (isObjCType((*I)->getType())) {
Steve Naroffd0419d62008-10-29 21:23:59 +00004194 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004195 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004196 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffd896f4b2008-12-11 21:05:33 +00004197 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004198 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004199 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4200 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy, Arg,
4201 Context->VoidPtrTy, SourceLocation(),
4202 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004203 } else {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004204 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004205 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004206 }
Steve Naroffd0419d62008-10-29 21:23:59 +00004207 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004208 }
4209 // Output all "by ref" declarations.
4210 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4211 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004212 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004213 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4214 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Steve Naroffd0419d62008-10-29 21:23:59 +00004215 Context->getPointerType(Exp->getType()),
4216 SourceLocation());
Steve Naroff362c7562008-11-14 21:36:12 +00004217 InitExprs.push_back(Exp);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004218 }
4219 }
Ted Kremenek362abcd2009-02-09 20:51:47 +00004220 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4221 FType, SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004222 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004223 Context->getPointerType(NewRep->getType()),
4224 SourceLocation());
Ted Kremenek0c97e042009-02-07 01:47:29 +00004225 NewRep = new (Context) CStyleCastExpr(FType, NewRep, FType, SourceLocation(),
4226 SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004227 BlockDeclRefs.clear();
4228 BlockByRefDecls.clear();
4229 BlockByCopyDecls.clear();
4230 ImportedBlockDecls.clear();
4231 return NewRep;
4232}
4233
4234//===----------------------------------------------------------------------===//
4235// Function Body / Expression rewriting
4236//===----------------------------------------------------------------------===//
4237
Steve Naroff0e948412008-12-04 16:24:46 +00004238// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4239// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4240// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4241// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4242// Since the rewriter isn't capable of rewriting rewritten code, it's important
4243// we get this right.
4244void RewriteObjC::CollectPropertySetters(Stmt *S) {
4245 // Perform a bottom up traversal of all children.
4246 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4247 CI != E; ++CI)
4248 if (*CI)
4249 CollectPropertySetters(*CI);
4250
4251 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4252 if (BinOp->isAssignmentOp()) {
4253 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4254 PropSetters[PRE] = BinOp;
4255 }
4256 }
4257}
4258
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004259Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4260 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4261 isa<DoStmt>(S) || isa<ForStmt>(S))
4262 Stmts.push_back(S);
4263 else if (isa<ObjCForCollectionStmt>(S)) {
4264 Stmts.push_back(S);
4265 ObjCBcLabelNo.push_back(++BcLabelCount);
4266 }
4267
4268 SourceRange OrigStmtRange = S->getSourceRange();
4269
4270 // Perform a bottom up rewrite of all children.
4271 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4272 CI != E; ++CI)
4273 if (*CI) {
4274 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
4275 if (newStmt)
4276 *CI = newStmt;
4277 }
4278
4279 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4280 // Rewrite the block body in place.
4281 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4282
4283 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroff80c54752008-10-29 18:15:37 +00004284 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4285 RewrittenBlockExprs[BE] = Str;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004286
4287 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4288 //blockTranscribed->dump();
Steve Naroff80c54752008-10-29 18:15:37 +00004289 ReplaceStmt(S, blockTranscribed);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004290 return blockTranscribed;
4291 }
4292 // Handle specific things.
4293 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4294 return RewriteAtEncode(AtEncode);
4295
4296 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4297 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4298
Steve Naroff0e948412008-12-04 16:24:46 +00004299 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4300 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4301 if (BinOp) {
4302 // Because the rewriter doesn't allow us to rewrite rewritten code,
4303 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffedb4bc92008-12-09 12:56:34 +00004304 DisableReplaceStmt = true;
4305 // Save the source range. Even if we disable the replacement, the
4306 // rewritten node will have been inserted into the tree. If the synthesized
4307 // node is at the 'end', the rewriter will fail. Consider this:
4308 // self.errorHandler = handler ? handler :
4309 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4310 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff0e948412008-12-04 16:24:46 +00004311 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffedb4bc92008-12-09 12:56:34 +00004312 DisableReplaceStmt = false;
Steve Naroff102c3f22008-12-04 23:50:32 +00004313 //
4314 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4315 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4316 // to see the original expression). Consider this example:
4317 //
4318 // Foo *obj1, *obj2;
4319 //
4320 // obj1.i = [obj2 rrrr];
4321 //
4322 // 'BinOp' for the previous expression looks like:
4323 //
4324 // (BinaryOperator 0x231ccf0 'int' '='
4325 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4326 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4327 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4328 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4329 //
4330 // 'newStmt' represents the rewritten message expression. For example:
4331 //
4332 // (CallExpr 0x231d300 'id':'struct objc_object *'
4333 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4334 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4335 // (CStyleCastExpr 0x231d220 'void *'
4336 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4337 //
4338 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4339 // can be used as the setter argument. ReplaceStmt() will still 'see'
4340 // the original RHS (since we haven't altered BinOp).
4341 //
4342 // This implies the Rewrite* routines can no longer delete the original
4343 // node. As a result, we now leak the original AST nodes.
4344 //
Steve Naroffedb4bc92008-12-09 12:56:34 +00004345 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff0e948412008-12-04 16:24:46 +00004346 } else {
4347 return RewritePropertyGetter(PropRefExpr);
Steve Narofff6ce8a12008-12-03 00:56:33 +00004348 }
4349 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004350 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4351 return RewriteAtSelector(AtSelector);
4352
4353 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4354 return RewriteObjCStringLiteral(AtString);
4355
4356 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff0e948412008-12-04 16:24:46 +00004357#if 0
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004358 // Before we rewrite it, put the original message expression in a comment.
4359 SourceLocation startLoc = MessExpr->getLocStart();
4360 SourceLocation endLoc = MessExpr->getLocEnd();
4361
4362 const char *startBuf = SM->getCharacterData(startLoc);
4363 const char *endBuf = SM->getCharacterData(endLoc);
4364
4365 std::string messString;
4366 messString += "// ";
4367 messString.append(startBuf, endBuf-startBuf+1);
4368 messString += "\n";
4369
4370 // FIXME: Missing definition of
4371 // InsertText(clang::SourceLocation, char const*, unsigned int).
4372 // InsertText(startLoc, messString.c_str(), messString.size());
4373 // Tried this, but it didn't work either...
4374 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff0e948412008-12-04 16:24:46 +00004375#endif
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004376 return RewriteMessageExpr(MessExpr);
4377 }
4378
4379 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4380 return RewriteObjCTryStmt(StmtTry);
4381
4382 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4383 return RewriteObjCSynchronizedStmt(StmtTry);
4384
4385 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4386 return RewriteObjCThrowStmt(StmtThrow);
4387
4388 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4389 return RewriteObjCProtocolExpr(ProtocolExp);
4390
4391 if (ObjCForCollectionStmt *StmtForCollection =
4392 dyn_cast<ObjCForCollectionStmt>(S))
4393 return RewriteObjCForCollectionStmt(StmtForCollection,
4394 OrigStmtRange.getEnd());
4395 if (BreakStmt *StmtBreakStmt =
4396 dyn_cast<BreakStmt>(S))
4397 return RewriteBreakStmt(StmtBreakStmt);
4398 if (ContinueStmt *StmtContinueStmt =
4399 dyn_cast<ContinueStmt>(S))
4400 return RewriteContinueStmt(StmtContinueStmt);
4401
4402 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4403 // and cast exprs.
4404 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4405 // FIXME: What we're doing here is modifying the type-specifier that
4406 // precedes the first Decl. In the future the DeclGroup should have
4407 // a separate type-specifier that we can rewrite.
4408 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4409
4410 // Blocks rewrite rules.
4411 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4412 DI != DE; ++DI) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00004413 Decl *SD = *DI;
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004414 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004415 if (isTopLevelBlockPointerType(ND->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004416 RewriteBlockPointerDecl(ND);
4417 else if (ND->getType()->isFunctionPointerType())
4418 CheckFunctionPointerDecl(ND->getType(), ND);
4419 }
4420 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004421 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004422 RewriteBlockPointerDecl(TD);
4423 else if (TD->getUnderlyingType()->isFunctionPointerType())
4424 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4425 }
4426 }
4427 }
4428
4429 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4430 RewriteObjCQualifiedInterfaceTypes(CE);
4431
4432 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4433 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4434 assert(!Stmts.empty() && "Statement stack is empty");
4435 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4436 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4437 && "Statement stack mismatch");
4438 Stmts.pop_back();
4439 }
4440 // Handle blocks rewriting.
4441 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4442 if (BDRE->isByRef())
4443 RewriteBlockDeclRefExpr(BDRE);
4444 }
4445 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff85eb17b2008-10-30 10:07:53 +00004446 if (CE->getCallee()->getType()->isBlockPointerType()) {
4447 Stmt *BlockCall = SynthesizeBlockCall(CE);
4448 ReplaceStmt(S, BlockCall);
4449 return BlockCall;
4450 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004451 }
Steve Naroff7f1412d2008-11-03 23:29:32 +00004452 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004453 RewriteCastExpr(CE);
4454 }
4455#if 0
4456 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek0c97e042009-02-07 01:47:29 +00004457 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004458 // Get the new text.
4459 std::string SStr;
4460 llvm::raw_string_ostream Buf(SStr);
4461 Replacement->printPretty(Buf);
4462 const std::string &Str = Buf.str();
4463
4464 printf("CAST = %s\n", &Str[0]);
4465 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4466 delete S;
4467 return Replacement;
4468 }
4469#endif
4470 // Return this stmt unmodified.
4471 return S;
4472}
4473
4474/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4475/// main file of the input.
4476void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4477 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffee8d4972008-12-17 00:20:22 +00004478 if (FD->isOverloadedOperator())
4479 return;
4480
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004481 // Since function prototypes don't have ParmDecl's, we check the function
4482 // prototype. This enables us to rewrite function declarations and
4483 // definitions using the same code.
Douglas Gregor4fa58902009-02-26 23:50:07 +00004484 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004485
Douglas Gregore3241e92009-04-18 00:02:19 +00004486 if (CompoundStmt *Body = FD->getBody(*Context)) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004487 CurFunctionDef = FD;
Steve Naroff0e948412008-12-04 16:24:46 +00004488 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004489 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004490 Body =
4491 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4492 FD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004493 CurrentBody = 0;
4494 if (PropParentMap) {
4495 delete PropParentMap;
4496 PropParentMap = 0;
4497 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004498 // This synthesizes and inserts the block "impl" struct, invoke function,
4499 // and any copy/dispose helper functions.
4500 InsertBlockLiteralsWithinFunction(FD);
4501 CurFunctionDef = 0;
4502 }
4503 return;
4504 }
4505 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenek30916072009-03-12 18:33:24 +00004506 if (CompoundStmt *Body = MD->getBody()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004507 CurMethodDef = MD;
Steve Naroff0e948412008-12-04 16:24:46 +00004508 CollectPropertySetters(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004509 CurrentBody = Body;
Ted Kremenek30916072009-03-12 18:33:24 +00004510 Body =
4511 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4512 MD->setBody(Body);
Steve Narofffbed6802008-12-08 16:43:47 +00004513 CurrentBody = 0;
4514 if (PropParentMap) {
4515 delete PropParentMap;
4516 PropParentMap = 0;
4517 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004518 InsertBlockLiteralsWithinMethod(MD);
4519 CurMethodDef = 0;
4520 }
4521 }
4522 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4523 ClassImplementation.push_back(CI);
4524 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4525 CategoryImplementation.push_back(CI);
4526 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4527 RewriteForwardClassDecl(CD);
4528 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4529 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffd896f4b2008-12-11 21:05:33 +00004530 if (isTopLevelBlockPointerType(VD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004531 RewriteBlockPointerDecl(VD);
Steve Naroff80c54752008-10-29 18:15:37 +00004532 else if (VD->getType()->isFunctionPointerType()) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004533 CheckFunctionPointerDecl(VD->getType(), VD);
4534 if (VD->getInit()) {
Steve Naroff7f1412d2008-11-03 23:29:32 +00004535 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004536 RewriteCastExpr(CE);
4537 }
4538 }
4539 }
Steve Naroff80c54752008-10-29 18:15:37 +00004540 if (VD->getInit()) {
4541 GlobalVarDecl = VD;
Steve Naroff0e948412008-12-04 16:24:46 +00004542 CollectPropertySetters(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004543 CurrentBody = VD->getInit();
Steve Naroff80c54752008-10-29 18:15:37 +00004544 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Narofffbed6802008-12-08 16:43:47 +00004545 CurrentBody = 0;
4546 if (PropParentMap) {
4547 delete PropParentMap;
4548 PropParentMap = 0;
4549 }
Douglas Gregor24afd4a2008-11-17 14:58:09 +00004550 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattnerd120b9e2008-11-24 03:54:41 +00004551 VD->getNameAsCString());
Steve Naroff80c54752008-10-29 18:15:37 +00004552 GlobalVarDecl = 0;
4553
4554 // This is needed for blocks.
Steve Naroff7f1412d2008-11-03 23:29:32 +00004555 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff80c54752008-10-29 18:15:37 +00004556 RewriteCastExpr(CE);
4557 }
4558 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004559 return;
4560 }
4561 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffd896f4b2008-12-11 21:05:33 +00004562 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004563 RewriteBlockPointerDecl(TD);
4564 else if (TD->getUnderlyingType()->isFunctionPointerType())
4565 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4566 return;
4567 }
4568 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
4569 if (RD->isDefinition()) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00004570 for (RecordDecl::field_iterator i = RD->field_begin(*Context),
4571 e = RD->field_end(*Context); i != e; ++i) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004572 FieldDecl *FD = *i;
Steve Naroffd896f4b2008-12-11 21:05:33 +00004573 if (isTopLevelBlockPointerType(FD->getType()))
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004574 RewriteBlockPointerDecl(FD);
4575 }
4576 }
4577 return;
4578 }
4579 // Nothing yet.
4580}
4581
Chris Lattner2a594d02009-03-28 04:11:33 +00004582void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004583 // Get the top-level buffer that this corresponds to.
4584
4585 // Rewrite tabs if we care.
4586 //RewriteTabs();
4587
4588 if (Diags.hasErrorOccurred())
4589 return;
4590
4591 // Create the output file.
4592
4593 llvm::OwningPtr<llvm::raw_ostream> OwnedStream;
4594 llvm::raw_ostream *OutFile;
4595 if (OutFileName == "-") {
4596 OutFile = &llvm::outs();
4597 } else if (!OutFileName.empty()) {
4598 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004599 OutFile = new llvm::raw_fd_ostream(OutFileName.c_str(),
4600 // set binary mode (critical for Windoze)
4601 true,
4602 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004603 OwnedStream.reset(OutFile);
4604 } else if (InFileName == "-") {
4605 OutFile = &llvm::outs();
4606 } else {
4607 llvm::sys::Path Path(InFileName);
4608 Path.eraseSuffix();
4609 Path.appendSuffix("cpp");
4610 std::string Err;
Steve Naroff08299f82009-02-03 20:39:18 +00004611 OutFile = new llvm::raw_fd_ostream(Path.toString().c_str(),
4612 // set binary mode (critical for Windoze)
4613 true,
4614 Err);
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004615 OwnedStream.reset(OutFile);
4616 }
4617
4618 RewriteInclude();
4619
Chris Lattnerf4f776a2009-01-17 06:22:33 +00004620 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004621 Preamble.c_str(), Preamble.size(), false);
4622
Steve Naroff901d8fd2008-11-14 14:10:01 +00004623 if (ClassImplementation.size() || CategoryImplementation.size())
4624 RewriteImplementations();
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004625
4626 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4627 // we are done.
4628 if (const RewriteBuffer *RewriteBuf =
4629 Rewrite.getRewriteBufferFor(MainFileID)) {
4630 //printf("Changed:\n");
4631 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4632 } else {
4633 fprintf(stderr, "No changes\n");
4634 }
Steve Naroff21658f62008-11-13 20:07:04 +00004635
Steve Naroff901d8fd2008-11-14 14:10:01 +00004636 if (ClassImplementation.size() || CategoryImplementation.size()) {
4637 // Rewrite Objective-c meta data*
4638 std::string ResultStr;
4639 SynthesizeMetaDataIntoBuffer(ResultStr);
4640 // Emit metadata.
4641 *OutFile << ResultStr;
4642 }
Steve Naroff0f3b9eb2008-10-28 20:29:00 +00004643 OutFile->flush();
4644}
4645