blob: e00f92dbd3da47a1caf937eda61ddfd4531a09d0 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner77cd2a02007-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 Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Steve Naroff874e2322007-11-15 10:28:18 +000026#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000027using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000028using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000029
Steve Naroff0113c9d2008-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 Lattner77cd2a02007-10-11 00:43:27 +000034namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000035 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000036 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000037 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000038 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000039 unsigned RewriteFailedDiag;
40
Chris Lattner01c57482007-10-17 22:35:30 +000041 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000042 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000043 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000044 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000045 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-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 Jahaniane8d1c052008-01-15 23:58:23 +000051 llvm::SmallVector<Stmt *, 32> Stmts;
52 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000053 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000054
55 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000056 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000057 FunctionDecl *MsgSendStretFunctionDecl;
58 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000059 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000060 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000061 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000062 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000063 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000064 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000065 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000066
Steve Naroffbeaf2992007-11-03 11:27:19 +000067 // ObjC string constant support.
68 FileVarDecl *ConstantStringClassReference;
69 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000070
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000071 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000072 int BcLabelCount;
73
Steve Naroff874e2322007-11-15 10:28:18 +000074 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000075 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000076 RecordDecl *SuperStructDecl;
77
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000078 // Needed for header files being rewritten
79 bool IsHeader;
80
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000081 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000082 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000083 void Initialize(ASTContext &context);
84
Chris Lattner8a12c272007-10-11 18:38:32 +000085
Chris Lattnerf04da132007-10-24 17:06:59 +000086 // Top Level Driver code.
87 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000088 void HandleDeclInMainFile(Decl *D);
Steve Naroff4f943c22008-03-10 20:43:59 +000089 RewriteTest(bool isHeader, Diagnostic &D, const LangOptions &LOpts) :
90 Diags(D), LangOpts(LOpts) {
Steve Narofff69cc5d2008-01-30 19:17:43 +000091 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +000092 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
93 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +000094 }
Chris Lattnerf04da132007-10-24 17:06:59 +000095 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000096
97 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +000098 // If replacement succeeded or warning disabled return with no warning.
99 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000100 return;
101
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000102 SourceRange Range = Old->getSourceRange();
103 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
104 0, 0, &Range, 1);
105 }
106
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000107 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000108 // If insertion succeeded or warning disabled return with no warning.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000109 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
110 SilenceRewriteMacroWarning)
111 return;
112
113 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
114 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000115
Chris Lattneraadaf782008-01-31 19:51:04 +0000116 void RemoveText(SourceLocation Loc, unsigned StrLen) {
117 // If removal succeeded or warning disabled return with no warning.
118 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
119 return;
120
121 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
122 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000123
Chris Lattneraadaf782008-01-31 19:51:04 +0000124 void ReplaceText(SourceLocation Start, unsigned OrigLength,
125 const char *NewStr, unsigned NewLength) {
126 // If removal succeeded or warning disabled return with no warning.
127 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
128 SilenceRewriteMacroWarning)
129 return;
130
131 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
132 }
133
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000135 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000136 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000137 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000138 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
139 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000140 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000141 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
142 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
143 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
144 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
145 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
146 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000147 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000148 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000149 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000150 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000151 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000152
Chris Lattnerf04da132007-10-24 17:06:59 +0000153 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000154 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000155 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000156 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000157 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000158 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000159 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000160 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000161 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000162 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000163 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
164 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
165 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000166 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
167 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000168 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
169 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000170 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000171 Stmt *RewriteBreakStmt(BreakStmt *S);
172 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000173 void SynthCountByEnumWithState(std::string &buf);
174
Steve Naroff09b266e2007-10-30 23:14:51 +0000175 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000176 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000177 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000178 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000179 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000180 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000181 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000182 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000183 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000184 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000185 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000186
Chris Lattnerf04da132007-10-24 17:06:59 +0000187 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000188 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000189 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000190
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000191 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000192 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000193
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000194 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
195 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000196 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000197 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000198 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000199 const char *ClassName,
200 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000203 int NumProtocols,
204 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000205 const char *ClassName,
206 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000207 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000208 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000209 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
210 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000211 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000212 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000213 };
214}
215
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000216static bool IsHeaderFile(const std::string &Filename) {
217 std::string::size_type DotPos = Filename.rfind('.');
218
219 if (DotPos == std::string::npos) {
220 // no file extension
221 return false;
222 }
223
224 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
225 // C header: .h
226 // C++ header: .hh or .H;
227 return Ext == "h" || Ext == "hh" || Ext == "H";
228}
229
230ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000231 Diagnostic &Diags,
232 const LangOptions &LOpts) {
233 return new RewriteTest(IsHeaderFile(InFile), Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000234}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000235
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000236void RewriteTest::Initialize(ASTContext &context) {
237 Context = &context;
238 SM = &Context->getSourceManager();
239 MsgSendFunctionDecl = 0;
240 MsgSendSuperFunctionDecl = 0;
241 MsgSendStretFunctionDecl = 0;
242 MsgSendSuperStretFunctionDecl = 0;
243 MsgSendFpretFunctionDecl = 0;
244 GetClassFunctionDecl = 0;
245 GetMetaClassFunctionDecl = 0;
246 SelGetUidFunctionDecl = 0;
247 CFStringFunctionDecl = 0;
248 GetProtocolFunctionDecl = 0;
249 ConstantStringClassReference = 0;
250 NSStringRecord = 0;
251 CurMethodDecl = 0;
252 SuperStructDecl = 0;
253 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000254 SuperContructorFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000255
256 // Get the ID and start/end of the main file.
257 MainFileID = SM->getMainFileID();
258 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
259 MainFileStart = MainBuf->getBufferStart();
260 MainFileEnd = MainBuf->getBufferEnd();
261
262
263 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000264
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000265 // declaring objc_selector outside the parameter list removes a silly
266 // scope related warning...
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000267 std::string S = "#pragma once\n";
268 S += "struct objc_selector; struct objc_class;\n";
269 S += "#ifndef OBJC_SUPER\n";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000270 S += "struct objc_super { struct objc_object *object; ";
271 S += "struct objc_object *superClass; ";
272 if (LangOpts.Microsoft) {
273 // Add a constructor for creating temporary objects.
274 S += "objc_super(struct objc_object *o, struct objc_object *s) : ";
275 S += "object(o), superClass(s) {} ";
276 }
277 S += "};\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000278 S += "#define OBJC_SUPER\n";
279 S += "#endif\n";
280 S += "#ifndef _REWRITER_typedef_Protocol\n";
281 S += "typedef struct objc_object Protocol;\n";
282 S += "#define _REWRITER_typedef_Protocol\n";
283 S += "#endif\n";
284 S += "extern struct objc_object *objc_msgSend";
285 S += "(struct objc_object *, struct objc_selector *, ...);\n";
286 S += "extern struct objc_object *objc_msgSendSuper";
287 S += "(struct objc_super *, struct objc_selector *, ...);\n";
288 S += "extern struct objc_object *objc_msgSend_stret";
289 S += "(struct objc_object *, struct objc_selector *, ...);\n";
290 S += "extern struct objc_object *objc_msgSendSuper_stret";
291 S += "(struct objc_super *, struct objc_selector *, ...);\n";
292 S += "extern struct objc_object *objc_msgSend_fpret";
293 S += "(struct objc_object *, struct objc_selector *, ...);\n";
294 S += "extern struct objc_object *objc_getClass";
295 S += "(const char *);\n";
296 S += "extern struct objc_object *objc_getMetaClass";
297 S += "(const char *);\n";
298 S += "extern void objc_exception_throw(struct objc_object *);\n";
299 S += "extern void objc_exception_try_enter(void *);\n";
300 S += "extern void objc_exception_try_exit(void *);\n";
301 S += "extern struct objc_object *objc_exception_extract(void *);\n";
302 S += "extern int objc_exception_match";
303 S += "(struct objc_class *, struct objc_object *, ...);\n";
304 S += "extern Protocol *objc_getProtocol(const char *);\n";
305 S += "#include <objc/objc.h>\n";
306 S += "#ifndef __FASTENUMERATIONSTATE\n";
307 S += "struct __objcFastEnumerationState {\n\t";
308 S += "unsigned long state;\n\t";
309 S += "id *itemsPtr;\n\t";
310 S += "unsigned long *mutationsPtr;\n\t";
311 S += "unsigned long extra[5];\n};\n";
312 S += "#define __FASTENUMERATIONSTATE\n";
313 S += "#endif\n";
314#if 0
315 if (LangOpts.Microsoft)
Steve Naroff4f943c22008-03-10 20:43:59 +0000316 S += "#define __attribute__(X)\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000317#endif
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000318 if (IsHeader) {
319 // insert the whole string when rewriting a header file
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000320 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000321 }
322 else {
323 // Not rewriting header, exclude the #pragma once pragma
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000324 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000325 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000326 }
327}
328
329
Chris Lattnerf04da132007-10-24 17:06:59 +0000330//===----------------------------------------------------------------------===//
331// Top Level Driver Code
332//===----------------------------------------------------------------------===//
333
Chris Lattner8a12c272007-10-11 18:38:32 +0000334void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000335 // Two cases: either the decl could be in the main file, or it could be in a
336 // #included file. If the former, rewrite it now. If the later, check to see
337 // if we rewrote the #include/#import.
338 SourceLocation Loc = D->getLocation();
339 Loc = SM->getLogicalLoc(Loc);
340
341 // If this is for a builtin, ignore it.
342 if (Loc.isInvalid()) return;
343
Steve Naroffebf2b562007-10-23 23:50:29 +0000344 // Look for built-in declarations that we need to refer during the rewrite.
345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000346 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000347 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
348 // declared in <Foundation/NSString.h>
349 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
350 ConstantStringClassReference = FVD;
351 return;
352 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000353 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000354 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000355 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000356 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000357 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000358 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000359 } else if (ObjCForwardProtocolDecl *FP =
360 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000361 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000362 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000363 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000364 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
365 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000366}
367
Chris Lattnerf04da132007-10-24 17:06:59 +0000368/// HandleDeclInMainFile - This is called for each top-level decl defined in the
369/// main file of the input.
370void RewriteTest::HandleDeclInMainFile(Decl *D) {
371 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
372 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000373 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000374
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000375 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000376 if (Stmt *Body = MD->getBody()) {
377 //Body->dump();
378 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000379 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000380 CurMethodDecl = 0;
381 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000382 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000383 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000384 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000385 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000386 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000387 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000388 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000389 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000390 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000391 if (VD->getInit())
392 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
393 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000394 // Nothing yet.
395}
396
397RewriteTest::~RewriteTest() {
398 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000399
400 // Rewrite tabs if we care.
401 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000402
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000403 RewriteInclude();
404
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000405 // Rewrite Objective-c meta data*
406 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000407 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000408
Chris Lattnerf04da132007-10-24 17:06:59 +0000409 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
410 // we are done.
411 if (const RewriteBuffer *RewriteBuf =
412 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000413 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000414 std::string S(RewriteBuf->begin(), RewriteBuf->end());
415 printf("%s\n", S.c_str());
416 } else {
417 printf("No changes\n");
418 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000419 // Emit metadata.
420 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000421}
422
Chris Lattnerf04da132007-10-24 17:06:59 +0000423//===----------------------------------------------------------------------===//
424// Syntactic (non-AST) Rewriting Code
425//===----------------------------------------------------------------------===//
426
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000427void RewriteTest::RewriteInclude() {
428 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
429 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
430 const char *MainBufStart = MainBuf.first;
431 const char *MainBufEnd = MainBuf.second;
432 size_t ImportLen = strlen("import");
433 size_t IncludeLen = strlen("include");
434
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000435 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000436 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
437 if (*BufPtr == '#') {
438 if (++BufPtr == MainBufEnd)
439 return;
440 while (*BufPtr == ' ' || *BufPtr == '\t')
441 if (++BufPtr == MainBufEnd)
442 return;
443 if (!strncmp(BufPtr, "import", ImportLen)) {
444 // replace import with include
445 SourceLocation ImportLoc =
446 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000447 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000448 BufPtr += ImportLen;
449 }
450 }
451 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000452}
453
Chris Lattnerf04da132007-10-24 17:06:59 +0000454void RewriteTest::RewriteTabs() {
455 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
456 const char *MainBufStart = MainBuf.first;
457 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000458
Chris Lattnerf04da132007-10-24 17:06:59 +0000459 // Loop over the whole file, looking for tabs.
460 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
461 if (*BufPtr != '\t')
462 continue;
463
464 // Okay, we found a tab. This tab will turn into at least one character,
465 // but it depends on which 'virtual column' it is in. Compute that now.
466 unsigned VCol = 0;
467 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
468 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
469 ++VCol;
470
471 // Okay, now that we know the virtual column, we know how many spaces to
472 // insert. We assume 8-character tab-stops.
473 unsigned Spaces = 8-(VCol & 7);
474
475 // Get the location of the tab.
476 SourceLocation TabLoc =
477 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
478
479 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000480 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000481 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000482}
483
484
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000485void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000486 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000487 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000488
489 // Get the start location and compute the semi location.
490 SourceLocation startLoc = ClassDecl->getLocation();
491 const char *startBuf = SM->getCharacterData(startLoc);
492 const char *semiPtr = strchr(startBuf, ';');
493
494 // Translate to typedef's that forward reference structs with the same name
495 // as the class. As a convenience, we include the original declaration
496 // as a comment.
497 std::string typedefString;
498 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000499 typedefString.append(startBuf, semiPtr-startBuf+1);
500 typedefString += "\n";
501 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000502 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000503 typedefString += "#ifndef _REWRITER_typedef_";
504 typedefString += ForwardDecl->getName();
505 typedefString += "\n";
506 typedefString += "#define _REWRITER_typedef_";
507 typedefString += ForwardDecl->getName();
508 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000509 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000510 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000511 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000512 }
513
514 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000515 ReplaceText(startLoc, semiPtr-startBuf+1,
516 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000517}
518
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000519void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000520 SourceLocation LocStart = Method->getLocStart();
521 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000522
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000523 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000524 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000525 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000526 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000527 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000528 }
529}
530
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000531void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000532{
533 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000534 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000535 SourceLocation Loc = Property->getLocation();
536
Chris Lattneraadaf782008-01-31 19:51:04 +0000537 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000538
539 // FIXME: handle properties that are declared across multiple lines.
540 }
541}
542
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000543void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000544 SourceLocation LocStart = CatDecl->getLocStart();
545
546 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000547 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000548
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000549 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000550 E = CatDecl->instmeth_end(); I != E; ++I)
551 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000552 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000553 E = CatDecl->classmeth_end(); I != E; ++I)
554 RewriteMethodDeclaration(*I);
555
Steve Naroff423cb562007-10-30 13:30:57 +0000556 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000557 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000558}
559
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000560void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000561 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000562
Steve Naroff752d6ef2007-10-30 16:42:30 +0000563 SourceLocation LocStart = PDecl->getLocStart();
564
565 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000566 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000567
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000568 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000569 E = PDecl->instmeth_end(); I != E; ++I)
570 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000571 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000572 E = PDecl->classmeth_end(); I != E; ++I)
573 RewriteMethodDeclaration(*I);
574
Steve Naroff752d6ef2007-10-30 16:42:30 +0000575 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000576 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000577 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000578
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000579 // Must comment out @optional/@required
580 const char *startBuf = SM->getCharacterData(LocStart);
581 const char *endBuf = SM->getCharacterData(LocEnd);
582 for (const char *p = startBuf; p < endBuf; p++) {
583 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
584 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000585 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000586 ReplaceText(OptionalLoc, strlen("@optional"),
587 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000588
589 }
590 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
591 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000592 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000593 ReplaceText(OptionalLoc, strlen("@required"),
594 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000595
596 }
597 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000598}
599
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000600void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000601 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000602 if (LocStart.isInvalid())
603 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000604 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000605 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000606}
607
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000608void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000609 std::string &ResultStr) {
610 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000611 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000612 ResultStr += "id";
613 else
614 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000615 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000616
617 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000618 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000619
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000620 if (OMD->isInstance())
621 NameStr += "_I_";
622 else
623 NameStr += "_C_";
624
625 NameStr += OMD->getClassInterface()->getName();
626 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000627
628 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000629 if (ObjCCategoryImplDecl *CID =
630 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000631 NameStr += CID->getName();
632 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000633 }
634 // Append selector names, replacing ':' with '_'
635 const char *selName = OMD->getSelector().getName().c_str();
636 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000637 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000638 else {
639 std::string selString = OMD->getSelector().getName();
640 int len = selString.size();
641 for (int i = 0; i < len; i++)
642 if (selString[i] == ':')
643 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000644 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000645 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000646 // Remember this name for metadata emission
647 MethodInternalNames[OMD] = NameStr;
648 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000649
650 // Rewrite arguments
651 ResultStr += "(";
652
653 // invisible arguments
654 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000655 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000656 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000657 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000658 ResultStr += "struct ";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000659 ResultStr += OMD->getClassInterface()->getName();
660 if (LangOpts.Microsoft)
661 ResultStr += "_IMPL";
662 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000663 }
664 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000665 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000666
667 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000668 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000669 ResultStr += " _cmd";
670
671 // Method arguments.
672 for (int i = 0; i < OMD->getNumParams(); i++) {
673 ParmVarDecl *PDecl = OMD->getParamDecl(i);
674 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000675 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000676 ResultStr += "id";
677 else
678 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000679 ResultStr += " ";
680 ResultStr += PDecl->getName();
681 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000682 if (OMD->isVariadic())
683 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000684 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000685
686}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000687void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
689 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000690
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000691 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000692 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000693 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000694 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000695
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000696 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000697 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
698 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000699 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000700 ObjCMethodDecl *OMD = *I;
701 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000702 SourceLocation LocStart = OMD->getLocStart();
703 SourceLocation LocEnd = OMD->getBody()->getLocStart();
704
705 const char *startBuf = SM->getCharacterData(LocStart);
706 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000707 ReplaceText(LocStart, endBuf-startBuf,
708 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000709 }
710
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000712 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
713 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000714 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000715 ObjCMethodDecl *OMD = *I;
716 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000717 SourceLocation LocStart = OMD->getLocStart();
718 SourceLocation LocEnd = OMD->getBody()->getLocStart();
719
720 const char *startBuf = SM->getCharacterData(LocStart);
721 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000722 ReplaceText(LocStart, endBuf-startBuf,
723 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000724 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000725 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000726 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000727 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000728 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000729}
730
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000731void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000732 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000733 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000734 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000735 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000736 ResultStr += ClassDecl->getName();
737 ResultStr += "\n";
738 ResultStr += "#define _REWRITER_typedef_";
739 ResultStr += ClassDecl->getName();
740 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000741 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000742 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000743 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000744 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000745 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000746 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000747 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000748
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000749 RewriteProperties(ClassDecl->getNumPropertyDecl(),
750 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000751 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000752 E = ClassDecl->instmeth_end(); I != E; ++I)
753 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000754 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000755 E = ClassDecl->classmeth_end(); I != E; ++I)
756 RewriteMethodDeclaration(*I);
757
Steve Naroff2feac5e2007-10-30 03:43:13 +0000758 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000759 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000760}
761
Steve Naroff7e3411b2007-11-15 02:58:25 +0000762Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000763 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000764 if (IV->isFreeIvar()) {
765 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
Eli Friedman51019072008-02-06 22:48:16 +0000766 IV->getLocation(), D->getType());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000767 ReplaceStmt(IV, Replacement);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000768 delete IV;
769 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000770 } else {
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000771#if 0
772 /// This code is not right. It seems unnecessary. It breaks use of
773 /// ivar reference used as 'receiver' of an expression; as in:
774 /// [newInv->_container addObject:0];
Steve Naroffc2a689b2007-11-15 11:33:00 +0000775 if (CurMethodDecl) {
776 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000777 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000778 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
779 IdentifierInfo *II = intT->getDecl()->getIdentifier();
780 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
781 II, 0);
782 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
783
784 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
785 // Don't forget the parens to enforce the proper binding.
786 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000787 ReplaceStmt(IV->getBase(), PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +0000788 delete IV->getBase();
789 return PE;
790 }
791 }
792 }
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000793#endif
Steve Naroff7e3411b2007-11-15 02:58:25 +0000794 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000795 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000796}
797
Chris Lattnerf04da132007-10-24 17:06:59 +0000798//===----------------------------------------------------------------------===//
799// Function Body / Expression rewriting
800//===----------------------------------------------------------------------===//
801
Steve Narofff3473a72007-11-09 15:20:18 +0000802Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000803 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
804 isa<DoStmt>(S) || isa<ForStmt>(S))
805 Stmts.push_back(S);
806 else if (isa<ObjCForCollectionStmt>(S)) {
807 Stmts.push_back(S);
808 ObjCBcLabelNo.push_back(++BcLabelCount);
809 }
810
Chris Lattner338d1e22008-01-31 05:10:40 +0000811 SourceLocation OrigStmtEnd = S->getLocEnd();
812
813 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000814 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
815 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000816 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000817 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000818 if (newStmt)
819 *CI = newStmt;
820 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000821
822 // Handle specific things.
823 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
824 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000825
826 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
827 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000828
829 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
830 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000831
Steve Naroffbeaf2992007-11-03 11:27:19 +0000832 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
833 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000834
Steve Naroff934f2762007-10-24 22:48:43 +0000835 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
836 // Before we rewrite it, put the original message expression in a comment.
837 SourceLocation startLoc = MessExpr->getLocStart();
838 SourceLocation endLoc = MessExpr->getLocEnd();
839
840 const char *startBuf = SM->getCharacterData(startLoc);
841 const char *endBuf = SM->getCharacterData(endLoc);
842
843 std::string messString;
844 messString += "// ";
845 messString.append(startBuf, endBuf-startBuf+1);
846 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000847
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000848 // FIXME: Missing definition of
849 // InsertText(clang::SourceLocation, char const*, unsigned int).
850 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000851 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000852 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000853 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000854 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000855
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000856 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
857 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000858
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000859 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
860 return RewriteObjCSynchronizedStmt(StmtTry);
861
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000862 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
863 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000864
865 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
866 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000867
868 if (ObjCForCollectionStmt *StmtForCollection =
869 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000870 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000871 if (BreakStmt *StmtBreakStmt =
872 dyn_cast<BreakStmt>(S))
873 return RewriteBreakStmt(StmtBreakStmt);
874 if (ContinueStmt *StmtContinueStmt =
875 dyn_cast<ContinueStmt>(S))
876 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000877
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000878 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
879 isa<DoStmt>(S) || isa<ForStmt>(S)) {
880 assert(!Stmts.empty() && "Statement stack is empty");
881 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
882 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
883 && "Statement stack mismatch");
884 Stmts.pop_back();
885 }
Steve Naroff874e2322007-11-15 10:28:18 +0000886#if 0
887 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
888 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
889 // Get the new text.
890 std::ostringstream Buf;
891 Replacement->printPretty(Buf);
892 const std::string &Str = Buf.str();
893
894 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000895 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000896 delete S;
897 return Replacement;
898 }
899#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000900 // Return this stmt unmodified.
901 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000902}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000903
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000904/// SynthCountByEnumWithState - To print:
905/// ((unsigned int (*)
906/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
907/// (void *)objc_msgSend)((id)l_collection,
908/// sel_registerName(
909/// "countByEnumeratingWithState:objects:count:"),
910/// &enumState,
911/// (id *)items, (unsigned int)16)
912///
913void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
914 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
915 "id *, unsigned int))(void *)objc_msgSend)";
916 buf += "\n\t\t";
917 buf += "((id)l_collection,\n\t\t";
918 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
919 buf += "\n\t\t";
920 buf += "&enumState, "
921 "(id *)items, (unsigned int)16)";
922}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000923
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000924/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
925/// statement to exit to its outer synthesized loop.
926///
927Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
928 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
929 return S;
930 // replace break with goto __break_label
931 std::string buf;
932
933 SourceLocation startLoc = S->getLocStart();
934 buf = "goto __break_label_";
935 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000936 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000937
938 return 0;
939}
940
941/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
942/// statement to continue with its inner synthesized loop.
943///
944Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
945 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
946 return S;
947 // replace continue with goto __continue_label
948 std::string buf;
949
950 SourceLocation startLoc = S->getLocStart();
951 buf = "goto __continue_label_";
952 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000953 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000954
955 return 0;
956}
957
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000958/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000959/// It rewrites:
960/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000961
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000962/// Into:
963/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000964/// type elem;
965/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000966/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000967/// id l_collection = (id)collection;
968/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
969/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000970/// if (limit) {
971/// unsigned long startMutations = *enumState.mutationsPtr;
972/// do {
973/// unsigned long counter = 0;
974/// do {
975/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000976/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000977/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000978/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000979/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000980/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000981/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
982/// objects:items count:16]);
983/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000984/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000985/// }
986/// else
987/// elem = nil;
988/// }
989///
Chris Lattner338d1e22008-01-31 05:10:40 +0000990Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
991 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000992 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
993 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
994 "ObjCForCollectionStmt Statement stack mismatch");
995 assert(!ObjCBcLabelNo.empty() &&
996 "ObjCForCollectionStmt - Label No stack empty");
997
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000998 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000999 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001000 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001001 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001002 std::string buf;
1003 buf = "\n{\n\t";
1004 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1005 // type elem;
1006 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001007 elementTypeAsString = ElementType.getAsString();
1008 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001009 buf += " ";
1010 elementName = DS->getDecl()->getName();
1011 buf += elementName;
1012 buf += ";\n\t";
1013 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001014 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001015 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001016 elementTypeAsString = DR->getDecl()->getType().getAsString();
1017 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001018 else
1019 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1020
1021 // struct __objcFastEnumerationState enumState = { 0 };
1022 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1023 // id items[16];
1024 buf += "id items[16];\n\t";
1025 // id l_collection = (id)
1026 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001027 // Find start location of 'collection' the hard way!
1028 const char *startCollectionBuf = startBuf;
1029 startCollectionBuf += 3; // skip 'for'
1030 startCollectionBuf = strchr(startCollectionBuf, '(');
1031 startCollectionBuf++; // skip '('
1032 // find 'in' and skip it.
1033 while (*startCollectionBuf != ' ' ||
1034 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1035 (*(startCollectionBuf+3) != ' ' &&
1036 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1037 startCollectionBuf++;
1038 startCollectionBuf += 3;
1039
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001040 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001041 ReplaceText(startLoc, startCollectionBuf - startBuf,
1042 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001043 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001044 SourceLocation rightParenLoc = S->getRParenLoc();
1045 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1046 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001047 buf = ";\n\t";
1048
1049 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1050 // objects:items count:16];
1051 // which is synthesized into:
1052 // unsigned int limit =
1053 // ((unsigned int (*)
1054 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1055 // (void *)objc_msgSend)((id)l_collection,
1056 // sel_registerName(
1057 // "countByEnumeratingWithState:objects:count:"),
1058 // (struct __objcFastEnumerationState *)&state,
1059 // (id *)items, (unsigned int)16);
1060 buf += "unsigned long limit =\n\t\t";
1061 SynthCountByEnumWithState(buf);
1062 buf += ";\n\t";
1063 /// if (limit) {
1064 /// unsigned long startMutations = *enumState.mutationsPtr;
1065 /// do {
1066 /// unsigned long counter = 0;
1067 /// do {
1068 /// if (startMutations != *enumState.mutationsPtr)
1069 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001070 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001071 buf += "if (limit) {\n\t";
1072 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1073 buf += "do {\n\t\t";
1074 buf += "unsigned long counter = 0;\n\t\t";
1075 buf += "do {\n\t\t\t";
1076 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1077 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1078 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001079 buf += " = (";
1080 buf += elementTypeAsString;
1081 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001082 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001083 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001084
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001085 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001086 /// } while (counter < limit);
1087 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1088 /// objects:items count:16]);
1089 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001090 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001091 /// }
1092 /// else
1093 /// elem = nil;
1094 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001095 ///
1096 buf = ";\n\t";
1097 buf += "__continue_label_";
1098 buf += utostr(ObjCBcLabelNo.back());
1099 buf += ": ;";
1100 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001101 buf += "} while (counter < limit);\n\t";
1102 buf += "} while (limit = ";
1103 SynthCountByEnumWithState(buf);
1104 buf += ");\n\t";
1105 buf += elementName;
1106 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001107 buf += "__break_label_";
1108 buf += utostr(ObjCBcLabelNo.back());
1109 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001110 buf += "}\n\t";
1111 buf += "else\n\t\t";
1112 buf += elementName;
1113 buf += " = nil;\n";
1114 buf += "}\n";
1115 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001116 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001117 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001118 Stmts.pop_back();
1119 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001120 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001121}
1122
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001123/// RewriteObjCSynchronizedStmt -
1124/// This routine rewrites @synchronized(expr) stmt;
1125/// into:
1126/// objc_sync_enter(expr);
1127/// @try stmt @finally { objc_sync_exit(expr); }
1128///
1129Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1130 // Get the start location and compute the semi location.
1131 SourceLocation startLoc = S->getLocStart();
1132 const char *startBuf = SM->getCharacterData(startLoc);
1133
1134 assert((*startBuf == '@') && "bogus @synchronized location");
1135
1136 std::string buf;
1137 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001138 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001139 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1140 const char *endBuf = SM->getCharacterData(endLoc);
1141 endBuf++;
1142 const char *rparenBuf = strchr(endBuf, ')');
1143 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1144 buf = ");\n";
1145 // declare a new scope with two variables, _stack and _rethrow.
1146 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1147 buf += "int buf[18/*32-bit i386*/];\n";
1148 buf += "char *pointers[4];} _stack;\n";
1149 buf += "id volatile _rethrow = 0;\n";
1150 buf += "objc_exception_try_enter(&_stack);\n";
1151 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001152 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001153 startLoc = S->getSynchBody()->getLocEnd();
1154 startBuf = SM->getCharacterData(startLoc);
1155
1156 assert((*startBuf == '}') && "bogus @try block");
1157 SourceLocation lastCurlyLoc = startLoc;
1158 buf = "}\nelse {\n";
1159 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1160 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1161 // FIXME: This must be objc_sync_exit(syncExpr);
1162 buf += " objc_sync_exit();\n";
1163 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1164 buf += "}\n";
1165 buf += "}";
1166
Chris Lattneraadaf782008-01-31 19:51:04 +00001167 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001168 return 0;
1169}
1170
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001171Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001172 // Get the start location and compute the semi location.
1173 SourceLocation startLoc = S->getLocStart();
1174 const char *startBuf = SM->getCharacterData(startLoc);
1175
1176 assert((*startBuf == '@') && "bogus @try location");
1177
1178 std::string buf;
1179 // declare a new scope with two variables, _stack and _rethrow.
1180 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1181 buf += "int buf[18/*32-bit i386*/];\n";
1182 buf += "char *pointers[4];} _stack;\n";
1183 buf += "id volatile _rethrow = 0;\n";
1184 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001185 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001186
Chris Lattneraadaf782008-01-31 19:51:04 +00001187 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001188
1189 startLoc = S->getTryBody()->getLocEnd();
1190 startBuf = SM->getCharacterData(startLoc);
1191
1192 assert((*startBuf == '}') && "bogus @try block");
1193
1194 SourceLocation lastCurlyLoc = startLoc;
1195
1196 startLoc = startLoc.getFileLocWithOffset(1);
1197 buf = " /* @catch begin */ else {\n";
1198 buf += " id _caught = objc_exception_extract(&_stack);\n";
1199 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001200 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001201 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1202 buf += " else { /* @catch continue */";
1203
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001204 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001205
1206 bool sawIdTypedCatch = false;
1207 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001208 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001209 while (catchList) {
1210 Stmt *catchStmt = catchList->getCatchParamStmt();
1211
1212 if (catchList == S->getCatchStmts())
1213 buf = "if ("; // we are generating code for the first catch clause
1214 else
1215 buf = "else if (";
1216 startLoc = catchList->getLocStart();
1217 startBuf = SM->getCharacterData(startLoc);
1218
1219 assert((*startBuf == '@') && "bogus @catch location");
1220
1221 const char *lParenLoc = strchr(startBuf, '(');
1222
Steve Naroffbe4b3332008-02-01 22:08:12 +00001223 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001224 // Now rewrite the body...
1225 lastCatchBody = catchList->getCatchBody();
1226 SourceLocation rParenLoc = catchList->getRParenLoc();
1227 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1228 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1229 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1230 assert((*rParenBuf == ')') && "bogus @catch paren location");
1231 assert((*bodyBuf == '{') && "bogus @catch body location");
1232
1233 buf += "1) { id _tmp = _caught;";
1234 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1235 buf.c_str(), buf.size());
1236 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001237 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001238 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001239 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001240 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001241 sawIdTypedCatch = true;
1242 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001243 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001244
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001245 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001246 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001247 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001248 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001249 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001250 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001251 }
1252 }
1253 // Now rewrite the body...
1254 lastCatchBody = catchList->getCatchBody();
1255 SourceLocation rParenLoc = catchList->getRParenLoc();
1256 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1257 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1258 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1259 assert((*rParenBuf == ')') && "bogus @catch paren location");
1260 assert((*bodyBuf == '{') && "bogus @catch body location");
1261
1262 buf = " = _caught;";
1263 // Here we replace ") {" with "= _caught;" (which initializes and
1264 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001265 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001266 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001267 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001268 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001269 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001270 catchList = catchList->getNextCatchStmt();
1271 }
1272 // Complete the catch list...
1273 if (lastCatchBody) {
1274 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1275 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1276 assert((*bodyBuf == '}') && "bogus @catch body location");
1277 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1278 buf = " } } /* @catch end */\n";
1279
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001280 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001281
1282 // Set lastCurlyLoc
1283 lastCurlyLoc = lastCatchBody->getLocEnd();
1284 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001285 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001286 startLoc = finalStmt->getLocStart();
1287 startBuf = SM->getCharacterData(startLoc);
1288 assert((*startBuf == '@') && "bogus @finally start");
1289
1290 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001291 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001292
1293 Stmt *body = finalStmt->getFinallyBody();
1294 SourceLocation startLoc = body->getLocStart();
1295 SourceLocation endLoc = body->getLocEnd();
1296 const char *startBuf = SM->getCharacterData(startLoc);
1297 const char *endBuf = SM->getCharacterData(endLoc);
1298 assert((*startBuf == '{') && "bogus @finally body location");
1299 assert((*endBuf == '}') && "bogus @finally body location");
1300
1301 startLoc = startLoc.getFileLocWithOffset(1);
1302 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001303 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001304 endLoc = endLoc.getFileLocWithOffset(-1);
1305 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001306 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001307
1308 // Set lastCurlyLoc
1309 lastCurlyLoc = body->getLocEnd();
1310 }
1311 // Now emit the final closing curly brace...
1312 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1313 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001314 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001315 return 0;
1316}
1317
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001318Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001319 return 0;
1320}
1321
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001322Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001323 return 0;
1324}
1325
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001326// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001327// the throw expression is typically a message expression that's already
1328// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001329Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001330 // Get the start location and compute the semi location.
1331 SourceLocation startLoc = S->getLocStart();
1332 const char *startBuf = SM->getCharacterData(startLoc);
1333
1334 assert((*startBuf == '@') && "bogus @throw location");
1335
1336 std::string buf;
1337 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001338 if (S->getThrowExpr())
1339 buf = "objc_exception_throw(";
1340 else // add an implicit argument
1341 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001342 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001343 const char *semiBuf = strchr(startBuf, ';');
1344 assert((*semiBuf == ';') && "@throw: can't find ';'");
1345 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1346 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001347 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001348 return 0;
1349}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001350
Chris Lattnere64b7772007-10-24 16:57:36 +00001351Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001352 // Create a new string expression.
1353 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001354 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001355 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1356 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001357 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1358 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001359 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001360 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001361
Chris Lattner07506182007-11-30 22:53:43 +00001362 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001363 delete Exp;
1364 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001365}
1366
Steve Naroffb42f8412007-11-05 14:50:49 +00001367Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1368 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1369 // Create a call to sel_registerName("selName").
1370 llvm::SmallVector<Expr*, 8> SelExprs;
1371 QualType argType = Context->getPointerType(Context->CharTy);
1372 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1373 Exp->getSelector().getName().size(),
1374 false, argType, SourceLocation(),
1375 SourceLocation()));
1376 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1377 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001378 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001379 delete Exp;
1380 return SelExp;
1381}
1382
Steve Naroff934f2762007-10-24 22:48:43 +00001383CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1384 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001385 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001386 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001387
1388 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001389 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001390
1391 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001392 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001393 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1394
1395 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001396
Steve Naroff934f2762007-10-24 22:48:43 +00001397 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1398}
1399
Steve Naroffd5255f52007-11-01 13:24:47 +00001400static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1401 const char *&startRef, const char *&endRef) {
1402 while (startBuf < endBuf) {
1403 if (*startBuf == '<')
1404 startRef = startBuf; // mark the start.
1405 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001406 if (startRef && *startRef == '<') {
1407 endRef = startBuf; // mark the end.
1408 return true;
1409 }
1410 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001411 }
1412 startBuf++;
1413 }
1414 return false;
1415}
1416
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001417static void scanToNextArgument(const char *&argRef) {
1418 int angle = 0;
1419 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1420 if (*argRef == '<')
1421 angle++;
1422 else if (*argRef == '>')
1423 angle--;
1424 argRef++;
1425 }
1426 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1427}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001428
Steve Naroffd5255f52007-11-01 13:24:47 +00001429bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001430
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001431 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001432 return true;
1433
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001434 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001435 return true;
1436
Steve Naroffd5255f52007-11-01 13:24:47 +00001437 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001438 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001439 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001440 return true; // we have "Class <Protocol> *".
1441 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001442 return false;
1443}
1444
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001445void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001446 SourceLocation Loc;
1447 QualType Type;
1448 const FunctionTypeProto *proto = 0;
1449 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1450 Loc = VD->getLocation();
1451 Type = VD->getType();
1452 }
1453 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1454 Loc = FD->getLocation();
1455 // Check for ObjC 'id' and class types that have been adorned with protocol
1456 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1457 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1458 assert(funcType && "missing function type");
1459 proto = dyn_cast<FunctionTypeProto>(funcType);
1460 if (!proto)
1461 return;
1462 Type = proto->getResultType();
1463 }
1464 else
1465 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001466
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001467 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001468 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001469
1470 const char *endBuf = SM->getCharacterData(Loc);
1471 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001472 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001473 startBuf--; // scan backward (from the decl location) for return type.
1474 const char *startRef = 0, *endRef = 0;
1475 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1476 // Get the locations of the startRef, endRef.
1477 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1478 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1479 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001480 InsertText(LessLoc, "/*", 2);
1481 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001482 }
1483 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001484 if (!proto)
1485 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001486 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001487 const char *startBuf = SM->getCharacterData(Loc);
1488 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001489 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1490 if (needToScanForQualifiers(proto->getArgType(i))) {
1491 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001492
Steve Naroffd5255f52007-11-01 13:24:47 +00001493 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001494 // scan forward (from the decl location) for argument types.
1495 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001496 const char *startRef = 0, *endRef = 0;
1497 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1498 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001499 SourceLocation LessLoc =
1500 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1501 SourceLocation GreaterLoc =
1502 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001503 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001504 InsertText(LessLoc, "/*", 2);
1505 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001506 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001507 startBuf = ++endBuf;
1508 }
1509 else {
1510 while (*startBuf != ')' && *startBuf != ',')
1511 startBuf++; // scan forward (from the decl location) for argument types.
1512 startBuf++;
1513 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001514 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001515}
1516
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001517// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1518void RewriteTest::SynthSelGetUidFunctionDecl() {
1519 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1520 llvm::SmallVector<QualType, 16> ArgTys;
1521 ArgTys.push_back(Context->getPointerType(
1522 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001523 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001524 &ArgTys[0], ArgTys.size(),
1525 false /*isVariadic*/);
1526 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1527 SelGetUidIdent, getFuncType,
1528 FunctionDecl::Extern, false, 0);
1529}
1530
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001531// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1532void RewriteTest::SynthGetProtocolFunctionDecl() {
1533 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1534 llvm::SmallVector<QualType, 16> ArgTys;
1535 ArgTys.push_back(Context->getPointerType(
1536 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001537 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001538 &ArgTys[0], ArgTys.size(),
1539 false /*isVariadic*/);
1540 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1541 SelGetProtoIdent, getFuncType,
1542 FunctionDecl::Extern, false, 0);
1543}
1544
Steve Naroff09b266e2007-10-30 23:14:51 +00001545void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1546 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001547 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001548 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001549 return;
1550 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001551 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001552}
1553
Steve Naroffc0a123c2008-03-11 17:37:02 +00001554// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1555void RewriteTest::SynthSuperContructorFunctionDecl() {
1556 if (SuperContructorFunctionDecl)
1557 return;
1558 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1559 llvm::SmallVector<QualType, 16> ArgTys;
1560 QualType argT = Context->getObjCIdType();
1561 assert(!argT.isNull() && "Can't find 'id' type");
1562 ArgTys.push_back(argT);
1563 ArgTys.push_back(argT);
1564 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1565 &ArgTys[0], ArgTys.size(),
1566 false);
1567 SuperContructorFunctionDecl = new FunctionDecl(SourceLocation(),
1568 msgSendIdent, msgSendType,
1569 FunctionDecl::Extern, false, 0);
1570}
1571
Steve Naroff09b266e2007-10-30 23:14:51 +00001572// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1573void RewriteTest::SynthMsgSendFunctionDecl() {
1574 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1575 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001576 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001577 assert(!argT.isNull() && "Can't find 'id' type");
1578 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001579 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001580 assert(!argT.isNull() && "Can't find 'SEL' type");
1581 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001582 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001583 &ArgTys[0], ArgTys.size(),
1584 true /*isVariadic*/);
1585 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1586 msgSendIdent, msgSendType,
1587 FunctionDecl::Extern, false, 0);
1588}
1589
Steve Naroff874e2322007-11-15 10:28:18 +00001590// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1591void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1592 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1593 llvm::SmallVector<QualType, 16> ArgTys;
1594 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1595 &Context->Idents.get("objc_super"), 0);
1596 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1597 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1598 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001599 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001600 assert(!argT.isNull() && "Can't find 'SEL' type");
1601 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001602 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001603 &ArgTys[0], ArgTys.size(),
1604 true /*isVariadic*/);
1605 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1606 msgSendIdent, msgSendType,
1607 FunctionDecl::Extern, false, 0);
1608}
1609
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001610// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1611void RewriteTest::SynthMsgSendStretFunctionDecl() {
1612 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1613 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001614 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001615 assert(!argT.isNull() && "Can't find 'id' type");
1616 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001617 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001618 assert(!argT.isNull() && "Can't find 'SEL' type");
1619 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001620 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001621 &ArgTys[0], ArgTys.size(),
1622 true /*isVariadic*/);
1623 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1624 msgSendIdent, msgSendType,
1625 FunctionDecl::Extern, false, 0);
1626}
1627
1628// SynthMsgSendSuperStretFunctionDecl -
1629// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1630void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1631 IdentifierInfo *msgSendIdent =
1632 &Context->Idents.get("objc_msgSendSuper_stret");
1633 llvm::SmallVector<QualType, 16> ArgTys;
1634 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1635 &Context->Idents.get("objc_super"), 0);
1636 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1637 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1638 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001639 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001640 assert(!argT.isNull() && "Can't find 'SEL' type");
1641 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001642 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001643 &ArgTys[0], ArgTys.size(),
1644 true /*isVariadic*/);
1645 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1646 msgSendIdent, msgSendType,
1647 FunctionDecl::Extern, false, 0);
1648}
1649
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001650// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1651void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1652 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1653 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001654 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001655 assert(!argT.isNull() && "Can't find 'id' type");
1656 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001657 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001658 assert(!argT.isNull() && "Can't find 'SEL' type");
1659 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001660 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001661 &ArgTys[0], ArgTys.size(),
1662 true /*isVariadic*/);
1663 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1664 msgSendIdent, msgSendType,
1665 FunctionDecl::Extern, false, 0);
1666}
1667
Steve Naroff09b266e2007-10-30 23:14:51 +00001668// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1669void RewriteTest::SynthGetClassFunctionDecl() {
1670 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1671 llvm::SmallVector<QualType, 16> ArgTys;
1672 ArgTys.push_back(Context->getPointerType(
1673 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001674 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001675 &ArgTys[0], ArgTys.size(),
1676 false /*isVariadic*/);
1677 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1678 getClassIdent, getClassType,
1679 FunctionDecl::Extern, false, 0);
1680}
1681
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001682// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1683void RewriteTest::SynthGetMetaClassFunctionDecl() {
1684 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1685 llvm::SmallVector<QualType, 16> ArgTys;
1686 ArgTys.push_back(Context->getPointerType(
1687 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001688 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001689 &ArgTys[0], ArgTys.size(),
1690 false /*isVariadic*/);
1691 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1692 getClassIdent, getClassType,
1693 FunctionDecl::Extern, false, 0);
1694}
1695
Steve Naroff96984642007-11-08 14:30:50 +00001696// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1697void RewriteTest::SynthCFStringFunctionDecl() {
1698 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1699 llvm::SmallVector<QualType, 16> ArgTys;
1700 ArgTys.push_back(Context->getPointerType(
1701 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001702 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001703 &ArgTys[0], ArgTys.size(),
1704 false /*isVariadic*/);
1705 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1706 getClassIdent, getClassType,
1707 FunctionDecl::Extern, false, 0);
1708}
1709
Steve Naroffbeaf2992007-11-03 11:27:19 +00001710Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001711#if 1
1712 // This rewrite is specific to GCC, which has builtin support for CFString.
1713 if (!CFStringFunctionDecl)
1714 SynthCFStringFunctionDecl();
1715 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1716 llvm::SmallVector<Expr*, 8> StrExpr;
1717 StrExpr.push_back(Exp->getString());
1718 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1719 &StrExpr[0], StrExpr.size());
1720 // cast to NSConstantString *
1721 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001722 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001723 delete Exp;
1724 return cast;
1725#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001726 assert(ConstantStringClassReference && "Can't find constant string reference");
1727 llvm::SmallVector<Expr*, 4> InitExprs;
1728
1729 // Synthesize "(Class)&_NSConstantStringClassReference"
1730 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1731 ConstantStringClassReference->getType(),
1732 SourceLocation());
1733 QualType expType = Context->getPointerType(ClsRef->getType());
1734 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1735 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001736 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001737 SourceLocation());
1738 InitExprs.push_back(cast); // set the 'isa'.
1739 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1740 unsigned IntSize = static_cast<unsigned>(
1741 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1742 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1743 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1744 Exp->getLocStart());
1745 InitExprs.push_back(len); // set "int numBytes".
1746
1747 // struct NSConstantString
1748 QualType CFConstantStrType = Context->getCFConstantStringType();
1749 // (struct NSConstantString) { <exprs from above> }
1750 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1751 &InitExprs[0], InitExprs.size(),
1752 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001753 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001754 // struct NSConstantString *
1755 expType = Context->getPointerType(StrRep->getType());
1756 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1757 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001758 // cast to NSConstantString *
1759 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001760 ReplaceStmt(Exp, cast);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001761 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001762 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001763#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001764}
1765
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001766ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001767 // check if we are sending a message to 'super'
1768 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001769 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1770 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1771 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1772 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001773 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001774 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001775 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001776 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001777 if (ObjCInterfaceType *IT =
1778 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001779 if (IT->getDecl() ==
1780 CurMethodDecl->getClassInterface()->getSuperClass())
1781 return IT->getDecl();
1782 }
1783 }
1784 }
1785 }
1786 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001787 }
Steve Naroff874e2322007-11-15 10:28:18 +00001788 }
1789 return 0;
1790}
1791
1792// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1793QualType RewriteTest::getSuperStructType() {
1794 if (!SuperStructDecl) {
1795 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1796 &Context->Idents.get("objc_super"), 0);
1797 QualType FieldTypes[2];
1798
1799 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001800 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001801 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001802 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001803 // Create fields
1804 FieldDecl *FieldDecls[2];
1805
1806 for (unsigned i = 0; i < 2; ++i)
1807 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1808
1809 SuperStructDecl->defineBody(FieldDecls, 4);
1810 }
1811 return Context->getTagDeclType(SuperStructDecl);
1812}
1813
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001814Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001815 if (!SelGetUidFunctionDecl)
1816 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001817 if (!MsgSendFunctionDecl)
1818 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001819 if (!MsgSendSuperFunctionDecl)
1820 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001821 if (!MsgSendStretFunctionDecl)
1822 SynthMsgSendStretFunctionDecl();
1823 if (!MsgSendSuperStretFunctionDecl)
1824 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001825 if (!MsgSendFpretFunctionDecl)
1826 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001827 if (!GetClassFunctionDecl)
1828 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001829 if (!GetMetaClassFunctionDecl)
1830 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001831
Steve Naroff874e2322007-11-15 10:28:18 +00001832 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001833 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1834 // May need to use objc_msgSend_stret() as well.
1835 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001836 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001837 QualType resultType = mDecl->getResultType();
1838 if (resultType.getCanonicalType()->isStructureType()
1839 || resultType.getCanonicalType()->isUnionType())
1840 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001841 else if (resultType.getCanonicalType()->isRealFloatingType())
1842 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001843 }
Steve Naroff874e2322007-11-15 10:28:18 +00001844
Steve Naroff934f2762007-10-24 22:48:43 +00001845 // Synthesize a call to objc_msgSend().
1846 llvm::SmallVector<Expr*, 8> MsgExprs;
1847 IdentifierInfo *clsName = Exp->getClassName();
1848
1849 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1850 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001851 if (!strcmp(clsName->getName(), "super")) {
1852 MsgSendFlavor = MsgSendSuperFunctionDecl;
1853 if (MsgSendStretFlavor)
1854 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1855 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1856
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001857 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001858 CurMethodDecl->getClassInterface()->getSuperClass();
1859
1860 llvm::SmallVector<Expr*, 4> InitExprs;
1861
1862 // set the receiver to self, the first argument to all methods.
1863 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001864 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001865 SourceLocation()));
1866 llvm::SmallVector<Expr*, 8> ClsExprs;
1867 QualType argType = Context->getPointerType(Context->CharTy);
1868 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1869 SuperDecl->getIdentifier()->getLength(),
1870 false, argType, SourceLocation(),
1871 SourceLocation()));
1872 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1873 &ClsExprs[0],
1874 ClsExprs.size());
1875 // To turn off a warning, type-cast to 'id'
1876 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001877 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001878 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1879 // struct objc_super
1880 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001881 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001882
Steve Naroff23f41272008-03-11 18:14:26 +00001883 if (LangOpts.Microsoft) {
1884 SynthSuperContructorFunctionDecl();
1885 // Simulate a contructor call...
1886 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1887 superType, SourceLocation());
1888 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1889 superType, SourceLocation());
1890 } else {
1891 // (struct objc_super) { <exprs from above> }
1892 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1893 &InitExprs[0], InitExprs.size(),
1894 SourceLocation());
1895 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1896 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001897 // struct objc_super *
1898 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1899 Context->getPointerType(SuperRep->getType()),
1900 SourceLocation());
1901 MsgExprs.push_back(Unop);
1902 } else {
1903 llvm::SmallVector<Expr*, 8> ClsExprs;
1904 QualType argType = Context->getPointerType(Context->CharTy);
1905 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1906 clsName->getLength(),
1907 false, argType, SourceLocation(),
1908 SourceLocation()));
1909 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1910 &ClsExprs[0],
1911 ClsExprs.size());
1912 MsgExprs.push_back(Cls);
1913 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001914 } else { // instance message.
1915 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001916
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001917 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001918 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001919 if (MsgSendStretFlavor)
1920 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001921 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1922
1923 llvm::SmallVector<Expr*, 4> InitExprs;
1924
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001925 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001926 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001927 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001928
1929 llvm::SmallVector<Expr*, 8> ClsExprs;
1930 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001931 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1932 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001933 false, argType, SourceLocation(),
1934 SourceLocation()));
1935 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001936 &ClsExprs[0],
1937 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001938 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001939 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001940 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001941 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001942 // struct objc_super
1943 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00001944 Expr *SuperRep;
1945
1946 if (LangOpts.Microsoft) {
1947 SynthSuperContructorFunctionDecl();
1948 // Simulate a contructor call...
1949 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1950 superType, SourceLocation());
1951 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1952 superType, SourceLocation());
1953 } else {
1954 // (struct objc_super) { <exprs from above> }
1955 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1956 &InitExprs[0], InitExprs.size(),
1957 SourceLocation());
1958 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1959 }
Steve Naroff874e2322007-11-15 10:28:18 +00001960 // struct objc_super *
1961 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1962 Context->getPointerType(SuperRep->getType()),
1963 SourceLocation());
1964 MsgExprs.push_back(Unop);
1965 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001966 // Remove all type-casts because it may contain objc-style types; e.g.
1967 // Foo<Proto> *.
1968 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1969 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001970 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001971 MsgExprs.push_back(recExpr);
1972 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001973 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001974 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001975 llvm::SmallVector<Expr*, 8> SelExprs;
1976 QualType argType = Context->getPointerType(Context->CharTy);
1977 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1978 Exp->getSelector().getName().size(),
1979 false, argType, SourceLocation(),
1980 SourceLocation()));
1981 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1982 &SelExprs[0], SelExprs.size());
1983 MsgExprs.push_back(SelExp);
1984
1985 // Now push any user supplied arguments.
1986 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001987 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001988 // Make all implicit casts explicit...ICE comes in handy:-)
1989 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1990 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001991 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1992 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001993 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001994 }
1995 // Make id<P...> cast into an 'id' cast.
1996 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001997 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001998 while ((CE = dyn_cast<CastExpr>(userExpr)))
1999 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002000 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002001 userExpr, SourceLocation());
2002 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002003 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002004 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002005 // We've transferred the ownership to MsgExprs. Null out the argument in
2006 // the original expression, since we will delete it below.
2007 Exp->setArg(i, 0);
2008 }
Steve Naroffab972d32007-11-04 22:37:50 +00002009 // Generate the funky cast.
2010 CastExpr *cast;
2011 llvm::SmallVector<QualType, 8> ArgTypes;
2012 QualType returnType;
2013
2014 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002015 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2016 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2017 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002018 ArgTypes.push_back(Context->getObjCIdType());
2019 ArgTypes.push_back(Context->getObjCSelType());
2020 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002021 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00002022 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002023 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2024 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002025 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002026 ArgTypes.push_back(t);
2027 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002028 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2029 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002030 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002031 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002032 }
2033 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002034 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002035
2036 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002037 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2038 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002039
2040 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2041 // If we don't do this cast, we get the following bizarre warning/note:
2042 // xx.m:13: warning: function called through a non-compatible type
2043 // xx.m:13: note: if this code is reached, the program will abort
2044 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2045 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002046
Steve Naroffab972d32007-11-04 22:37:50 +00002047 // Now do the "normal" pointer to function cast.
2048 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002049 &ArgTypes[0], ArgTypes.size(),
2050 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00002051 castType = Context->getPointerType(castType);
2052 cast = new CastExpr(castType, cast, SourceLocation());
2053
2054 // Don't forget the parens to enforce the proper binding.
2055 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2056
2057 const FunctionType *FT = msgSendType->getAsFunctionType();
2058 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2059 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002060 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002061 if (MsgSendStretFlavor) {
2062 // We have the method which returns a struct/union. Must also generate
2063 // call to objc_msgSend_stret and hang both varieties on a conditional
2064 // expression which dictate which one to envoke depending on size of
2065 // method's return type.
2066
2067 // Create a reference to the objc_msgSend_stret() declaration.
2068 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2069 SourceLocation());
2070 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2071 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2072 SourceLocation());
2073 // Now do the "normal" pointer to function cast.
2074 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002075 &ArgTypes[0], ArgTypes.size(),
2076 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002077 castType = Context->getPointerType(castType);
2078 cast = new CastExpr(castType, cast, SourceLocation());
2079
2080 // Don't forget the parens to enforce the proper binding.
2081 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2082
2083 FT = msgSendType->getAsFunctionType();
2084 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2085 FT->getResultType(), SourceLocation());
2086
2087 // Build sizeof(returnType)
2088 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2089 returnType, Context->getSizeType(),
2090 SourceLocation(), SourceLocation());
2091 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2092 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2093 // For X86 it is more complicated and some kind of target specific routine
2094 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002095 unsigned IntSize =
2096 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002097 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2098 Context->IntTy,
2099 SourceLocation());
2100 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2101 BinaryOperator::LE,
2102 Context->IntTy,
2103 SourceLocation());
2104 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2105 ConditionalOperator *CondExpr =
2106 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002107 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002108 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002109 return ReplacingStmt;
2110}
2111
2112Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2113 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002114 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002115 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002116
Chris Lattnere64b7772007-10-24 16:57:36 +00002117 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002118 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002119}
2120
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002121/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2122/// call to objc_getProtocol("proto-name").
2123Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2124 if (!GetProtocolFunctionDecl)
2125 SynthGetProtocolFunctionDecl();
2126 // Create a call to objc_getProtocol("ProtocolName").
2127 llvm::SmallVector<Expr*, 8> ProtoExprs;
2128 QualType argType = Context->getPointerType(Context->CharTy);
2129 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2130 strlen(Exp->getProtocol()->getName()),
2131 false, argType, SourceLocation(),
2132 SourceLocation()));
2133 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2134 &ProtoExprs[0],
2135 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002136 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002137 delete Exp;
2138 return ProtoExp;
2139
2140}
2141
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002142/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002143/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002144void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002145 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002146 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2147 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002148 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002149 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002150 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002151 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002152 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002153 SourceLocation LocStart = CDecl->getLocStart();
2154 SourceLocation LocEnd = CDecl->getLocEnd();
2155
2156 const char *startBuf = SM->getCharacterData(LocStart);
2157 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002158 // If no ivars and no root or if its root, directly or indirectly,
2159 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002160 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002161 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002162 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002163 return;
2164 }
2165
2166 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002167 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002168 Result += "\nstruct ";
2169 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002170 if (LangOpts.Microsoft)
2171 Result += "_IMPL";
Steve Narofffea763e82007-11-14 19:25:57 +00002172
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002173 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002174 const char *cursor = strchr(startBuf, '{');
2175 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002176 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002177
2178 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002179 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002180 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002181 Result = "\n struct ";
2182 Result += RCDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002183 if (LangOpts.Microsoft)
2184 Result += "_IMPL";
Steve Narofff69cc5d2008-01-30 19:17:43 +00002185 // Note: We don't name the field decl. This simplifies the "codegen" for
2186 // accessing a superclasses instance variables (and is similar to what gcc
2187 // does internally). The unnamed struct field feature is enabled with
2188 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2189 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002190 Result += ";\n";
2191
2192 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002193 SourceLocation OnePastCurly =
2194 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2195 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002196 }
2197 cursor++; // past '{'
2198
2199 // Now comment out any visibility specifiers.
2200 while (cursor < endBuf) {
2201 if (*cursor == '@') {
2202 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002203 // Skip whitespace.
2204 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2205 /*scan*/;
2206
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002207 // FIXME: presence of @public, etc. inside comment results in
2208 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002209 if (!strncmp(cursor, "public", strlen("public")) ||
2210 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002211 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002212 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002213 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002214 // FIXME: If there are cases where '<' is used in ivar declaration part
2215 // of user code, then scan the ivar list and use needToScanForQualifiers
2216 // for type checking.
2217 else if (*cursor == '<') {
2218 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002219 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002220 cursor = strchr(cursor, '>');
2221 cursor++;
2222 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002223 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002224 }
Steve Narofffea763e82007-11-14 19:25:57 +00002225 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002226 }
Steve Narofffea763e82007-11-14 19:25:57 +00002227 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002228 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002229 } else { // we don't have any instance variables - insert super struct.
2230 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2231 Result += " {\n struct ";
2232 Result += RCDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002233 if (LangOpts.Microsoft)
2234 Result += "_IMPL";
Steve Narofff69cc5d2008-01-30 19:17:43 +00002235 // Note: We don't name the field decl. This simplifies the "codegen" for
2236 // accessing a superclasses instance variables (and is similar to what gcc
2237 // does internally). The unnamed struct field feature is enabled with
2238 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2239 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002240 Result += ";\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002241 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002242 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002243 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002244 if (!ObjCSynthesizedStructs.insert(CDecl))
2245 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002246}
2247
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002248// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002249/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002250void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002251 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002252 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002253 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002254 const char *ClassName,
2255 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002256 if (MethodBegin == MethodEnd) return;
2257
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002258 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002259 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002260 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002261 SEL _cmd;
2262 char *method_types;
2263 void *_imp;
2264 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002265 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002266 Result += "\nstruct _objc_method {\n";
2267 Result += "\tSEL _cmd;\n";
2268 Result += "\tchar *method_types;\n";
2269 Result += "\tvoid *_imp;\n";
2270 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002271
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002272 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002273 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002274
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002275 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002276
2277 /* struct {
2278 struct _objc_method_list *next_method;
2279 int method_count;
2280 struct _objc_method method_list[];
2281 }
2282 */
2283 Result += "\nstatic struct {\n";
2284 Result += "\tstruct _objc_method_list *next_method;\n";
2285 Result += "\tint method_count;\n";
2286 Result += "\tstruct _objc_method method_list[";
2287 Result += utostr(MethodEnd-MethodBegin);
2288 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002289 Result += prefix;
2290 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2291 Result += "_METHODS_";
2292 Result += ClassName;
2293 Result += " __attribute__ ((section (\"__OBJC, __";
2294 Result += IsInstanceMethod ? "inst" : "cls";
2295 Result += "_meth\")))= ";
2296 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002297
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002298 Result += "\t,{{(SEL)\"";
2299 Result += (*MethodBegin)->getSelector().getName().c_str();
2300 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002301 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002302 Result += "\", \"";
2303 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002304 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002305 Result += MethodInternalNames[*MethodBegin];
2306 Result += "}\n";
2307 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2308 Result += "\t ,{(SEL)\"";
2309 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002310 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002311 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002312 Result += "\", \"";
2313 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002314 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002315 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002316 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002317 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002318 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002319}
2320
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002321/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2322void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002323 int NumProtocols,
2324 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002325 const char *ClassName,
2326 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002327 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002328 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002329 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002330 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002331 // Output struct protocol_methods holder of method selector and type.
2332 if (!objc_protocol_methods &&
2333 (PDecl->getNumInstanceMethods() > 0
2334 || PDecl->getNumClassMethods() > 0)) {
2335 /* struct protocol_methods {
2336 SEL _cmd;
2337 char *method_types;
2338 }
2339 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002340 Result += "\nstruct protocol_methods {\n";
2341 Result += "\tSEL _cmd;\n";
2342 Result += "\tchar *method_types;\n";
2343 Result += "};\n";
2344
2345 /* struct _objc_protocol_method_list {
2346 int protocol_method_count;
2347 struct protocol_methods protocols[];
2348 }
2349 */
2350 Result += "\nstruct _objc_protocol_method_list {\n";
2351 Result += "\tint protocol_method_count;\n";
2352 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002353 objc_protocol_methods = true;
2354 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002355
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002356 int NumMethods = PDecl->getNumInstanceMethods();
2357 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002358 Result += "\nstatic struct _objc_protocol_method_list "
2359 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2360 Result += PDecl->getName();
2361 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2362 "{\n\t" + utostr(NumMethods) + "\n";
2363
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002364 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002365 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002366 E = PDecl->instmeth_end(); I != E; ++I) {
2367 if (I == PDecl->instmeth_begin())
2368 Result += "\t ,{{(SEL)\"";
2369 else
2370 Result += "\t ,{(SEL)\"";
2371 Result += (*I)->getSelector().getName().c_str();
2372 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002373 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002374 Result += "\", \"";
2375 Result += MethodTypeString;
2376 Result += "\"}\n";
2377 }
2378 Result += "\t }\n};\n";
2379 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002380
2381 // Output class methods declared in this protocol.
2382 NumMethods = PDecl->getNumClassMethods();
2383 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002384 Result += "\nstatic struct _objc_protocol_method_list "
2385 "_OBJC_PROTOCOL_CLASS_METHODS_";
2386 Result += PDecl->getName();
2387 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2388 "{\n\t";
2389 Result += utostr(NumMethods);
2390 Result += "\n";
2391
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002392 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002393 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002394 E = PDecl->classmeth_end(); I != E; ++I) {
2395 if (I == PDecl->classmeth_begin())
2396 Result += "\t ,{{(SEL)\"";
2397 else
2398 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002399 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002400 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002401 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002402 Result += "\", \"";
2403 Result += MethodTypeString;
2404 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002405 }
2406 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002407 }
2408 // Output:
2409 /* struct _objc_protocol {
2410 // Objective-C 1.0 extensions
2411 struct _objc_protocol_extension *isa;
2412 char *protocol_name;
2413 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002414 struct _objc_protocol_method_list *instance_methods;
2415 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002416 };
2417 */
2418 static bool objc_protocol = false;
2419 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002420 Result += "\nstruct _objc_protocol {\n";
2421 Result += "\tstruct _objc_protocol_extension *isa;\n";
2422 Result += "\tchar *protocol_name;\n";
2423 Result += "\tstruct _objc_protocol **protocol_list;\n";
2424 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2425 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2426 Result += "};\n";
2427
2428 /* struct _objc_protocol_list {
2429 struct _objc_protocol_list *next;
2430 int protocol_count;
2431 struct _objc_protocol *class_protocols[];
2432 }
2433 */
2434 Result += "\nstruct _objc_protocol_list {\n";
2435 Result += "\tstruct _objc_protocol_list *next;\n";
2436 Result += "\tint protocol_count;\n";
2437 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2438 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002439 objc_protocol = true;
2440 }
2441
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002442 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2443 Result += PDecl->getName();
2444 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2445 "{\n\t0, \"";
2446 Result += PDecl->getName();
2447 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002448 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002449 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2450 Result += PDecl->getName();
2451 Result += ", ";
2452 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002453 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002454 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002455 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002456 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2457 Result += PDecl->getName();
2458 Result += "\n";
2459 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002460 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002461 Result += "0\n";
2462 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002463 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002464 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002465 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2466 Result += prefix;
2467 Result += "_PROTOCOLS_";
2468 Result += ClassName;
2469 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2470 "{\n\t0, ";
2471 Result += utostr(NumProtocols);
2472 Result += "\n";
2473
2474 Result += "\t,{&_OBJC_PROTOCOL_";
2475 Result += Protocols[0]->getName();
2476 Result += " \n";
2477
2478 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002479 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002480 Result += "\t ,&_OBJC_PROTOCOL_";
2481 Result += PDecl->getName();
2482 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002483 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002484 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002485 }
2486}
2487
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002488/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002489/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002490void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002491 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002492 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002493 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002494 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002495 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2496 CDecl = CDecl->getNextClassCategory())
2497 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2498 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002499
Chris Lattnereb44eee2007-12-23 01:40:15 +00002500 std::string FullCategoryName = ClassDecl->getName();
2501 FullCategoryName += '_';
2502 FullCategoryName += IDecl->getName();
2503
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002504 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002506 true, "CATEGORY_", FullCategoryName.c_str(),
2507 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002508
2509 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002510 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002511 false, "CATEGORY_", FullCategoryName.c_str(),
2512 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002513
2514 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002515 // Null CDecl is case of a category implementation with no category interface
2516 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002517 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002518 CDecl->getNumReferencedProtocols(),
2519 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002520 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002521
2522 /* struct _objc_category {
2523 char *category_name;
2524 char *class_name;
2525 struct _objc_method_list *instance_methods;
2526 struct _objc_method_list *class_methods;
2527 struct _objc_protocol_list *protocols;
2528 // Objective-C 1.0 extensions
2529 uint32_t size; // sizeof (struct _objc_category)
2530 struct _objc_property_list *instance_properties; // category's own
2531 // @property decl.
2532 };
2533 */
2534
2535 static bool objc_category = false;
2536 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002537 Result += "\nstruct _objc_category {\n";
2538 Result += "\tchar *category_name;\n";
2539 Result += "\tchar *class_name;\n";
2540 Result += "\tstruct _objc_method_list *instance_methods;\n";
2541 Result += "\tstruct _objc_method_list *class_methods;\n";
2542 Result += "\tstruct _objc_protocol_list *protocols;\n";
2543 Result += "\tunsigned int size;\n";
2544 Result += "\tstruct _objc_property_list *instance_properties;\n";
2545 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002546 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002547 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002548 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2549 Result += FullCategoryName;
2550 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2551 Result += IDecl->getName();
2552 Result += "\"\n\t, \"";
2553 Result += ClassDecl->getName();
2554 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002555
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002556 if (IDecl->getNumInstanceMethods() > 0) {
2557 Result += "\t, (struct _objc_method_list *)"
2558 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2559 Result += FullCategoryName;
2560 Result += "\n";
2561 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002562 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002563 Result += "\t, 0\n";
2564 if (IDecl->getNumClassMethods() > 0) {
2565 Result += "\t, (struct _objc_method_list *)"
2566 "&_OBJC_CATEGORY_CLASS_METHODS_";
2567 Result += FullCategoryName;
2568 Result += "\n";
2569 }
2570 else
2571 Result += "\t, 0\n";
2572
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002573 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002574 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2575 Result += FullCategoryName;
2576 Result += "\n";
2577 }
2578 else
2579 Result += "\t, 0\n";
2580 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002581}
2582
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002583/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2584/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002585void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2586 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002587 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002588 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002589 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002590 if (LangOpts.Microsoft)
2591 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002592 Result += ", ";
2593 Result += ivar->getName();
2594 Result += ")";
2595}
2596
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002597//===----------------------------------------------------------------------===//
2598// Meta Data Emission
2599//===----------------------------------------------------------------------===//
2600
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002601void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002602 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002603 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002604
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002605 // Explictly declared @interface's are already synthesized.
2606 if (CDecl->ImplicitInterfaceDecl()) {
2607 // FIXME: Implementation of a class with no @interface (legacy) doese not
2608 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002609 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002610 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002611
Chris Lattnerbe6df082007-12-12 07:56:42 +00002612 // Build _objc_ivar_list metadata for classes ivars if needed
2613 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2614 ? IDecl->getImplDeclNumIvars()
2615 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002616 if (NumIvars > 0) {
2617 static bool objc_ivar = false;
2618 if (!objc_ivar) {
2619 /* struct _objc_ivar {
2620 char *ivar_name;
2621 char *ivar_type;
2622 int ivar_offset;
2623 };
2624 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002625 Result += "\nstruct _objc_ivar {\n";
2626 Result += "\tchar *ivar_name;\n";
2627 Result += "\tchar *ivar_type;\n";
2628 Result += "\tint ivar_offset;\n";
2629 Result += "};\n";
2630
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002631 objc_ivar = true;
2632 }
2633
Steve Naroff946a6932008-03-11 00:12:29 +00002634 /* struct {
2635 int ivar_count;
2636 struct _objc_ivar ivar_list[nIvars];
2637 };
2638 */
2639 Result += "\nstatic struct {\n";
2640 Result += "\tint ivar_count;\n";
2641 Result += "\tstruct _objc_ivar ivar_list[";
2642 Result += utostr(NumIvars);
2643 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002644 Result += IDecl->getName();
2645 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2646 "{\n\t";
2647 Result += utostr(NumIvars);
2648 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002649
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002650 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002651 if (IDecl->getImplDeclNumIvars() > 0) {
2652 IVI = IDecl->ivar_begin();
2653 IVE = IDecl->ivar_end();
2654 } else {
2655 IVI = CDecl->ivar_begin();
2656 IVE = CDecl->ivar_end();
2657 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002658 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002659 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002660 Result += "\", \"";
2661 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002662 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2663 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002664 Result += StrEncoding;
2665 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002666 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002667 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002668 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002669 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002670 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002671 Result += "\", \"";
2672 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002673 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2674 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002675 Result += StrEncoding;
2676 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002677 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002678 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002679 }
2680
2681 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002682 }
2683
2684 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002685 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002686 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002687
2688 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002689 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002690 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002691
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002692 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002693 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002694 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002695 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002696
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002697
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002698 // Declaration of class/meta-class metadata
2699 /* struct _objc_class {
2700 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002701 const char *super_class_name;
2702 char *name;
2703 long version;
2704 long info;
2705 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002706 struct _objc_ivar_list *ivars;
2707 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002708 struct objc_cache *cache;
2709 struct objc_protocol_list *protocols;
2710 const char *ivar_layout;
2711 struct _objc_class_ext *ext;
2712 };
2713 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002714 static bool objc_class = false;
2715 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002716 Result += "\nstruct _objc_class {\n";
2717 Result += "\tstruct _objc_class *isa;\n";
2718 Result += "\tconst char *super_class_name;\n";
2719 Result += "\tchar *name;\n";
2720 Result += "\tlong version;\n";
2721 Result += "\tlong info;\n";
2722 Result += "\tlong instance_size;\n";
2723 Result += "\tstruct _objc_ivar_list *ivars;\n";
2724 Result += "\tstruct _objc_method_list *methods;\n";
2725 Result += "\tstruct objc_cache *cache;\n";
2726 Result += "\tstruct _objc_protocol_list *protocols;\n";
2727 Result += "\tconst char *ivar_layout;\n";
2728 Result += "\tstruct _objc_class_ext *ext;\n";
2729 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002730 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002731 }
2732
2733 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002734 ObjCInterfaceDecl *RootClass = 0;
2735 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002736 while (SuperClass) {
2737 RootClass = SuperClass;
2738 SuperClass = SuperClass->getSuperClass();
2739 }
2740 SuperClass = CDecl->getSuperClass();
2741
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002742 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2743 Result += CDecl->getName();
2744 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2745 "{\n\t(struct _objc_class *)\"";
2746 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2747 Result += "\"";
2748
2749 if (SuperClass) {
2750 Result += ", \"";
2751 Result += SuperClass->getName();
2752 Result += "\", \"";
2753 Result += CDecl->getName();
2754 Result += "\"";
2755 }
2756 else {
2757 Result += ", 0, \"";
2758 Result += CDecl->getName();
2759 Result += "\"";
2760 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002761 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002762 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002764 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002765 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002766 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002767 Result += "\n";
2768 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002769 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002770 Result += ", 0\n";
2771 if (CDecl->getNumIntfRefProtocols() > 0) {
2772 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2773 Result += CDecl->getName();
2774 Result += ",0,0\n";
2775 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002776 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002777 Result += "\t,0,0,0,0\n";
2778 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002779
2780 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002781 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2782 Result += CDecl->getName();
2783 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2784 "{\n\t&_OBJC_METACLASS_";
2785 Result += CDecl->getName();
2786 if (SuperClass) {
2787 Result += ", \"";
2788 Result += SuperClass->getName();
2789 Result += "\", \"";
2790 Result += CDecl->getName();
2791 Result += "\"";
2792 }
2793 else {
2794 Result += ", 0, \"";
2795 Result += CDecl->getName();
2796 Result += "\"";
2797 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002798 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002799 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002800 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002801 Result += ",0";
2802 else {
2803 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002804 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002805 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002806 if (LangOpts.Microsoft)
2807 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002808 Result += ")";
2809 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002810 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002811 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002812 Result += CDecl->getName();
2813 Result += "\n\t";
2814 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002815 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002816 Result += ",0";
2817 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002818 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002819 Result += CDecl->getName();
2820 Result += ", 0\n\t";
2821 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002822 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002823 Result += ",0,0";
2824 if (CDecl->getNumIntfRefProtocols() > 0) {
2825 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2826 Result += CDecl->getName();
2827 Result += ", 0,0\n";
2828 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002829 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002830 Result += ",0,0,0\n";
2831 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002832}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002833
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002834/// RewriteImplementations - This routine rewrites all method implementations
2835/// and emits meta-data.
2836
2837void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002838 int ClsDefCount = ClassImplementation.size();
2839 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002840
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002841 if (ClsDefCount == 0 && CatDefCount == 0)
2842 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002843 // Rewrite implemented methods
2844 for (int i = 0; i < ClsDefCount; i++)
2845 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002846
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002847 for (int i = 0; i < CatDefCount; i++)
2848 RewriteImplementationDecl(CategoryImplementation[i]);
2849
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002850 // This is needed for use of offsetof
2851 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002852
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002853 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002854 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002855 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002856
2857 // For each implemented category, write out all its meta data.
2858 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002859 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002860
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002861 // Write objc_symtab metadata
2862 /*
2863 struct _objc_symtab
2864 {
2865 long sel_ref_cnt;
2866 SEL *refs;
2867 short cls_def_cnt;
2868 short cat_def_cnt;
2869 void *defs[cls_def_cnt + cat_def_cnt];
2870 };
2871 */
2872
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002873 Result += "\nstruct _objc_symtab {\n";
2874 Result += "\tlong sel_ref_cnt;\n";
2875 Result += "\tSEL *refs;\n";
2876 Result += "\tshort cls_def_cnt;\n";
2877 Result += "\tshort cat_def_cnt;\n";
2878 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2879 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002880
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002881 Result += "static struct _objc_symtab "
2882 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2883 Result += "\t0, 0, " + utostr(ClsDefCount)
2884 + ", " + utostr(CatDefCount) + "\n";
2885 for (int i = 0; i < ClsDefCount; i++) {
2886 Result += "\t,&_OBJC_CLASS_";
2887 Result += ClassImplementation[i]->getName();
2888 Result += "\n";
2889 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002890
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002891 for (int i = 0; i < CatDefCount; i++) {
2892 Result += "\t,&_OBJC_CATEGORY_";
2893 Result += CategoryImplementation[i]->getClassInterface()->getName();
2894 Result += "_";
2895 Result += CategoryImplementation[i]->getName();
2896 Result += "\n";
2897 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002898
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002899 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002900
2901 // Write objc_module metadata
2902
2903 /*
2904 struct _objc_module {
2905 long version;
2906 long size;
2907 const char *name;
2908 struct _objc_symtab *symtab;
2909 }
2910 */
2911
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002912 Result += "\nstruct _objc_module {\n";
2913 Result += "\tlong version;\n";
2914 Result += "\tlong size;\n";
2915 Result += "\tconst char *name;\n";
2916 Result += "\tstruct _objc_symtab *symtab;\n";
2917 Result += "};\n\n";
2918 Result += "static struct _objc_module "
2919 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002920 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2921 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002922 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002923
2924 if (LangOpts.Microsoft) {
2925 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2926 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2927 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2928 Result += "&_OBJC_MODULES;\n";
2929 Result += "#pragma data_seg(pop)\n\n";
2930 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002931}
Chris Lattner311ff022007-10-16 22:36:42 +00002932