blob: 3ada2b88de533071a889e7b4186c40d31babcd5f [file] [log] [blame]
Chris Lattnerb429ae42007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
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"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000026#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000027using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000028using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000029
Steve Naroff1c46cf12008-01-28 21:34:52 +000030static llvm::cl::opt<bool>
31SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
32 llvm::cl::desc("Silence ObjC rewriting warnings"));
33
Chris Lattnerb429ae42007-10-11 00:43:27 +000034namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000035 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000036 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000037 Diagnostic &Diags;
Steve Naroff7fd0aff2008-03-10 20:43:59 +000038 const LangOptions &LangOpts;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000039 unsigned RewriteFailedDiag;
40
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000041 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000042 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000043 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000044 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000045 SourceLocation LastIncLoc;
Ted Kremenek42730c52008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
49 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
50 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000051 llvm::SmallVector<Stmt *, 32> Stmts;
52 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000053 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000054
Steve Naroff47e7fa22008-03-15 00:55:56 +000055 unsigned NumObjCStringLiterals;
56
Steve Naroffe9780582007-10-23 23:50:29 +000057 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000058 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000059 FunctionDecl *MsgSendStretFunctionDecl;
60 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000061 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000062 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000063 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000064 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000065 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000066 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffbec4bf52008-03-11 17:37:02 +000067 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000068
Steve Naroff0add5d22007-11-03 11:27:19 +000069 // ObjC string constant support.
70 FileVarDecl *ConstantStringClassReference;
71 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000072
Fariborz Jahanian22277422008-01-16 00:09:11 +000073 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000074 int BcLabelCount;
75
Steve Naroff764c1ae2007-11-15 10:28:18 +000076 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000077 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000078 RecordDecl *SuperStructDecl;
Steve Naroff47e7fa22008-03-15 00:55:56 +000079 RecordDecl *ConstantStringDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000081 // Needed for header files being rewritten
82 bool IsHeader;
83
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000084 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000085 public:
Chris Lattner12499682008-01-31 19:38:44 +000086 void Initialize(ASTContext &context);
87
Chris Lattner569faa62007-10-11 18:38:32 +000088
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000089 // Top Level Driver code.
90 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000091 void HandleDeclInMainFile(Decl *D);
Steve Naroff7fd0aff2008-03-10 20:43:59 +000092 RewriteTest(bool isHeader, Diagnostic &D, const LangOptions &LOpts) :
93 Diags(D), LangOpts(LOpts) {
Steve Naroff53b6f4c2008-01-30 19:17:43 +000094 IsHeader = isHeader;
Steve Naroff1c46cf12008-01-28 21:34:52 +000095 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
96 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff53b6f4c2008-01-30 19:17:43 +000097 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000098 ~RewriteTest();
Chris Lattnerb1548372008-01-31 19:37:57 +000099
100 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattner6216f292008-01-31 19:42:41 +0000101 // If replacement succeeded or warning disabled return with no warning.
102 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerb1548372008-01-31 19:37:57 +0000103 return;
104
Chris Lattnerb1548372008-01-31 19:37:57 +0000105 SourceRange Range = Old->getSourceRange();
106 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
107 0, 0, &Range, 1);
108 }
109
Chris Lattner6216f292008-01-31 19:42:41 +0000110 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000111 // If insertion succeeded or warning disabled return with no warning.
Chris Lattner6216f292008-01-31 19:42:41 +0000112 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
113 SilenceRewriteMacroWarning)
114 return;
115
116 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
117 }
Chris Lattnerb1548372008-01-31 19:37:57 +0000118
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000119 void RemoveText(SourceLocation Loc, unsigned StrLen) {
120 // If removal succeeded or warning disabled return with no warning.
121 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
122 return;
123
124 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
125 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000126
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000127 void ReplaceText(SourceLocation Start, unsigned OrigLength,
128 const char *NewStr, unsigned NewLength) {
129 // If removal succeeded or warning disabled return with no warning.
130 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
131 SilenceRewriteMacroWarning)
132 return;
133
134 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
135 }
136
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000137 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000138 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000139 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000140 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000141 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
142 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000143 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000144 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
145 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
146 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
147 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
148 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
149 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000150 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000151 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000152 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000153 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000154 QualType getSuperStructType();
Steve Naroff47e7fa22008-03-15 00:55:56 +0000155 QualType getConstantStringStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000156
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000157 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000158 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000159 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000160 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000161 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000162 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000163 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000164 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000165 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000166 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000167 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
168 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
169 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000170 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
171 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000172 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
173 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000174 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000175 Stmt *RewriteBreakStmt(BreakStmt *S);
176 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000177 void SynthCountByEnumWithState(std::string &buf);
178
Steve Naroff02a82aa2007-10-30 23:14:51 +0000179 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000180 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000181 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000182 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000183 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000184 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000185 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000186 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000187 void SynthGetProtocolFunctionDecl();
Steve Naroffbec4bf52008-03-11 17:37:02 +0000188 void SynthSuperContructorFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000189
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000190 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000191 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000192 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000193
Ted Kremenek42730c52008-01-07 19:49:32 +0000194 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000195 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000196
Ted Kremenek42730c52008-01-07 19:49:32 +0000197 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
198 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000199 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000200 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000201 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000202 const char *ClassName,
203 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000204
Ted Kremenek42730c52008-01-07 19:49:32 +0000205 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000206 int NumProtocols,
207 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000208 const char *ClassName,
209 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000210 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000211 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000212 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
213 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000214 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000215 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000216 };
217}
218
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000219static bool IsHeaderFile(const std::string &Filename) {
220 std::string::size_type DotPos = Filename.rfind('.');
221
222 if (DotPos == std::string::npos) {
223 // no file extension
224 return false;
225 }
226
227 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
228 // C header: .h
229 // C++ header: .hh or .H;
230 return Ext == "h" || Ext == "hh" || Ext == "H";
231}
232
233ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000234 Diagnostic &Diags,
235 const LangOptions &LOpts) {
236 return new RewriteTest(IsHeaderFile(InFile), Diags, LOpts);
Chris Lattner258f26c2007-11-30 22:25:36 +0000237}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000238
Chris Lattner12499682008-01-31 19:38:44 +0000239void RewriteTest::Initialize(ASTContext &context) {
240 Context = &context;
241 SM = &Context->getSourceManager();
242 MsgSendFunctionDecl = 0;
243 MsgSendSuperFunctionDecl = 0;
244 MsgSendStretFunctionDecl = 0;
245 MsgSendSuperStretFunctionDecl = 0;
246 MsgSendFpretFunctionDecl = 0;
247 GetClassFunctionDecl = 0;
248 GetMetaClassFunctionDecl = 0;
249 SelGetUidFunctionDecl = 0;
250 CFStringFunctionDecl = 0;
251 GetProtocolFunctionDecl = 0;
252 ConstantStringClassReference = 0;
253 NSStringRecord = 0;
254 CurMethodDecl = 0;
255 SuperStructDecl = 0;
256 BcLabelCount = 0;
Steve Naroffbec4bf52008-03-11 17:37:02 +0000257 SuperContructorFunctionDecl = 0;
Steve Naroff47e7fa22008-03-15 00:55:56 +0000258 NumObjCStringLiterals = 0;
Chris Lattner12499682008-01-31 19:38:44 +0000259
260 // Get the ID and start/end of the main file.
261 MainFileID = SM->getMainFileID();
262 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
263 MainFileStart = MainBuf->getBufferStart();
264 MainFileEnd = MainBuf->getBufferEnd();
265
266
267 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffde0da102008-03-10 23:16:54 +0000268
Chris Lattner12499682008-01-31 19:38:44 +0000269 // declaring objc_selector outside the parameter list removes a silly
270 // scope related warning...
Steve Naroffde0da102008-03-10 23:16:54 +0000271 std::string S = "#pragma once\n";
272 S += "struct objc_selector; struct objc_class;\n";
273 S += "#ifndef OBJC_SUPER\n";
Steve Naroffbec4bf52008-03-11 17:37:02 +0000274 S += "struct objc_super { struct objc_object *object; ";
275 S += "struct objc_object *superClass; ";
276 if (LangOpts.Microsoft) {
277 // Add a constructor for creating temporary objects.
278 S += "objc_super(struct objc_object *o, struct objc_object *s) : ";
279 S += "object(o), superClass(s) {} ";
280 }
281 S += "};\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000282 S += "#define OBJC_SUPER\n";
283 S += "#endif\n";
284 S += "#ifndef _REWRITER_typedef_Protocol\n";
285 S += "typedef struct objc_object Protocol;\n";
286 S += "#define _REWRITER_typedef_Protocol\n";
287 S += "#endif\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000288 if (LangOpts.Microsoft)
289 S += "extern \"C\" {\n";
290 S += "struct objc_object *objc_msgSend";
Steve Naroffde0da102008-03-10 23:16:54 +0000291 S += "(struct objc_object *, struct objc_selector *, ...);\n";
292 S += "extern struct objc_object *objc_msgSendSuper";
293 S += "(struct objc_super *, struct objc_selector *, ...);\n";
294 S += "extern struct objc_object *objc_msgSend_stret";
295 S += "(struct objc_object *, struct objc_selector *, ...);\n";
296 S += "extern struct objc_object *objc_msgSendSuper_stret";
297 S += "(struct objc_super *, struct objc_selector *, ...);\n";
298 S += "extern struct objc_object *objc_msgSend_fpret";
299 S += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000300 S += "struct objc_object *objc_getClass";
Steve Naroffde0da102008-03-10 23:16:54 +0000301 S += "(const char *);\n";
302 S += "extern struct objc_object *objc_getMetaClass";
303 S += "(const char *);\n";
304 S += "extern void objc_exception_throw(struct objc_object *);\n";
305 S += "extern void objc_exception_try_enter(void *);\n";
306 S += "extern void objc_exception_try_exit(void *);\n";
307 S += "extern struct objc_object *objc_exception_extract(void *);\n";
308 S += "extern int objc_exception_match";
309 S += "(struct objc_class *, struct objc_object *, ...);\n";
310 S += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff6453aab2008-03-12 13:19:12 +0000311 if (LangOpts.Microsoft)
312 S += "} // end extern \"C\"\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000313 S += "#include <objc/objc.h>\n";
314 S += "#ifndef __FASTENUMERATIONSTATE\n";
315 S += "struct __objcFastEnumerationState {\n\t";
316 S += "unsigned long state;\n\t";
317 S += "id *itemsPtr;\n\t";
318 S += "unsigned long *mutationsPtr;\n\t";
319 S += "unsigned long extra[5];\n};\n";
320 S += "#define __FASTENUMERATIONSTATE\n";
321 S += "#endif\n";
Steve Naroff47e7fa22008-03-15 00:55:56 +0000322 S += "#ifndef __NSCONSTANTSTRINGIMPL\n";
323 S += "struct __NSConstantStringImpl {\n";
324 S += " struct objc_object *isa;\n";
325 S += " int flags;\n";
326 S += " char *str;\n";
327 S += " long length;\n";
328 S += " __NSConstantStringImpl(char *s, long l) :\n";
329 S += " flags(0), str(s), length(l)\n";
330 S += " { extern struct objc_object *_NSConstantStringClassReference;\n";
331 S += " isa = _NSConstantStringClassReference; }\n";
332 S += "};\n";
333 S += "#define __NSCONSTANTSTRINGIMPL\n";
334 S += "#endif\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000335#if 0
336 if (LangOpts.Microsoft)
Steve Naroff7fd0aff2008-03-10 20:43:59 +0000337 S += "#define __attribute__(X)\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000338#endif
Chris Lattner12499682008-01-31 19:38:44 +0000339 if (IsHeader) {
340 // insert the whole string when rewriting a header file
Steve Naroffde0da102008-03-10 23:16:54 +0000341 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner12499682008-01-31 19:38:44 +0000342 }
343 else {
344 // Not rewriting header, exclude the #pragma once pragma
Steve Naroffde0da102008-03-10 23:16:54 +0000345 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattner6216f292008-01-31 19:42:41 +0000346 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner12499682008-01-31 19:38:44 +0000347 }
348}
349
350
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000351//===----------------------------------------------------------------------===//
352// Top Level Driver Code
353//===----------------------------------------------------------------------===//
354
Chris Lattner569faa62007-10-11 18:38:32 +0000355void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000356 // Two cases: either the decl could be in the main file, or it could be in a
357 // #included file. If the former, rewrite it now. If the later, check to see
358 // if we rewrote the #include/#import.
359 SourceLocation Loc = D->getLocation();
360 Loc = SM->getLogicalLoc(Loc);
361
362 // If this is for a builtin, ignore it.
363 if (Loc.isInvalid()) return;
364
Steve Naroffe9780582007-10-23 23:50:29 +0000365 // Look for built-in declarations that we need to refer during the rewrite.
366 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000367 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000368 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
369 // declared in <Foundation/NSString.h>
370 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
371 ConstantStringClassReference = FVD;
372 return;
373 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000374 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000375 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000376 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000377 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000378 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000379 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000380 } else if (ObjCForwardProtocolDecl *FP =
381 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000382 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000383 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000384 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000385 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
386 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000387}
388
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000389/// HandleDeclInMainFile - This is called for each top-level decl defined in the
390/// main file of the input.
391void RewriteTest::HandleDeclInMainFile(Decl *D) {
392 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
393 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000394 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000395
Ted Kremenek42730c52008-01-07 19:49:32 +0000396 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000397 if (Stmt *Body = MD->getBody()) {
398 //Body->dump();
399 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000400 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000401 CurMethodDecl = 0;
402 }
Steve Naroff18c83382007-11-13 23:01:27 +0000403 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000404 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000405 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000406 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000407 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000408 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000409 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000410 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000411 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000412 if (VD->getInit())
413 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
414 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000415 // Nothing yet.
416}
417
418RewriteTest::~RewriteTest() {
419 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000420
421 // Rewrite tabs if we care.
422 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000423
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000424 RewriteInclude();
425
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000426 // Rewrite Objective-c meta data*
427 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000428 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000429
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000430 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
431 // we are done.
432 if (const RewriteBuffer *RewriteBuf =
433 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000434 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000435 std::string S(RewriteBuf->begin(), RewriteBuf->end());
436 printf("%s\n", S.c_str());
437 } else {
438 printf("No changes\n");
439 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000440 // Emit metadata.
441 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000442}
443
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000444//===----------------------------------------------------------------------===//
445// Syntactic (non-AST) Rewriting Code
446//===----------------------------------------------------------------------===//
447
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000448void RewriteTest::RewriteInclude() {
449 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
450 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
451 const char *MainBufStart = MainBuf.first;
452 const char *MainBufEnd = MainBuf.second;
453 size_t ImportLen = strlen("import");
454 size_t IncludeLen = strlen("include");
455
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000456 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000457 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
458 if (*BufPtr == '#') {
459 if (++BufPtr == MainBufEnd)
460 return;
461 while (*BufPtr == ' ' || *BufPtr == '\t')
462 if (++BufPtr == MainBufEnd)
463 return;
464 if (!strncmp(BufPtr, "import", ImportLen)) {
465 // replace import with include
466 SourceLocation ImportLoc =
467 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000468 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000469 BufPtr += ImportLen;
470 }
471 }
472 }
Chris Lattner74db1682007-10-16 21:07:07 +0000473}
474
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000475void RewriteTest::RewriteTabs() {
476 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
477 const char *MainBufStart = MainBuf.first;
478 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000479
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000480 // Loop over the whole file, looking for tabs.
481 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
482 if (*BufPtr != '\t')
483 continue;
484
485 // Okay, we found a tab. This tab will turn into at least one character,
486 // but it depends on which 'virtual column' it is in. Compute that now.
487 unsigned VCol = 0;
488 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
489 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
490 ++VCol;
491
492 // Okay, now that we know the virtual column, we know how many spaces to
493 // insert. We assume 8-character tab-stops.
494 unsigned Spaces = 8-(VCol & 7);
495
496 // Get the location of the tab.
497 SourceLocation TabLoc =
498 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
499
500 // Rewrite the single tab character into a sequence of spaces.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000501 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000502 }
Chris Lattner569faa62007-10-11 18:38:32 +0000503}
504
505
Ted Kremenek42730c52008-01-07 19:49:32 +0000506void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000507 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000508 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000509
510 // Get the start location and compute the semi location.
511 SourceLocation startLoc = ClassDecl->getLocation();
512 const char *startBuf = SM->getCharacterData(startLoc);
513 const char *semiPtr = strchr(startBuf, ';');
514
515 // Translate to typedef's that forward reference structs with the same name
516 // as the class. As a convenience, we include the original declaration
517 // as a comment.
518 std::string typedefString;
519 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000520 typedefString.append(startBuf, semiPtr-startBuf+1);
521 typedefString += "\n";
522 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000523 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000524 typedefString += "#ifndef _REWRITER_typedef_";
525 typedefString += ForwardDecl->getName();
526 typedefString += "\n";
527 typedefString += "#define _REWRITER_typedef_";
528 typedefString += ForwardDecl->getName();
529 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000530 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000531 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000532 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000533 }
534
535 // Replace the @class with typedefs corresponding to the classes.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000536 ReplaceText(startLoc, semiPtr-startBuf+1,
537 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000538}
539
Ted Kremenek42730c52008-01-07 19:49:32 +0000540void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000541 SourceLocation LocStart = Method->getLocStart();
542 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000543
Steve Naroff2ce399a2007-12-14 23:37:57 +0000544 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattner6216f292008-01-31 19:42:41 +0000545 InsertText(LocStart, "/* ", 3);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000546 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000547 } else {
Chris Lattner6216f292008-01-31 19:42:41 +0000548 InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000549 }
550}
551
Ted Kremenek42730c52008-01-07 19:49:32 +0000552void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000553{
554 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000555 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000556 SourceLocation Loc = Property->getLocation();
557
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000558 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000559
560 // FIXME: handle properties that are declared across multiple lines.
561 }
562}
563
Ted Kremenek42730c52008-01-07 19:49:32 +0000564void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000565 SourceLocation LocStart = CatDecl->getLocStart();
566
567 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000568 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000569
Ted Kremenek42730c52008-01-07 19:49:32 +0000570 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000571 E = CatDecl->instmeth_end(); I != E; ++I)
572 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000573 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000574 E = CatDecl->classmeth_end(); I != E; ++I)
575 RewriteMethodDeclaration(*I);
576
Steve Naroff667f1682007-10-30 13:30:57 +0000577 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000578 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000579}
580
Ted Kremenek42730c52008-01-07 19:49:32 +0000581void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000582 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000583
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000584 SourceLocation LocStart = PDecl->getLocStart();
585
586 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000587 ReplaceText(LocStart, 0, "// ", 3);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000588
Ted Kremenek42730c52008-01-07 19:49:32 +0000589 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000590 E = PDecl->instmeth_end(); I != E; ++I)
591 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000592 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000593 E = PDecl->classmeth_end(); I != E; ++I)
594 RewriteMethodDeclaration(*I);
595
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000596 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000597 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000598 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000599
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000600 // Must comment out @optional/@required
601 const char *startBuf = SM->getCharacterData(LocStart);
602 const char *endBuf = SM->getCharacterData(LocEnd);
603 for (const char *p = startBuf; p < endBuf; p++) {
604 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
605 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000606 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000607 ReplaceText(OptionalLoc, strlen("@optional"),
608 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000609
610 }
611 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
612 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000613 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000614 ReplaceText(OptionalLoc, strlen("@required"),
615 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000616
617 }
618 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000619}
620
Ted Kremenek42730c52008-01-07 19:49:32 +0000621void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000622 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000623 if (LocStart.isInvalid())
624 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000625 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000626 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000627}
628
Ted Kremenek42730c52008-01-07 19:49:32 +0000629void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000630 std::string &ResultStr) {
631 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000632 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000633 ResultStr += "id";
634 else
635 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000636 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000637
638 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000639 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000640
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000641 if (OMD->isInstance())
642 NameStr += "_I_";
643 else
644 NameStr += "_C_";
645
646 NameStr += OMD->getClassInterface()->getName();
647 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000648
649 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000650 if (ObjCCategoryImplDecl *CID =
651 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000652 NameStr += CID->getName();
653 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000654 }
655 // Append selector names, replacing ':' with '_'
656 const char *selName = OMD->getSelector().getName().c_str();
657 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000658 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000659 else {
660 std::string selString = OMD->getSelector().getName();
661 int len = selString.size();
662 for (int i = 0; i < len; i++)
663 if (selString[i] == ':')
664 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000665 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000666 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000667 // Remember this name for metadata emission
668 MethodInternalNames[OMD] = NameStr;
669 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000670
671 // Rewrite arguments
672 ResultStr += "(";
673
674 // invisible arguments
675 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000676 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000677 selfTy = Context->getPointerType(selfTy);
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000678 if (!LangOpts.Microsoft) {
679 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
680 ResultStr += "struct ";
681 }
682 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroffde0da102008-03-10 23:16:54 +0000683 ResultStr += OMD->getClassInterface()->getName();
Steve Naroffde0da102008-03-10 23:16:54 +0000684 ResultStr += " *";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000685 }
686 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000687 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000688
689 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000690 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000691 ResultStr += " _cmd";
692
693 // Method arguments.
694 for (int i = 0; i < OMD->getNumParams(); i++) {
695 ParmVarDecl *PDecl = OMD->getParamDecl(i);
696 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000697 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000698 ResultStr += "id";
699 else
700 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000701 ResultStr += " ";
702 ResultStr += PDecl->getName();
703 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000704 if (OMD->isVariadic())
705 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000706 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000707
708}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000709void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000710 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
711 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000712
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000713 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000714 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000715 else
Chris Lattner6216f292008-01-31 19:42:41 +0000716 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000717
Ted Kremenek42730c52008-01-07 19:49:32 +0000718 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000719 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
720 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000721 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000722 ObjCMethodDecl *OMD = *I;
723 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000724 SourceLocation LocStart = OMD->getLocStart();
725 SourceLocation LocEnd = OMD->getBody()->getLocStart();
726
727 const char *startBuf = SM->getCharacterData(LocStart);
728 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000729 ReplaceText(LocStart, endBuf-startBuf,
730 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000731 }
732
Ted Kremenek42730c52008-01-07 19:49:32 +0000733 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000734 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
735 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000736 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000737 ObjCMethodDecl *OMD = *I;
738 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000739 SourceLocation LocStart = OMD->getLocStart();
740 SourceLocation LocEnd = OMD->getBody()->getLocStart();
741
742 const char *startBuf = SM->getCharacterData(LocStart);
743 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000744 ReplaceText(LocStart, endBuf-startBuf,
745 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000746 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000747 if (IMD)
Chris Lattner6216f292008-01-31 19:42:41 +0000748 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000749 else
Chris Lattner6216f292008-01-31 19:42:41 +0000750 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000751}
752
Ted Kremenek42730c52008-01-07 19:49:32 +0000753void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000754 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000755 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000756 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000757 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000758 ResultStr += ClassDecl->getName();
759 ResultStr += "\n";
760 ResultStr += "#define _REWRITER_typedef_";
761 ResultStr += ClassDecl->getName();
762 ResultStr += "\n";
Steve Naroffde0da102008-03-10 23:16:54 +0000763 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000764 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000765 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000766 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000767 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000768 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000769 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000770
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000771 RewriteProperties(ClassDecl->getNumPropertyDecl(),
772 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000773 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000774 E = ClassDecl->instmeth_end(); I != E; ++I)
775 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000776 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000777 E = ClassDecl->classmeth_end(); I != E; ++I)
778 RewriteMethodDeclaration(*I);
779
Steve Naroff1ccf4632007-10-30 03:43:13 +0000780 // Lastly, comment out the @end.
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000781 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000782}
783
Steve Naroff6b759ce2007-11-15 02:58:25 +0000784Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000785 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000786 if (CurMethodDecl) {
787 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
788 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
789 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000790 // lookup which class implements the instance variable.
791 ObjCInterfaceDecl *clsDeclared = 0;
792 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
793 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Steve Naroff5d933112008-03-12 23:15:19 +0000794
795 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroffcbf88fe2008-03-12 21:09:20 +0000796 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000797 RecName += "_IMPL";
798 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
799 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(), II, 0);
800 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
801 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
802 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
803 // Don't forget the parens to enforce the proper binding.
804 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
805 if (IV->isFreeIvar()) {
806 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
807 ReplaceStmt(IV, ME);
808 delete IV;
809 return ME;
810 } else {
Chris Lattnerb1548372008-01-31 19:37:57 +0000811 ReplaceStmt(IV->getBase(), PE);
Steve Naroff5d933112008-03-12 23:15:19 +0000812 // Cannot delete IV->getBase(), since PE points to it.
813 // Replace the old base with the cast. This is important when doing
814 // embedded rewrites. For example, [newInv->_container addObject:0].
815 IV->setBase(PE);
816 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000817 }
818 }
819 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000820 }
Steve Naroff5d933112008-03-12 23:15:19 +0000821 // FIXME: Implement public ivar access from a function.
Steve Naroff60dfb6b2008-03-12 00:25:36 +0000822 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
823 IV->getLocation(), D->getType());
824 ReplaceStmt(IV, Replacement);
825 delete IV;
826 return Replacement;
Steve Naroff6b759ce2007-11-15 02:58:25 +0000827}
828
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000829//===----------------------------------------------------------------------===//
830// Function Body / Expression rewriting
831//===----------------------------------------------------------------------===//
832
Steve Naroff334fbc22007-11-09 15:20:18 +0000833Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000834 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
835 isa<DoStmt>(S) || isa<ForStmt>(S))
836 Stmts.push_back(S);
837 else if (isa<ObjCForCollectionStmt>(S)) {
838 Stmts.push_back(S);
839 ObjCBcLabelNo.push_back(++BcLabelCount);
840 }
841
Chris Lattner2c022162008-01-31 05:10:40 +0000842 SourceLocation OrigStmtEnd = S->getLocEnd();
843
844 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000845 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
846 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000847 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000848 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000849 if (newStmt)
850 *CI = newStmt;
851 }
Steve Naroffe9780582007-10-23 23:50:29 +0000852
853 // Handle specific things.
854 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
855 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000856
857 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
858 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000859
860 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
861 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000862
Steve Naroff0add5d22007-11-03 11:27:19 +0000863 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
864 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000865
Steve Naroff71226032007-10-24 22:48:43 +0000866 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
867 // Before we rewrite it, put the original message expression in a comment.
868 SourceLocation startLoc = MessExpr->getLocStart();
869 SourceLocation endLoc = MessExpr->getLocEnd();
870
871 const char *startBuf = SM->getCharacterData(startLoc);
872 const char *endBuf = SM->getCharacterData(endLoc);
873
874 std::string messString;
875 messString += "// ";
876 messString.append(startBuf, endBuf-startBuf+1);
877 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000878
Chris Lattner6216f292008-01-31 19:42:41 +0000879 // FIXME: Missing definition of
880 // InsertText(clang::SourceLocation, char const*, unsigned int).
881 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff71226032007-10-24 22:48:43 +0000882 // Tried this, but it didn't work either...
Chris Lattner6216f292008-01-31 19:42:41 +0000883 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000884 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000885 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000886
Ted Kremenek42730c52008-01-07 19:49:32 +0000887 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
888 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000889
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000890 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
891 return RewriteObjCSynchronizedStmt(StmtTry);
892
Ted Kremenek42730c52008-01-07 19:49:32 +0000893 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
894 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000895
896 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
897 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000898
899 if (ObjCForCollectionStmt *StmtForCollection =
900 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner2c022162008-01-31 05:10:40 +0000901 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000902 if (BreakStmt *StmtBreakStmt =
903 dyn_cast<BreakStmt>(S))
904 return RewriteBreakStmt(StmtBreakStmt);
905 if (ContinueStmt *StmtContinueStmt =
906 dyn_cast<ContinueStmt>(S))
907 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000908
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000909 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
910 isa<DoStmt>(S) || isa<ForStmt>(S)) {
911 assert(!Stmts.empty() && "Statement stack is empty");
912 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
913 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
914 && "Statement stack mismatch");
915 Stmts.pop_back();
916 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000917#if 0
918 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
919 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
920 // Get the new text.
921 std::ostringstream Buf;
922 Replacement->printPretty(Buf);
923 const std::string &Str = Buf.str();
924
925 printf("CAST = %s\n", &Str[0]);
Chris Lattner6216f292008-01-31 19:42:41 +0000926 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff764c1ae2007-11-15 10:28:18 +0000927 delete S;
928 return Replacement;
929 }
930#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000931 // Return this stmt unmodified.
932 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000933}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000934
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000935/// SynthCountByEnumWithState - To print:
936/// ((unsigned int (*)
937/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
938/// (void *)objc_msgSend)((id)l_collection,
939/// sel_registerName(
940/// "countByEnumeratingWithState:objects:count:"),
941/// &enumState,
942/// (id *)items, (unsigned int)16)
943///
944void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
945 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
946 "id *, unsigned int))(void *)objc_msgSend)";
947 buf += "\n\t\t";
948 buf += "((id)l_collection,\n\t\t";
949 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
950 buf += "\n\t\t";
951 buf += "&enumState, "
952 "(id *)items, (unsigned int)16)";
953}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000954
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000955/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
956/// statement to exit to its outer synthesized loop.
957///
958Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
959 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
960 return S;
961 // replace break with goto __break_label
962 std::string buf;
963
964 SourceLocation startLoc = S->getLocStart();
965 buf = "goto __break_label_";
966 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000967 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000968
969 return 0;
970}
971
972/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
973/// statement to continue with its inner synthesized loop.
974///
975Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
976 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
977 return S;
978 // replace continue with goto __continue_label
979 std::string buf;
980
981 SourceLocation startLoc = S->getLocStart();
982 buf = "goto __continue_label_";
983 buf += utostr(ObjCBcLabelNo.back());
Chris Lattnerb8a1b042008-01-31 19:51:04 +0000984 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000985
986 return 0;
987}
988
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000989/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000990/// It rewrites:
991/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000992
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000993/// Into:
994/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000995/// type elem;
996/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000997/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000998/// id l_collection = (id)collection;
999/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1000/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001001/// if (limit) {
1002/// unsigned long startMutations = *enumState.mutationsPtr;
1003/// do {
1004/// unsigned long counter = 0;
1005/// do {
1006/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001007/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001008/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001009/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001010/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001011/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001012/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1013/// objects:items count:16]);
1014/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001015/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001016/// }
1017/// else
1018/// elem = nil;
1019/// }
1020///
Chris Lattner2c022162008-01-31 05:10:40 +00001021Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1022 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001023 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1024 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1025 "ObjCForCollectionStmt Statement stack mismatch");
1026 assert(!ObjCBcLabelNo.empty() &&
1027 "ObjCForCollectionStmt - Label No stack empty");
1028
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001029 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001030 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001031 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001032 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001033 std::string buf;
1034 buf = "\n{\n\t";
1035 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1036 // type elem;
1037 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001038 elementTypeAsString = ElementType.getAsString();
1039 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001040 buf += " ";
1041 elementName = DS->getDecl()->getName();
1042 buf += elementName;
1043 buf += ";\n\t";
1044 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001045 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001046 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001047 elementTypeAsString = DR->getDecl()->getType().getAsString();
1048 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001049 else
1050 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1051
1052 // struct __objcFastEnumerationState enumState = { 0 };
1053 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1054 // id items[16];
1055 buf += "id items[16];\n\t";
1056 // id l_collection = (id)
1057 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001058 // Find start location of 'collection' the hard way!
1059 const char *startCollectionBuf = startBuf;
1060 startCollectionBuf += 3; // skip 'for'
1061 startCollectionBuf = strchr(startCollectionBuf, '(');
1062 startCollectionBuf++; // skip '('
1063 // find 'in' and skip it.
1064 while (*startCollectionBuf != ' ' ||
1065 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1066 (*(startCollectionBuf+3) != ' ' &&
1067 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1068 startCollectionBuf++;
1069 startCollectionBuf += 3;
1070
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001071 // Replace: "for (type element in" with string constructed thus far.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001072 ReplaceText(startLoc, startCollectionBuf - startBuf,
1073 buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001074 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +00001075 SourceLocation rightParenLoc = S->getRParenLoc();
1076 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1077 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001078 buf = ";\n\t";
1079
1080 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1081 // objects:items count:16];
1082 // which is synthesized into:
1083 // unsigned int limit =
1084 // ((unsigned int (*)
1085 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1086 // (void *)objc_msgSend)((id)l_collection,
1087 // sel_registerName(
1088 // "countByEnumeratingWithState:objects:count:"),
1089 // (struct __objcFastEnumerationState *)&state,
1090 // (id *)items, (unsigned int)16);
1091 buf += "unsigned long limit =\n\t\t";
1092 SynthCountByEnumWithState(buf);
1093 buf += ";\n\t";
1094 /// if (limit) {
1095 /// unsigned long startMutations = *enumState.mutationsPtr;
1096 /// do {
1097 /// unsigned long counter = 0;
1098 /// do {
1099 /// if (startMutations != *enumState.mutationsPtr)
1100 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001101 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001102 buf += "if (limit) {\n\t";
1103 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1104 buf += "do {\n\t\t";
1105 buf += "unsigned long counter = 0;\n\t\t";
1106 buf += "do {\n\t\t\t";
1107 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1108 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1109 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001110 buf += " = (";
1111 buf += elementTypeAsString;
1112 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001113 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001114 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001115
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001116 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001117 /// } while (counter < limit);
1118 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1119 /// objects:items count:16]);
1120 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001121 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001122 /// }
1123 /// else
1124 /// elem = nil;
1125 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001126 ///
1127 buf = ";\n\t";
1128 buf += "__continue_label_";
1129 buf += utostr(ObjCBcLabelNo.back());
1130 buf += ": ;";
1131 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001132 buf += "} while (counter < limit);\n\t";
1133 buf += "} while (limit = ";
1134 SynthCountByEnumWithState(buf);
1135 buf += ");\n\t";
1136 buf += elementName;
1137 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001138 buf += "__break_label_";
1139 buf += utostr(ObjCBcLabelNo.back());
1140 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001141 buf += "}\n\t";
1142 buf += "else\n\t\t";
1143 buf += elementName;
1144 buf += " = nil;\n";
1145 buf += "}\n";
1146 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001147 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattner6216f292008-01-31 19:42:41 +00001148 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001149 Stmts.pop_back();
1150 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001151 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001152}
1153
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001154/// RewriteObjCSynchronizedStmt -
1155/// This routine rewrites @synchronized(expr) stmt;
1156/// into:
1157/// objc_sync_enter(expr);
1158/// @try stmt @finally { objc_sync_exit(expr); }
1159///
1160Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1161 // Get the start location and compute the semi location.
1162 SourceLocation startLoc = S->getLocStart();
1163 const char *startBuf = SM->getCharacterData(startLoc);
1164
1165 assert((*startBuf == '@') && "bogus @synchronized location");
1166
1167 std::string buf;
1168 buf = "objc_sync_enter";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001169 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001170 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1171 const char *endBuf = SM->getCharacterData(endLoc);
1172 endBuf++;
1173 const char *rparenBuf = strchr(endBuf, ')');
1174 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1175 buf = ");\n";
1176 // declare a new scope with two variables, _stack and _rethrow.
1177 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1178 buf += "int buf[18/*32-bit i386*/];\n";
1179 buf += "char *pointers[4];} _stack;\n";
1180 buf += "id volatile _rethrow = 0;\n";
1181 buf += "objc_exception_try_enter(&_stack);\n";
1182 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001183 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001184 startLoc = S->getSynchBody()->getLocEnd();
1185 startBuf = SM->getCharacterData(startLoc);
1186
1187 assert((*startBuf == '}') && "bogus @try block");
1188 SourceLocation lastCurlyLoc = startLoc;
1189 buf = "}\nelse {\n";
1190 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1191 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1192 // FIXME: This must be objc_sync_exit(syncExpr);
1193 buf += " objc_sync_exit();\n";
1194 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1195 buf += "}\n";
1196 buf += "}";
1197
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001198 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001199 return 0;
1200}
1201
Ted Kremenek42730c52008-01-07 19:49:32 +00001202Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001203 // Get the start location and compute the semi location.
1204 SourceLocation startLoc = S->getLocStart();
1205 const char *startBuf = SM->getCharacterData(startLoc);
1206
1207 assert((*startBuf == '@') && "bogus @try location");
1208
1209 std::string buf;
1210 // declare a new scope with two variables, _stack and _rethrow.
1211 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1212 buf += "int buf[18/*32-bit i386*/];\n";
1213 buf += "char *pointers[4];} _stack;\n";
1214 buf += "id volatile _rethrow = 0;\n";
1215 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001216 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001217
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001218 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001219
1220 startLoc = S->getTryBody()->getLocEnd();
1221 startBuf = SM->getCharacterData(startLoc);
1222
1223 assert((*startBuf == '}') && "bogus @try block");
1224
1225 SourceLocation lastCurlyLoc = startLoc;
1226
1227 startLoc = startLoc.getFileLocWithOffset(1);
1228 buf = " /* @catch begin */ else {\n";
1229 buf += " id _caught = objc_exception_extract(&_stack);\n";
1230 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001231 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001232 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1233 buf += " else { /* @catch continue */";
1234
Chris Lattner6216f292008-01-31 19:42:41 +00001235 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001236
1237 bool sawIdTypedCatch = false;
1238 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001239 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001240 while (catchList) {
1241 Stmt *catchStmt = catchList->getCatchParamStmt();
1242
1243 if (catchList == S->getCatchStmts())
1244 buf = "if ("; // we are generating code for the first catch clause
1245 else
1246 buf = "else if (";
1247 startLoc = catchList->getLocStart();
1248 startBuf = SM->getCharacterData(startLoc);
1249
1250 assert((*startBuf == '@') && "bogus @catch location");
1251
1252 const char *lParenLoc = strchr(startBuf, '(');
1253
Steve Naroff397c4ce2008-02-01 22:08:12 +00001254 if (catchList->hasEllipsis()) {
Steve Naroff929c77e2008-02-01 20:02:07 +00001255 // Now rewrite the body...
1256 lastCatchBody = catchList->getCatchBody();
1257 SourceLocation rParenLoc = catchList->getRParenLoc();
1258 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1259 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1260 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1261 assert((*rParenBuf == ')') && "bogus @catch paren location");
1262 assert((*bodyBuf == '{') && "bogus @catch body location");
1263
1264 buf += "1) { id _tmp = _caught;";
1265 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1266 buf.c_str(), buf.size());
1267 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001268 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001269 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001270 buf += "1) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001271 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001272 sawIdTypedCatch = true;
1273 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001274 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001275
Ted Kremenek42730c52008-01-07 19:49:32 +00001276 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001277 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001278 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001279 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001280 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001281 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001282 }
1283 }
1284 // Now rewrite the body...
1285 lastCatchBody = catchList->getCatchBody();
1286 SourceLocation rParenLoc = catchList->getRParenLoc();
1287 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1288 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1289 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1290 assert((*rParenBuf == ')') && "bogus @catch paren location");
1291 assert((*bodyBuf == '{') && "bogus @catch body location");
1292
1293 buf = " = _caught;";
1294 // Here we replace ") {" with "= _caught;" (which initializes and
1295 // declares the @catch parameter).
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001296 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001297 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001298 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001299 }
Steve Naroff929c77e2008-02-01 20:02:07 +00001300 // make sure all the catch bodies get rewritten!
Steve Naroffe9f69842007-11-07 04:08:17 +00001301 catchList = catchList->getNextCatchStmt();
1302 }
1303 // Complete the catch list...
1304 if (lastCatchBody) {
1305 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1306 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1307 assert((*bodyBuf == '}') && "bogus @catch body location");
1308 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1309 buf = " } } /* @catch end */\n";
1310
Chris Lattner6216f292008-01-31 19:42:41 +00001311 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001312
1313 // Set lastCurlyLoc
1314 lastCurlyLoc = lastCatchBody->getLocEnd();
1315 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001316 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001317 startLoc = finalStmt->getLocStart();
1318 startBuf = SM->getCharacterData(startLoc);
1319 assert((*startBuf == '@') && "bogus @finally start");
1320
1321 buf = "/* @finally */";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001322 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001323
1324 Stmt *body = finalStmt->getFinallyBody();
1325 SourceLocation startLoc = body->getLocStart();
1326 SourceLocation endLoc = body->getLocEnd();
1327 const char *startBuf = SM->getCharacterData(startLoc);
1328 const char *endBuf = SM->getCharacterData(endLoc);
1329 assert((*startBuf == '{') && "bogus @finally body location");
1330 assert((*endBuf == '}') && "bogus @finally body location");
1331
1332 startLoc = startLoc.getFileLocWithOffset(1);
1333 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001334 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001335 endLoc = endLoc.getFileLocWithOffset(-1);
1336 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001337 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001338
1339 // Set lastCurlyLoc
1340 lastCurlyLoc = body->getLocEnd();
1341 }
1342 // Now emit the final closing curly brace...
1343 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1344 buf = " } /* @try scope end */\n";
Chris Lattner6216f292008-01-31 19:42:41 +00001345 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001346 return 0;
1347}
1348
Ted Kremenek42730c52008-01-07 19:49:32 +00001349Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001350 return 0;
1351}
1352
Ted Kremenek42730c52008-01-07 19:49:32 +00001353Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001354 return 0;
1355}
1356
Chris Lattnerb1548372008-01-31 19:37:57 +00001357// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001358// the throw expression is typically a message expression that's already
1359// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001360Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001361 // Get the start location and compute the semi location.
1362 SourceLocation startLoc = S->getLocStart();
1363 const char *startBuf = SM->getCharacterData(startLoc);
1364
1365 assert((*startBuf == '@') && "bogus @throw location");
1366
1367 std::string buf;
1368 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001369 if (S->getThrowExpr())
1370 buf = "objc_exception_throw(";
1371 else // add an implicit argument
1372 buf = "objc_exception_throw(_caught";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001373 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001374 const char *semiBuf = strchr(startBuf, ';');
1375 assert((*semiBuf == ';') && "@throw: can't find ';'");
1376 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1377 buf = ");";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00001378 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001379 return 0;
1380}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001381
Chris Lattner0021f452007-10-24 16:57:36 +00001382Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001383 // Create a new string expression.
1384 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001385 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001386 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1387 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001388 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1389 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001390 SourceLocation(), SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001391 ReplaceStmt(Exp, Replacement);
Chris Lattner258f26c2007-11-30 22:25:36 +00001392
Chris Lattner4478db92007-11-30 22:53:43 +00001393 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001394 delete Exp;
1395 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001396}
1397
Steve Naroff296b74f2007-11-05 14:50:49 +00001398Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1399 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1400 // Create a call to sel_registerName("selName").
1401 llvm::SmallVector<Expr*, 8> SelExprs;
1402 QualType argType = Context->getPointerType(Context->CharTy);
1403 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1404 Exp->getSelector().getName().size(),
1405 false, argType, SourceLocation(),
1406 SourceLocation()));
1407 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1408 &SelExprs[0], SelExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00001409 ReplaceStmt(Exp, SelExp);
Steve Naroff296b74f2007-11-05 14:50:49 +00001410 delete Exp;
1411 return SelExp;
1412}
1413
Steve Naroff71226032007-10-24 22:48:43 +00001414CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1415 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001416 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001417 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001418
1419 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001420 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001421
1422 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001423 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001424 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1425
1426 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001427
Steve Naroff71226032007-10-24 22:48:43 +00001428 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1429}
1430
Steve Naroffc8a92d12007-11-01 13:24:47 +00001431static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1432 const char *&startRef, const char *&endRef) {
1433 while (startBuf < endBuf) {
1434 if (*startBuf == '<')
1435 startRef = startBuf; // mark the start.
1436 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001437 if (startRef && *startRef == '<') {
1438 endRef = startBuf; // mark the end.
1439 return true;
1440 }
1441 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001442 }
1443 startBuf++;
1444 }
1445 return false;
1446}
1447
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001448static void scanToNextArgument(const char *&argRef) {
1449 int angle = 0;
1450 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1451 if (*argRef == '<')
1452 angle++;
1453 else if (*argRef == '>')
1454 angle--;
1455 argRef++;
1456 }
1457 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1458}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001459
Steve Naroffc8a92d12007-11-01 13:24:47 +00001460bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001461
Ted Kremenek42730c52008-01-07 19:49:32 +00001462 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001463 return true;
1464
Ted Kremenek42730c52008-01-07 19:49:32 +00001465 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001466 return true;
1467
Steve Naroffc8a92d12007-11-01 13:24:47 +00001468 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001469 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001470 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001471 return true; // we have "Class <Protocol> *".
1472 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001473 return false;
1474}
1475
Ted Kremenek42730c52008-01-07 19:49:32 +00001476void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001477 SourceLocation Loc;
1478 QualType Type;
1479 const FunctionTypeProto *proto = 0;
1480 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1481 Loc = VD->getLocation();
1482 Type = VD->getType();
1483 }
1484 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1485 Loc = FD->getLocation();
1486 // Check for ObjC 'id' and class types that have been adorned with protocol
1487 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1488 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1489 assert(funcType && "missing function type");
1490 proto = dyn_cast<FunctionTypeProto>(funcType);
1491 if (!proto)
1492 return;
1493 Type = proto->getResultType();
1494 }
1495 else
1496 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001497
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001498 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001499 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001500
1501 const char *endBuf = SM->getCharacterData(Loc);
1502 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001503 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001504 startBuf--; // scan backward (from the decl location) for return type.
1505 const char *startRef = 0, *endRef = 0;
1506 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1507 // Get the locations of the startRef, endRef.
1508 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1509 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1510 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001511 InsertText(LessLoc, "/*", 2);
1512 InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001513 }
1514 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001515 if (!proto)
1516 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001517 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001518 const char *startBuf = SM->getCharacterData(Loc);
1519 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001520 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1521 if (needToScanForQualifiers(proto->getArgType(i))) {
1522 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001523
Steve Naroffc8a92d12007-11-01 13:24:47 +00001524 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001525 // scan forward (from the decl location) for argument types.
1526 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001527 const char *startRef = 0, *endRef = 0;
1528 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1529 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001530 SourceLocation LessLoc =
1531 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1532 SourceLocation GreaterLoc =
1533 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001534 // Comment out the protocol references.
Chris Lattner6216f292008-01-31 19:42:41 +00001535 InsertText(LessLoc, "/*", 2);
1536 InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001537 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001538 startBuf = ++endBuf;
1539 }
1540 else {
1541 while (*startBuf != ')' && *startBuf != ',')
1542 startBuf++; // scan forward (from the decl location) for argument types.
1543 startBuf++;
1544 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001545 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001546}
1547
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001548// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1549void RewriteTest::SynthSelGetUidFunctionDecl() {
1550 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1551 llvm::SmallVector<QualType, 16> ArgTys;
1552 ArgTys.push_back(Context->getPointerType(
1553 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001554 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001555 &ArgTys[0], ArgTys.size(),
1556 false /*isVariadic*/);
1557 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1558 SelGetUidIdent, getFuncType,
1559 FunctionDecl::Extern, false, 0);
1560}
1561
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001562// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1563void RewriteTest::SynthGetProtocolFunctionDecl() {
1564 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1565 llvm::SmallVector<QualType, 16> ArgTys;
1566 ArgTys.push_back(Context->getPointerType(
1567 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001568 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001569 &ArgTys[0], ArgTys.size(),
1570 false /*isVariadic*/);
1571 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1572 SelGetProtoIdent, getFuncType,
1573 FunctionDecl::Extern, false, 0);
1574}
1575
Steve Naroff02a82aa2007-10-30 23:14:51 +00001576void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1577 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001578 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001579 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001580 return;
1581 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001582 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001583}
1584
Steve Naroffbec4bf52008-03-11 17:37:02 +00001585// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1586void RewriteTest::SynthSuperContructorFunctionDecl() {
1587 if (SuperContructorFunctionDecl)
1588 return;
1589 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1590 llvm::SmallVector<QualType, 16> ArgTys;
1591 QualType argT = Context->getObjCIdType();
1592 assert(!argT.isNull() && "Can't find 'id' type");
1593 ArgTys.push_back(argT);
1594 ArgTys.push_back(argT);
1595 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1596 &ArgTys[0], ArgTys.size(),
1597 false);
1598 SuperContructorFunctionDecl = new FunctionDecl(SourceLocation(),
1599 msgSendIdent, msgSendType,
1600 FunctionDecl::Extern, false, 0);
1601}
1602
Steve Naroff02a82aa2007-10-30 23:14:51 +00001603// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1604void RewriteTest::SynthMsgSendFunctionDecl() {
1605 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1606 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001607 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001608 assert(!argT.isNull() && "Can't find 'id' type");
1609 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001610 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001611 assert(!argT.isNull() && "Can't find 'SEL' type");
1612 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001613 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001614 &ArgTys[0], ArgTys.size(),
1615 true /*isVariadic*/);
1616 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1617 msgSendIdent, msgSendType,
1618 FunctionDecl::Extern, false, 0);
1619}
1620
Steve Naroff764c1ae2007-11-15 10:28:18 +00001621// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1622void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1623 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1624 llvm::SmallVector<QualType, 16> ArgTys;
1625 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1626 &Context->Idents.get("objc_super"), 0);
1627 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1628 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1629 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001630 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001631 assert(!argT.isNull() && "Can't find 'SEL' type");
1632 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001633 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001634 &ArgTys[0], ArgTys.size(),
1635 true /*isVariadic*/);
1636 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1637 msgSendIdent, msgSendType,
1638 FunctionDecl::Extern, false, 0);
1639}
1640
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001641// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1642void RewriteTest::SynthMsgSendStretFunctionDecl() {
1643 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1644 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001645 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001646 assert(!argT.isNull() && "Can't find 'id' type");
1647 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001648 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001649 assert(!argT.isNull() && "Can't find 'SEL' type");
1650 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001651 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001652 &ArgTys[0], ArgTys.size(),
1653 true /*isVariadic*/);
1654 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1655 msgSendIdent, msgSendType,
1656 FunctionDecl::Extern, false, 0);
1657}
1658
1659// SynthMsgSendSuperStretFunctionDecl -
1660// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1661void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1662 IdentifierInfo *msgSendIdent =
1663 &Context->Idents.get("objc_msgSendSuper_stret");
1664 llvm::SmallVector<QualType, 16> ArgTys;
1665 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1666 &Context->Idents.get("objc_super"), 0);
1667 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1668 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1669 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001670 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001671 assert(!argT.isNull() && "Can't find 'SEL' type");
1672 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001673 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001674 &ArgTys[0], ArgTys.size(),
1675 true /*isVariadic*/);
1676 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1677 msgSendIdent, msgSendType,
1678 FunctionDecl::Extern, false, 0);
1679}
1680
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001681// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1682void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1683 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1684 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001685 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001686 assert(!argT.isNull() && "Can't find 'id' type");
1687 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001688 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001689 assert(!argT.isNull() && "Can't find 'SEL' type");
1690 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001691 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001692 &ArgTys[0], ArgTys.size(),
1693 true /*isVariadic*/);
1694 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1695 msgSendIdent, msgSendType,
1696 FunctionDecl::Extern, false, 0);
1697}
1698
Steve Naroff02a82aa2007-10-30 23:14:51 +00001699// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1700void RewriteTest::SynthGetClassFunctionDecl() {
1701 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1702 llvm::SmallVector<QualType, 16> ArgTys;
1703 ArgTys.push_back(Context->getPointerType(
1704 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001705 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001706 &ArgTys[0], ArgTys.size(),
1707 false /*isVariadic*/);
1708 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1709 getClassIdent, getClassType,
1710 FunctionDecl::Extern, false, 0);
1711}
1712
Steve Naroff3b1caac2007-12-07 03:50:46 +00001713// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1714void RewriteTest::SynthGetMetaClassFunctionDecl() {
1715 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1716 llvm::SmallVector<QualType, 16> ArgTys;
1717 ArgTys.push_back(Context->getPointerType(
1718 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001719 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001720 &ArgTys[0], ArgTys.size(),
1721 false /*isVariadic*/);
1722 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1723 getClassIdent, getClassType,
1724 FunctionDecl::Extern, false, 0);
1725}
1726
Steve Naroff0add5d22007-11-03 11:27:19 +00001727Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff47e7fa22008-03-15 00:55:56 +00001728 QualType strType = getConstantStringStructType();
1729
1730 std::string S = "__NSConstantStringImpl_";
1731 S += utostr(NumObjCStringLiterals++);
1732
1733 std::string StrObjDecl = "static __NSConstantStringImpl " + S;
1734 StrObjDecl += " = __NSConstantStringImpl(";
1735 // The pretty printer for StringLiteral handles escape characters properly.
1736 std::ostringstream prettyBuf;
1737 Exp->getString()->printPretty(prettyBuf);
1738 StrObjDecl += prettyBuf.str();
1739 StrObjDecl += ",";
1740 // FIXME: This length isn't correct. It doesn't include escape characters
1741 // inserted by the pretty printer.
1742 StrObjDecl += utostr(Exp->getString()->getByteLength()) + ");\n";
1743 InsertText(SourceLocation::getFileLoc(MainFileID, 0),
1744 StrObjDecl.c_str(), StrObjDecl.size());
1745
1746 FileVarDecl *NewVD = new FileVarDecl(SourceLocation(),
1747 &Context->Idents.get(S.c_str()), strType,
1748 VarDecl::Static, NULL);
1749 DeclRefExpr *DRE = new DeclRefExpr(NewVD, strType, SourceLocation());
1750 Expr *Unop = new UnaryOperator(DRE, UnaryOperator::AddrOf,
1751 Context->getPointerType(DRE->getType()),
1752 SourceLocation());
Steve Naroffabb96362007-11-08 14:30:50 +00001753 // cast to NSConstantString *
Steve Naroff47e7fa22008-03-15 00:55:56 +00001754 CastExpr *cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerb1548372008-01-31 19:37:57 +00001755 ReplaceStmt(Exp, cast);
Steve Naroffabb96362007-11-08 14:30:50 +00001756 delete Exp;
1757 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +00001758}
1759
Ted Kremenek42730c52008-01-07 19:49:32 +00001760ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001761 // check if we are sending a message to 'super'
1762 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001763 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1764 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1765 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1766 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001767 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001768 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001769 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001770 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001771 if (ObjCInterfaceType *IT =
1772 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001773 if (IT->getDecl() ==
1774 CurMethodDecl->getClassInterface()->getSuperClass())
1775 return IT->getDecl();
1776 }
1777 }
1778 }
1779 }
1780 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001781 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001782 }
1783 return 0;
1784}
1785
1786// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1787QualType RewriteTest::getSuperStructType() {
1788 if (!SuperStructDecl) {
1789 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1790 &Context->Idents.get("objc_super"), 0);
1791 QualType FieldTypes[2];
1792
1793 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001794 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001795 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001796 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001797 // Create fields
1798 FieldDecl *FieldDecls[2];
1799
1800 for (unsigned i = 0; i < 2; ++i)
1801 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1802
1803 SuperStructDecl->defineBody(FieldDecls, 4);
1804 }
1805 return Context->getTagDeclType(SuperStructDecl);
1806}
1807
Steve Naroff47e7fa22008-03-15 00:55:56 +00001808QualType RewriteTest::getConstantStringStructType() {
1809 if (!ConstantStringDecl) {
1810 ConstantStringDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1811 &Context->Idents.get("__NSConstantStringImpl"), 0);
1812 QualType FieldTypes[4];
1813
1814 // struct objc_object *receiver;
1815 FieldTypes[0] = Context->getObjCIdType();
1816 // int flags;
1817 FieldTypes[1] = Context->IntTy;
1818 // char *str;
1819 FieldTypes[2] = Context->getPointerType(Context->CharTy);
1820 // long length;
1821 FieldTypes[3] = Context->LongTy;
1822 // Create fields
1823 FieldDecl *FieldDecls[2];
1824
1825 for (unsigned i = 0; i < 4; ++i)
1826 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1827
1828 ConstantStringDecl->defineBody(FieldDecls, 4);
1829 }
1830 return Context->getTagDeclType(ConstantStringDecl);
1831}
1832
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001833Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001834 if (!SelGetUidFunctionDecl)
1835 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001836 if (!MsgSendFunctionDecl)
1837 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001838 if (!MsgSendSuperFunctionDecl)
1839 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001840 if (!MsgSendStretFunctionDecl)
1841 SynthMsgSendStretFunctionDecl();
1842 if (!MsgSendSuperStretFunctionDecl)
1843 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001844 if (!MsgSendFpretFunctionDecl)
1845 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001846 if (!GetClassFunctionDecl)
1847 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001848 if (!GetMetaClassFunctionDecl)
1849 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001850
Steve Naroff764c1ae2007-11-15 10:28:18 +00001851 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001852 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1853 // May need to use objc_msgSend_stret() as well.
1854 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001855 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001856 QualType resultType = mDecl->getResultType();
1857 if (resultType.getCanonicalType()->isStructureType()
1858 || resultType.getCanonicalType()->isUnionType())
1859 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001860 else if (resultType.getCanonicalType()->isRealFloatingType())
1861 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001862 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001863
Steve Naroff71226032007-10-24 22:48:43 +00001864 // Synthesize a call to objc_msgSend().
1865 llvm::SmallVector<Expr*, 8> MsgExprs;
1866 IdentifierInfo *clsName = Exp->getClassName();
1867
1868 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1869 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001870 if (!strcmp(clsName->getName(), "super")) {
1871 MsgSendFlavor = MsgSendSuperFunctionDecl;
1872 if (MsgSendStretFlavor)
1873 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1874 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1875
Ted Kremenek42730c52008-01-07 19:49:32 +00001876 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001877 CurMethodDecl->getClassInterface()->getSuperClass();
1878
1879 llvm::SmallVector<Expr*, 4> InitExprs;
1880
1881 // set the receiver to self, the first argument to all methods.
1882 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001883 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001884 SourceLocation()));
1885 llvm::SmallVector<Expr*, 8> ClsExprs;
1886 QualType argType = Context->getPointerType(Context->CharTy);
1887 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1888 SuperDecl->getIdentifier()->getLength(),
1889 false, argType, SourceLocation(),
1890 SourceLocation()));
1891 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1892 &ClsExprs[0],
1893 ClsExprs.size());
1894 // To turn off a warning, type-cast to 'id'
1895 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001896 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001897 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1898 // struct objc_super
1899 QualType superType = getSuperStructType();
Steve Naroffdee066b2008-03-11 18:14:26 +00001900 Expr *SuperRep;
Steve Naroffbec4bf52008-03-11 17:37:02 +00001901
Steve Naroffdee066b2008-03-11 18:14:26 +00001902 if (LangOpts.Microsoft) {
1903 SynthSuperContructorFunctionDecl();
1904 // Simulate a contructor call...
1905 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1906 superType, SourceLocation());
1907 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1908 superType, SourceLocation());
1909 } else {
1910 // (struct objc_super) { <exprs from above> }
1911 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1912 &InitExprs[0], InitExprs.size(),
1913 SourceLocation());
1914 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1915 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001916 // struct objc_super *
1917 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1918 Context->getPointerType(SuperRep->getType()),
1919 SourceLocation());
1920 MsgExprs.push_back(Unop);
1921 } else {
1922 llvm::SmallVector<Expr*, 8> ClsExprs;
1923 QualType argType = Context->getPointerType(Context->CharTy);
1924 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1925 clsName->getLength(),
1926 false, argType, SourceLocation(),
1927 SourceLocation()));
1928 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1929 &ClsExprs[0],
1930 ClsExprs.size());
1931 MsgExprs.push_back(Cls);
1932 }
Steve Naroff885e2122007-11-14 23:54:14 +00001933 } else { // instance message.
1934 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001935
Ted Kremenek42730c52008-01-07 19:49:32 +00001936 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001937 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001938 if (MsgSendStretFlavor)
1939 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001940 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1941
1942 llvm::SmallVector<Expr*, 4> InitExprs;
1943
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001944 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001945 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001946 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001947
1948 llvm::SmallVector<Expr*, 8> ClsExprs;
1949 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001950 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1951 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001952 false, argType, SourceLocation(),
1953 SourceLocation()));
1954 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001955 &ClsExprs[0],
1956 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001957 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001958 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001959 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001960 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001961 // struct objc_super
1962 QualType superType = getSuperStructType();
Steve Naroffbec4bf52008-03-11 17:37:02 +00001963 Expr *SuperRep;
1964
1965 if (LangOpts.Microsoft) {
1966 SynthSuperContructorFunctionDecl();
1967 // Simulate a contructor call...
1968 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1969 superType, SourceLocation());
1970 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1971 superType, SourceLocation());
1972 } else {
1973 // (struct objc_super) { <exprs from above> }
1974 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1975 &InitExprs[0], InitExprs.size(),
1976 SourceLocation());
1977 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1978 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001979 // struct objc_super *
1980 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1981 Context->getPointerType(SuperRep->getType()),
1982 SourceLocation());
1983 MsgExprs.push_back(Unop);
1984 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001985 // Remove all type-casts because it may contain objc-style types; e.g.
1986 // Foo<Proto> *.
1987 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1988 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001989 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001990 MsgExprs.push_back(recExpr);
1991 }
Steve Naroff885e2122007-11-14 23:54:14 +00001992 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001993 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001994 llvm::SmallVector<Expr*, 8> SelExprs;
1995 QualType argType = Context->getPointerType(Context->CharTy);
1996 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1997 Exp->getSelector().getName().size(),
1998 false, argType, SourceLocation(),
1999 SourceLocation()));
2000 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2001 &SelExprs[0], SelExprs.size());
2002 MsgExprs.push_back(SelExp);
2003
2004 // Now push any user supplied arguments.
2005 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00002006 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00002007 // Make all implicit casts explicit...ICE comes in handy:-)
2008 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2009 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00002010 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2011 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002012 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002013 }
2014 // Make id<P...> cast into an 'id' cast.
2015 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002016 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002017 while ((CE = dyn_cast<CastExpr>(userExpr)))
2018 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00002019 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00002020 userExpr, SourceLocation());
2021 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00002022 }
Steve Naroff885e2122007-11-14 23:54:14 +00002023 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00002024 // We've transferred the ownership to MsgExprs. Null out the argument in
2025 // the original expression, since we will delete it below.
2026 Exp->setArg(i, 0);
2027 }
Steve Naroff0744c472007-11-04 22:37:50 +00002028 // Generate the funky cast.
2029 CastExpr *cast;
2030 llvm::SmallVector<QualType, 8> ArgTypes;
2031 QualType returnType;
2032
2033 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00002034 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2035 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2036 else
Ted Kremenek42730c52008-01-07 19:49:32 +00002037 ArgTypes.push_back(Context->getObjCIdType());
2038 ArgTypes.push_back(Context->getObjCSelType());
2039 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00002040 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00002041 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002042 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2043 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00002044 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00002045 ArgTypes.push_back(t);
2046 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002047 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2048 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00002049 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00002050 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00002051 }
2052 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00002053 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00002054
2055 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002056 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2057 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00002058
2059 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2060 // If we don't do this cast, we get the following bizarre warning/note:
2061 // xx.m:13: warning: function called through a non-compatible type
2062 // xx.m:13: note: if this code is reached, the program will abort
2063 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2064 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00002065
Steve Naroff0744c472007-11-04 22:37:50 +00002066 // Now do the "normal" pointer to function cast.
2067 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002068 &ArgTypes[0], ArgTypes.size(),
2069 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00002070 castType = Context->getPointerType(castType);
2071 cast = new CastExpr(castType, cast, SourceLocation());
2072
2073 // Don't forget the parens to enforce the proper binding.
2074 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2075
2076 const FunctionType *FT = msgSendType->getAsFunctionType();
2077 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2078 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002079 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002080 if (MsgSendStretFlavor) {
2081 // We have the method which returns a struct/union. Must also generate
2082 // call to objc_msgSend_stret and hang both varieties on a conditional
2083 // expression which dictate which one to envoke depending on size of
2084 // method's return type.
2085
2086 // Create a reference to the objc_msgSend_stret() declaration.
2087 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2088 SourceLocation());
2089 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2090 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2091 SourceLocation());
2092 // Now do the "normal" pointer to function cast.
2093 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00002094 &ArgTypes[0], ArgTypes.size(),
2095 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002096 castType = Context->getPointerType(castType);
2097 cast = new CastExpr(castType, cast, SourceLocation());
2098
2099 // Don't forget the parens to enforce the proper binding.
2100 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2101
2102 FT = msgSendType->getAsFunctionType();
2103 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2104 FT->getResultType(), SourceLocation());
2105
2106 // Build sizeof(returnType)
2107 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2108 returnType, Context->getSizeType(),
2109 SourceLocation(), SourceLocation());
2110 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2111 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2112 // For X86 it is more complicated and some kind of target specific routine
2113 // is needed to decide what to do.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002114 unsigned IntSize =
2115 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002116 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2117 Context->IntTy,
2118 SourceLocation());
2119 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2120 BinaryOperator::LE,
2121 Context->IntTy,
2122 SourceLocation());
2123 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2124 ConditionalOperator *CondExpr =
2125 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002126 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002127 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002128 return ReplacingStmt;
2129}
2130
2131Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2132 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002133 // Now do the actual rewrite.
Chris Lattnerb1548372008-01-31 19:37:57 +00002134 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff71226032007-10-24 22:48:43 +00002135
Chris Lattner0021f452007-10-24 16:57:36 +00002136 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002137 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002138}
2139
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002140/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2141/// call to objc_getProtocol("proto-name").
2142Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2143 if (!GetProtocolFunctionDecl)
2144 SynthGetProtocolFunctionDecl();
2145 // Create a call to objc_getProtocol("ProtocolName").
2146 llvm::SmallVector<Expr*, 8> ProtoExprs;
2147 QualType argType = Context->getPointerType(Context->CharTy);
2148 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2149 strlen(Exp->getProtocol()->getName()),
2150 false, argType, SourceLocation(),
2151 SourceLocation()));
2152 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2153 &ProtoExprs[0],
2154 ProtoExprs.size());
Chris Lattnerb1548372008-01-31 19:37:57 +00002155 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002156 delete Exp;
2157 return ProtoExp;
2158
2159}
2160
Ted Kremenek42730c52008-01-07 19:49:32 +00002161/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002162/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002163void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002164 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002165 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2166 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002167 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002168 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002169 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002170 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002171 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002172 SourceLocation LocStart = CDecl->getLocStart();
2173 SourceLocation LocEnd = CDecl->getLocEnd();
2174
2175 const char *startBuf = SM->getCharacterData(LocStart);
2176 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002177 // If no ivars and no root or if its root, directly or indirectly,
2178 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00002179 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002180 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002181 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002182 return;
2183 }
2184
2185 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002186 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002187 Result += "\nstruct ";
2188 Result += CDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002189 if (LangOpts.Microsoft)
2190 Result += "_IMPL";
Steve Naroff60dfb6b2008-03-12 00:25:36 +00002191
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002192 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002193 const char *cursor = strchr(startBuf, '{');
2194 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002195 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002196
2197 // rewrite the original header *without* disturbing the '{'
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002198 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002199 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002200 Result = "\n struct ";
2201 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002202 Result += "_IMPL ";
2203 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002204 Result += "_IVARS;\n";
Steve Naroff2c7afc92007-11-14 19:25:57 +00002205
2206 // insert the super class structure definition.
Chris Lattner6216f292008-01-31 19:42:41 +00002207 SourceLocation OnePastCurly =
2208 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2209 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroff2c7afc92007-11-14 19:25:57 +00002210 }
2211 cursor++; // past '{'
2212
2213 // Now comment out any visibility specifiers.
2214 while (cursor < endBuf) {
2215 if (*cursor == '@') {
2216 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002217 // Skip whitespace.
2218 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2219 /*scan*/;
2220
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002221 // FIXME: presence of @public, etc. inside comment results in
2222 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002223 if (!strncmp(cursor, "public", strlen("public")) ||
2224 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002225 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner6216f292008-01-31 19:42:41 +00002226 InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002227 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002228 // FIXME: If there are cases where '<' is used in ivar declaration part
2229 // of user code, then scan the ivar list and use needToScanForQualifiers
2230 // for type checking.
2231 else if (*cursor == '<') {
2232 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002233 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002234 cursor = strchr(cursor, '>');
2235 cursor++;
2236 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner6216f292008-01-31 19:42:41 +00002237 InsertText(atLoc, " */", 3);
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002238 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002239 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002240 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002241 // Don't forget to add a ';'!!
Chris Lattner6216f292008-01-31 19:42:41 +00002242 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroff2c7afc92007-11-14 19:25:57 +00002243 } else { // we don't have any instance variables - insert super struct.
2244 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2245 Result += " {\n struct ";
2246 Result += RCDecl->getName();
Steve Naroffcbf88fe2008-03-12 21:09:20 +00002247 Result += "_IMPL ";
2248 Result += RCDecl->getName();
Steve Naroff4850dfe2008-03-12 21:22:52 +00002249 Result += "_IVARS;\n};\n";
Chris Lattnerb8a1b042008-01-31 19:51:04 +00002250 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002251 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002252 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002253 if (!ObjCSynthesizedStructs.insert(CDecl))
2254 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002255}
2256
Ted Kremenek42730c52008-01-07 19:49:32 +00002257// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002258/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002259void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002260 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002261 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002262 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002263 const char *ClassName,
2264 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002265 if (MethodBegin == MethodEnd) return;
2266
Fariborz Jahanian04455192007-10-22 21:41:37 +00002267 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002268 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002269 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002270 SEL _cmd;
2271 char *method_types;
2272 void *_imp;
2273 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002274 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002275 Result += "\nstruct _objc_method {\n";
2276 Result += "\tSEL _cmd;\n";
2277 Result += "\tchar *method_types;\n";
2278 Result += "\tvoid *_imp;\n";
2279 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002280
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002281 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002282 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002283
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002284 // Build _objc_method_list for class's methods if needed
Steve Naroffc723eec2008-03-11 00:12:29 +00002285
2286 /* struct {
2287 struct _objc_method_list *next_method;
2288 int method_count;
2289 struct _objc_method method_list[];
2290 }
2291 */
2292 Result += "\nstatic struct {\n";
2293 Result += "\tstruct _objc_method_list *next_method;\n";
2294 Result += "\tint method_count;\n";
2295 Result += "\tstruct _objc_method method_list[";
2296 Result += utostr(MethodEnd-MethodBegin);
2297 Result += "];\n} _OBJC_";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002298 Result += prefix;
2299 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2300 Result += "_METHODS_";
2301 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002302 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002303 Result += IsInstanceMethod ? "inst" : "cls";
2304 Result += "_meth\")))= ";
2305 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002306
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002307 Result += "\t,{{(SEL)\"";
2308 Result += (*MethodBegin)->getSelector().getName().c_str();
2309 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002310 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002311 Result += "\", \"";
2312 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002313 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002314 Result += MethodInternalNames[*MethodBegin];
2315 Result += "}\n";
2316 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2317 Result += "\t ,{(SEL)\"";
2318 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002319 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002320 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002321 Result += "\", \"";
2322 Result += MethodTypeString;
Steve Naroffc723eec2008-03-11 00:12:29 +00002323 Result += "\", (void *)";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002324 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002325 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002326 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002327 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002328}
2329
Ted Kremenek42730c52008-01-07 19:49:32 +00002330/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2331void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002332 int NumProtocols,
2333 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002334 const char *ClassName,
2335 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002336 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002337 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002338 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002339 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002340 // Output struct protocol_methods holder of method selector and type.
2341 if (!objc_protocol_methods &&
2342 (PDecl->getNumInstanceMethods() > 0
2343 || PDecl->getNumClassMethods() > 0)) {
2344 /* struct protocol_methods {
2345 SEL _cmd;
2346 char *method_types;
2347 }
2348 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002349 Result += "\nstruct protocol_methods {\n";
2350 Result += "\tSEL _cmd;\n";
2351 Result += "\tchar *method_types;\n";
2352 Result += "};\n";
2353
Steve Naroff27429432008-03-12 01:06:30 +00002354 objc_protocol_methods = true;
2355 }
2356 int NumMethods = PDecl->getNumInstanceMethods();
2357 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002358 /* struct _objc_protocol_method_list {
2359 int protocol_method_count;
2360 struct protocol_methods protocols[];
2361 }
2362 */
Steve Naroff27429432008-03-12 01:06:30 +00002363 Result += "\nstatic struct {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002364 Result += "\tint protocol_method_count;\n";
Steve Naroff27429432008-03-12 01:06:30 +00002365 Result += "\tstruct protocol_methods protocols[";
2366 Result += utostr(NumMethods);
2367 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002368 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002369 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002370 "{\n\t" + utostr(NumMethods) + "\n";
2371
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002372 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002373 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002374 E = PDecl->instmeth_end(); I != E; ++I) {
2375 if (I == PDecl->instmeth_begin())
2376 Result += "\t ,{{(SEL)\"";
2377 else
2378 Result += "\t ,{(SEL)\"";
2379 Result += (*I)->getSelector().getName().c_str();
2380 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002381 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002382 Result += "\", \"";
2383 Result += MethodTypeString;
2384 Result += "\"}\n";
2385 }
2386 Result += "\t }\n};\n";
2387 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002388
2389 // Output class methods declared in this protocol.
2390 NumMethods = PDecl->getNumClassMethods();
2391 if (NumMethods > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002392 /* struct _objc_protocol_method_list {
2393 int protocol_method_count;
2394 struct protocol_methods protocols[];
2395 }
2396 */
2397 Result += "\nstatic struct {\n";
2398 Result += "\tint protocol_method_count;\n";
2399 Result += "\tstruct protocol_methods protocols[";
2400 Result += utostr(NumMethods);
2401 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002402 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002403 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002404 "{\n\t";
2405 Result += utostr(NumMethods);
2406 Result += "\n";
2407
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002408 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002409 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002410 E = PDecl->classmeth_end(); I != E; ++I) {
2411 if (I == PDecl->classmeth_begin())
2412 Result += "\t ,{{(SEL)\"";
2413 else
2414 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002415 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002416 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002417 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002418 Result += "\", \"";
2419 Result += MethodTypeString;
2420 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002421 }
2422 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002423 }
2424 // Output:
2425 /* struct _objc_protocol {
2426 // Objective-C 1.0 extensions
2427 struct _objc_protocol_extension *isa;
2428 char *protocol_name;
2429 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002430 struct _objc_protocol_method_list *instance_methods;
2431 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002432 };
2433 */
2434 static bool objc_protocol = false;
2435 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002436 Result += "\nstruct _objc_protocol {\n";
2437 Result += "\tstruct _objc_protocol_extension *isa;\n";
2438 Result += "\tchar *protocol_name;\n";
2439 Result += "\tstruct _objc_protocol **protocol_list;\n";
2440 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2441 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2442 Result += "};\n";
2443
Fariborz Jahanian04455192007-10-22 21:41:37 +00002444 objc_protocol = true;
2445 }
2446
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002447 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2448 Result += PDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002449 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002450 "{\n\t0, \"";
2451 Result += PDecl->getName();
2452 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002453 if (PDecl->getNumInstanceMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002454 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002455 Result += PDecl->getName();
2456 Result += ", ";
2457 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002458 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002459 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002460 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002461 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002462 Result += PDecl->getName();
2463 Result += "\n";
2464 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002465 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002466 Result += "0\n";
2467 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002468 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002469 // Output the top lovel protocol meta-data for the class.
Steve Naroff27429432008-03-12 01:06:30 +00002470 /* struct _objc_protocol_list {
2471 struct _objc_protocol_list *next;
2472 int protocol_count;
2473 struct _objc_protocol *class_protocols[];
2474 }
2475 */
2476 Result += "\nstatic struct {\n";
2477 Result += "\tstruct _objc_protocol_list *next;\n";
2478 Result += "\tint protocol_count;\n";
2479 Result += "\tstruct _objc_protocol *class_protocols[";
2480 Result += utostr(NumProtocols);
2481 Result += "];\n} _OBJC_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002482 Result += prefix;
2483 Result += "_PROTOCOLS_";
2484 Result += ClassName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002485 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002486 "{\n\t0, ";
2487 Result += utostr(NumProtocols);
2488 Result += "\n";
2489
2490 Result += "\t,{&_OBJC_PROTOCOL_";
2491 Result += Protocols[0]->getName();
2492 Result += " \n";
2493
2494 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002495 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff27429432008-03-12 01:06:30 +00002496 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002497 Result += PDecl->getName();
2498 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002499 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002500 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002501 }
2502}
2503
Ted Kremenek42730c52008-01-07 19:49:32 +00002504/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002505/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002506void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002507 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002508 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002509 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002510 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002511 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2512 CDecl = CDecl->getNextClassCategory())
2513 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2514 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002515
Chris Lattnera661a4d2007-12-23 01:40:15 +00002516 std::string FullCategoryName = ClassDecl->getName();
2517 FullCategoryName += '_';
2518 FullCategoryName += IDecl->getName();
2519
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002520 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002521 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002522 true, "CATEGORY_", FullCategoryName.c_str(),
2523 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002524
2525 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002526 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002527 false, "CATEGORY_", FullCategoryName.c_str(),
2528 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002529
2530 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002531 // Null CDecl is case of a category implementation with no category interface
2532 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002533 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002534 CDecl->getNumReferencedProtocols(),
2535 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002536 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002537
2538 /* struct _objc_category {
2539 char *category_name;
2540 char *class_name;
2541 struct _objc_method_list *instance_methods;
2542 struct _objc_method_list *class_methods;
2543 struct _objc_protocol_list *protocols;
2544 // Objective-C 1.0 extensions
2545 uint32_t size; // sizeof (struct _objc_category)
2546 struct _objc_property_list *instance_properties; // category's own
2547 // @property decl.
2548 };
2549 */
2550
2551 static bool objc_category = false;
2552 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002553 Result += "\nstruct _objc_category {\n";
2554 Result += "\tchar *category_name;\n";
2555 Result += "\tchar *class_name;\n";
2556 Result += "\tstruct _objc_method_list *instance_methods;\n";
2557 Result += "\tstruct _objc_method_list *class_methods;\n";
2558 Result += "\tstruct _objc_protocol_list *protocols;\n";
2559 Result += "\tunsigned int size;\n";
2560 Result += "\tstruct _objc_property_list *instance_properties;\n";
2561 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002562 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002563 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002564 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2565 Result += FullCategoryName;
Steve Naroff5ce4a242008-03-12 17:18:30 +00002566 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002567 Result += IDecl->getName();
2568 Result += "\"\n\t, \"";
2569 Result += ClassDecl->getName();
2570 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002571
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002572 if (IDecl->getNumInstanceMethods() > 0) {
2573 Result += "\t, (struct _objc_method_list *)"
2574 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2575 Result += FullCategoryName;
2576 Result += "\n";
2577 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002578 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002579 Result += "\t, 0\n";
2580 if (IDecl->getNumClassMethods() > 0) {
2581 Result += "\t, (struct _objc_method_list *)"
2582 "&_OBJC_CATEGORY_CLASS_METHODS_";
2583 Result += FullCategoryName;
2584 Result += "\n";
2585 }
2586 else
2587 Result += "\t, 0\n";
2588
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002589 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002590 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2591 Result += FullCategoryName;
2592 Result += "\n";
2593 }
2594 else
2595 Result += "\t, 0\n";
2596 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002597}
2598
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002599/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2600/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002601void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2602 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002603 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002604 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002605 Result += IDecl->getName();
Steve Naroffde0da102008-03-10 23:16:54 +00002606 if (LangOpts.Microsoft)
2607 Result += "_IMPL";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002608 Result += ", ";
2609 Result += ivar->getName();
2610 Result += ")";
2611}
2612
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002613//===----------------------------------------------------------------------===//
2614// Meta Data Emission
2615//===----------------------------------------------------------------------===//
2616
Ted Kremenek42730c52008-01-07 19:49:32 +00002617void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002618 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002619 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002620
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002621 // Explictly declared @interface's are already synthesized.
2622 if (CDecl->ImplicitInterfaceDecl()) {
2623 // FIXME: Implementation of a class with no @interface (legacy) doese not
2624 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002625 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002626 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002627
Chris Lattnerc7b06752007-12-12 07:56:42 +00002628 // Build _objc_ivar_list metadata for classes ivars if needed
2629 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2630 ? IDecl->getImplDeclNumIvars()
2631 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002632 if (NumIvars > 0) {
2633 static bool objc_ivar = false;
2634 if (!objc_ivar) {
2635 /* struct _objc_ivar {
2636 char *ivar_name;
2637 char *ivar_type;
2638 int ivar_offset;
2639 };
2640 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002641 Result += "\nstruct _objc_ivar {\n";
2642 Result += "\tchar *ivar_name;\n";
2643 Result += "\tchar *ivar_type;\n";
2644 Result += "\tint ivar_offset;\n";
2645 Result += "};\n";
2646
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002647 objc_ivar = true;
2648 }
2649
Steve Naroffc723eec2008-03-11 00:12:29 +00002650 /* struct {
2651 int ivar_count;
2652 struct _objc_ivar ivar_list[nIvars];
2653 };
2654 */
2655 Result += "\nstatic struct {\n";
2656 Result += "\tint ivar_count;\n";
2657 Result += "\tstruct _objc_ivar ivar_list[";
2658 Result += utostr(NumIvars);
2659 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002660 Result += IDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002661 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002662 "{\n\t";
2663 Result += utostr(NumIvars);
2664 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002665
Ted Kremenek42730c52008-01-07 19:49:32 +00002666 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002667 if (IDecl->getImplDeclNumIvars() > 0) {
2668 IVI = IDecl->ivar_begin();
2669 IVE = IDecl->ivar_end();
2670 } else {
2671 IVI = CDecl->ivar_begin();
2672 IVE = CDecl->ivar_end();
2673 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002674 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002675 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002676 Result += "\", \"";
2677 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002678 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2679 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002680 Result += StrEncoding;
2681 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002682 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002683 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002684 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002685 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002686 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002687 Result += "\", \"";
2688 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002689 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2690 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002691 Result += StrEncoding;
2692 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002693 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002694 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002695 }
2696
2697 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002698 }
2699
2700 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002701 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002702 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002703
2704 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002705 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002706 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002707
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002708 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002709 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002710 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002711 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002712
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002713
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002714 // Declaration of class/meta-class metadata
2715 /* struct _objc_class {
2716 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002717 const char *super_class_name;
2718 char *name;
2719 long version;
2720 long info;
2721 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002722 struct _objc_ivar_list *ivars;
2723 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002724 struct objc_cache *cache;
2725 struct objc_protocol_list *protocols;
2726 const char *ivar_layout;
2727 struct _objc_class_ext *ext;
2728 };
2729 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002730 static bool objc_class = false;
2731 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002732 Result += "\nstruct _objc_class {\n";
2733 Result += "\tstruct _objc_class *isa;\n";
2734 Result += "\tconst char *super_class_name;\n";
2735 Result += "\tchar *name;\n";
2736 Result += "\tlong version;\n";
2737 Result += "\tlong info;\n";
2738 Result += "\tlong instance_size;\n";
2739 Result += "\tstruct _objc_ivar_list *ivars;\n";
2740 Result += "\tstruct _objc_method_list *methods;\n";
2741 Result += "\tstruct objc_cache *cache;\n";
2742 Result += "\tstruct _objc_protocol_list *protocols;\n";
2743 Result += "\tconst char *ivar_layout;\n";
2744 Result += "\tstruct _objc_class_ext *ext;\n";
2745 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002746 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002747 }
2748
2749 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002750 ObjCInterfaceDecl *RootClass = 0;
2751 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002752 while (SuperClass) {
2753 RootClass = SuperClass;
2754 SuperClass = SuperClass->getSuperClass();
2755 }
2756 SuperClass = CDecl->getSuperClass();
2757
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002758 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2759 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002760 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002761 "{\n\t(struct _objc_class *)\"";
2762 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2763 Result += "\"";
2764
2765 if (SuperClass) {
2766 Result += ", \"";
2767 Result += SuperClass->getName();
2768 Result += "\", \"";
2769 Result += CDecl->getName();
2770 Result += "\"";
2771 }
2772 else {
2773 Result += ", 0, \"";
2774 Result += CDecl->getName();
2775 Result += "\"";
2776 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002777 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002778 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002779 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002780 if (IDecl->getNumClassMethods() > 0) {
Steve Naroffdee066b2008-03-11 18:14:26 +00002781 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002782 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002783 Result += "\n";
2784 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002785 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002786 Result += ", 0\n";
2787 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002788 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002789 Result += CDecl->getName();
2790 Result += ",0,0\n";
2791 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002792 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002793 Result += "\t,0,0,0,0\n";
2794 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002795
2796 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002797 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2798 Result += CDecl->getName();
Steve Naroff5ce4a242008-03-12 17:18:30 +00002799 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002800 "{\n\t&_OBJC_METACLASS_";
2801 Result += CDecl->getName();
2802 if (SuperClass) {
2803 Result += ", \"";
2804 Result += SuperClass->getName();
2805 Result += "\", \"";
2806 Result += CDecl->getName();
2807 Result += "\"";
2808 }
2809 else {
2810 Result += ", 0, \"";
2811 Result += CDecl->getName();
2812 Result += "\"";
2813 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002814 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002815 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002816 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002817 Result += ",0";
2818 else {
2819 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002820 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002821 Result += CDecl->getName();
Steve Naroffc302e5b2008-03-10 23:33:22 +00002822 if (LangOpts.Microsoft)
2823 Result += "_IMPL";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002824 Result += ")";
2825 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002826 if (NumIvars > 0) {
Steve Naroffbec4bf52008-03-11 17:37:02 +00002827 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002828 Result += CDecl->getName();
2829 Result += "\n\t";
2830 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002831 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002832 Result += ",0";
2833 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroffc723eec2008-03-11 00:12:29 +00002834 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002835 Result += CDecl->getName();
2836 Result += ", 0\n\t";
2837 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002838 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002839 Result += ",0,0";
2840 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff27429432008-03-12 01:06:30 +00002841 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002842 Result += CDecl->getName();
2843 Result += ", 0,0\n";
2844 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002845 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002846 Result += ",0,0,0\n";
2847 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002848}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002849
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002850/// RewriteImplementations - This routine rewrites all method implementations
2851/// and emits meta-data.
2852
2853void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002854 int ClsDefCount = ClassImplementation.size();
2855 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002856
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002857 if (ClsDefCount == 0 && CatDefCount == 0)
2858 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002859 // Rewrite implemented methods
2860 for (int i = 0; i < ClsDefCount; i++)
2861 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002862
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002863 for (int i = 0; i < CatDefCount; i++)
2864 RewriteImplementationDecl(CategoryImplementation[i]);
2865
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002866 // This is needed for use of offsetof
2867 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002868
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002869 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002870 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002871 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002872
2873 // For each implemented category, write out all its meta data.
2874 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002875 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002876
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002877 // Write objc_symtab metadata
2878 /*
2879 struct _objc_symtab
2880 {
2881 long sel_ref_cnt;
2882 SEL *refs;
2883 short cls_def_cnt;
2884 short cat_def_cnt;
2885 void *defs[cls_def_cnt + cat_def_cnt];
2886 };
2887 */
2888
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002889 Result += "\nstruct _objc_symtab {\n";
2890 Result += "\tlong sel_ref_cnt;\n";
2891 Result += "\tSEL *refs;\n";
2892 Result += "\tshort cls_def_cnt;\n";
2893 Result += "\tshort cat_def_cnt;\n";
2894 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2895 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002896
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002897 Result += "static struct _objc_symtab "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002898 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002899 Result += "\t0, 0, " + utostr(ClsDefCount)
2900 + ", " + utostr(CatDefCount) + "\n";
2901 for (int i = 0; i < ClsDefCount; i++) {
2902 Result += "\t,&_OBJC_CLASS_";
2903 Result += ClassImplementation[i]->getName();
2904 Result += "\n";
2905 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002906
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002907 for (int i = 0; i < CatDefCount; i++) {
2908 Result += "\t,&_OBJC_CATEGORY_";
2909 Result += CategoryImplementation[i]->getClassInterface()->getName();
2910 Result += "_";
2911 Result += CategoryImplementation[i]->getName();
2912 Result += "\n";
2913 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002914
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002915 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002916
2917 // Write objc_module metadata
2918
2919 /*
2920 struct _objc_module {
2921 long version;
2922 long size;
2923 const char *name;
2924 struct _objc_symtab *symtab;
2925 }
2926 */
2927
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002928 Result += "\nstruct _objc_module {\n";
2929 Result += "\tlong version;\n";
2930 Result += "\tlong size;\n";
2931 Result += "\tconst char *name;\n";
2932 Result += "\tstruct _objc_symtab *symtab;\n";
2933 Result += "};\n\n";
2934 Result += "static struct _objc_module "
Steve Naroff5ce4a242008-03-12 17:18:30 +00002935 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002936 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2937 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002938 Result += "};\n\n";
Steve Naroff7fd0aff2008-03-10 20:43:59 +00002939
2940 if (LangOpts.Microsoft) {
2941 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2942 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2943 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2944 Result += "&_OBJC_MODULES;\n";
2945 Result += "#pragma data_seg(pop)\n\n";
2946 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002947}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002948