blob: 6ad362a2a0b75e06c4ba41eb793d4388b4f6afa0 [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);
Steve Naroff05b8c782008-03-12 00:25:36 +0000657 if (!LangOpts.Microsoft) {
658 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
659 ResultStr += "struct ";
660 }
661 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000662 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000663 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000664 }
665 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000666 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000667
668 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000669 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000670 ResultStr += " _cmd";
671
672 // Method arguments.
673 for (int i = 0; i < OMD->getNumParams(); i++) {
674 ParmVarDecl *PDecl = OMD->getParamDecl(i);
675 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000676 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000677 ResultStr += "id";
678 else
679 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000680 ResultStr += " ";
681 ResultStr += PDecl->getName();
682 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000683 if (OMD->isVariadic())
684 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000685 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000686
687}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000688void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000689 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
690 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000691
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000692 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000693 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000694 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000695 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000696
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000697 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000698 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
699 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000700 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000701 ObjCMethodDecl *OMD = *I;
702 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000703 SourceLocation LocStart = OMD->getLocStart();
704 SourceLocation LocEnd = OMD->getBody()->getLocStart();
705
706 const char *startBuf = SM->getCharacterData(LocStart);
707 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000708 ReplaceText(LocStart, endBuf-startBuf,
709 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000710 }
711
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000712 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000713 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
714 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000715 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 ObjCMethodDecl *OMD = *I;
717 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000718 SourceLocation LocStart = OMD->getLocStart();
719 SourceLocation LocEnd = OMD->getBody()->getLocStart();
720
721 const char *startBuf = SM->getCharacterData(LocStart);
722 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000723 ReplaceText(LocStart, endBuf-startBuf,
724 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000725 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000726 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000727 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000728 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000729 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000730}
731
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000733 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000735 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000736 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000737 ResultStr += ClassDecl->getName();
738 ResultStr += "\n";
739 ResultStr += "#define _REWRITER_typedef_";
740 ResultStr += ClassDecl->getName();
741 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000742 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000743 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000744 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000745 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000747 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000748 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000749
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000750 RewriteProperties(ClassDecl->getNumPropertyDecl(),
751 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000752 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000753 E = ClassDecl->instmeth_end(); I != E; ++I)
754 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000755 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000756 E = ClassDecl->classmeth_end(); I != E; ++I)
757 RewriteMethodDeclaration(*I);
758
Steve Naroff2feac5e2007-10-30 03:43:13 +0000759 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000760 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000761}
762
Steve Naroff05b8c782008-03-12 00:25:36 +0000763/// FIXME: Investigate the following comment...
764/// This code is not right. It seems unnecessary. It breaks use of
765/// ivar reference used as 'receiver' of an expression; as in:
766/// [newInv->_container addObject:0];
Steve Naroff7e3411b2007-11-15 02:58:25 +0000767Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000768 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000769 if (CurMethodDecl) {
770 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
771 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
772 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
773 std::string RecName = intT->getDecl()->getIdentifier()->getName();
774 RecName += "_IMPL";
775 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
776 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(), II, 0);
777 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
778 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
779 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
780 // Don't forget the parens to enforce the proper binding.
781 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
782 if (IV->isFreeIvar()) {
783 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
784 ReplaceStmt(IV, ME);
785 delete IV;
786 return ME;
787 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000788 ReplaceStmt(IV->getBase(), PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +0000789 delete IV->getBase();
790 return PE;
791 }
792 }
793 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000794 }
Steve Naroff05b8c782008-03-12 00:25:36 +0000795 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
796 IV->getLocation(), D->getType());
797 ReplaceStmt(IV, Replacement);
798 delete IV;
799 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000800}
801
Chris Lattnerf04da132007-10-24 17:06:59 +0000802//===----------------------------------------------------------------------===//
803// Function Body / Expression rewriting
804//===----------------------------------------------------------------------===//
805
Steve Narofff3473a72007-11-09 15:20:18 +0000806Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000807 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
808 isa<DoStmt>(S) || isa<ForStmt>(S))
809 Stmts.push_back(S);
810 else if (isa<ObjCForCollectionStmt>(S)) {
811 Stmts.push_back(S);
812 ObjCBcLabelNo.push_back(++BcLabelCount);
813 }
814
Chris Lattner338d1e22008-01-31 05:10:40 +0000815 SourceLocation OrigStmtEnd = S->getLocEnd();
816
817 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000818 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
819 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000820 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000821 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000822 if (newStmt)
823 *CI = newStmt;
824 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000825
826 // Handle specific things.
827 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
828 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000829
830 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
831 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000832
833 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
834 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000835
Steve Naroffbeaf2992007-11-03 11:27:19 +0000836 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
837 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000838
Steve Naroff934f2762007-10-24 22:48:43 +0000839 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
840 // Before we rewrite it, put the original message expression in a comment.
841 SourceLocation startLoc = MessExpr->getLocStart();
842 SourceLocation endLoc = MessExpr->getLocEnd();
843
844 const char *startBuf = SM->getCharacterData(startLoc);
845 const char *endBuf = SM->getCharacterData(endLoc);
846
847 std::string messString;
848 messString += "// ";
849 messString.append(startBuf, endBuf-startBuf+1);
850 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000851
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000852 // FIXME: Missing definition of
853 // InsertText(clang::SourceLocation, char const*, unsigned int).
854 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000855 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000856 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000857 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000858 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000859
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000860 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
861 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000862
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000863 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
864 return RewriteObjCSynchronizedStmt(StmtTry);
865
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000866 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
867 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000868
869 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
870 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000871
872 if (ObjCForCollectionStmt *StmtForCollection =
873 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000874 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000875 if (BreakStmt *StmtBreakStmt =
876 dyn_cast<BreakStmt>(S))
877 return RewriteBreakStmt(StmtBreakStmt);
878 if (ContinueStmt *StmtContinueStmt =
879 dyn_cast<ContinueStmt>(S))
880 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000881
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000882 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
883 isa<DoStmt>(S) || isa<ForStmt>(S)) {
884 assert(!Stmts.empty() && "Statement stack is empty");
885 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
886 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
887 && "Statement stack mismatch");
888 Stmts.pop_back();
889 }
Steve Naroff874e2322007-11-15 10:28:18 +0000890#if 0
891 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
892 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
893 // Get the new text.
894 std::ostringstream Buf;
895 Replacement->printPretty(Buf);
896 const std::string &Str = Buf.str();
897
898 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000899 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000900 delete S;
901 return Replacement;
902 }
903#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000904 // Return this stmt unmodified.
905 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000906}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000907
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000908/// SynthCountByEnumWithState - To print:
909/// ((unsigned int (*)
910/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
911/// (void *)objc_msgSend)((id)l_collection,
912/// sel_registerName(
913/// "countByEnumeratingWithState:objects:count:"),
914/// &enumState,
915/// (id *)items, (unsigned int)16)
916///
917void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
918 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
919 "id *, unsigned int))(void *)objc_msgSend)";
920 buf += "\n\t\t";
921 buf += "((id)l_collection,\n\t\t";
922 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
923 buf += "\n\t\t";
924 buf += "&enumState, "
925 "(id *)items, (unsigned int)16)";
926}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000927
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000928/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
929/// statement to exit to its outer synthesized loop.
930///
931Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
932 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
933 return S;
934 // replace break with goto __break_label
935 std::string buf;
936
937 SourceLocation startLoc = S->getLocStart();
938 buf = "goto __break_label_";
939 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000940 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000941
942 return 0;
943}
944
945/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
946/// statement to continue with its inner synthesized loop.
947///
948Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
949 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
950 return S;
951 // replace continue with goto __continue_label
952 std::string buf;
953
954 SourceLocation startLoc = S->getLocStart();
955 buf = "goto __continue_label_";
956 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000957 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000958
959 return 0;
960}
961
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000962/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000963/// It rewrites:
964/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000965
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000966/// Into:
967/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000968/// type elem;
969/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000970/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000971/// id l_collection = (id)collection;
972/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
973/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000974/// if (limit) {
975/// unsigned long startMutations = *enumState.mutationsPtr;
976/// do {
977/// unsigned long counter = 0;
978/// do {
979/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000980/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000981/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000982/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000983/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000984/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000985/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
986/// objects:items count:16]);
987/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000988/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000989/// }
990/// else
991/// elem = nil;
992/// }
993///
Chris Lattner338d1e22008-01-31 05:10:40 +0000994Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
995 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000996 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
997 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
998 "ObjCForCollectionStmt Statement stack mismatch");
999 assert(!ObjCBcLabelNo.empty() &&
1000 "ObjCForCollectionStmt - Label No stack empty");
1001
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001002 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001003 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001004 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001005 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001006 std::string buf;
1007 buf = "\n{\n\t";
1008 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1009 // type elem;
1010 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001011 elementTypeAsString = ElementType.getAsString();
1012 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001013 buf += " ";
1014 elementName = DS->getDecl()->getName();
1015 buf += elementName;
1016 buf += ";\n\t";
1017 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001018 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001019 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001020 elementTypeAsString = DR->getDecl()->getType().getAsString();
1021 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001022 else
1023 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1024
1025 // struct __objcFastEnumerationState enumState = { 0 };
1026 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1027 // id items[16];
1028 buf += "id items[16];\n\t";
1029 // id l_collection = (id)
1030 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001031 // Find start location of 'collection' the hard way!
1032 const char *startCollectionBuf = startBuf;
1033 startCollectionBuf += 3; // skip 'for'
1034 startCollectionBuf = strchr(startCollectionBuf, '(');
1035 startCollectionBuf++; // skip '('
1036 // find 'in' and skip it.
1037 while (*startCollectionBuf != ' ' ||
1038 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1039 (*(startCollectionBuf+3) != ' ' &&
1040 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1041 startCollectionBuf++;
1042 startCollectionBuf += 3;
1043
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001044 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001045 ReplaceText(startLoc, startCollectionBuf - startBuf,
1046 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001047 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001048 SourceLocation rightParenLoc = S->getRParenLoc();
1049 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1050 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001051 buf = ";\n\t";
1052
1053 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1054 // objects:items count:16];
1055 // which is synthesized into:
1056 // unsigned int limit =
1057 // ((unsigned int (*)
1058 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1059 // (void *)objc_msgSend)((id)l_collection,
1060 // sel_registerName(
1061 // "countByEnumeratingWithState:objects:count:"),
1062 // (struct __objcFastEnumerationState *)&state,
1063 // (id *)items, (unsigned int)16);
1064 buf += "unsigned long limit =\n\t\t";
1065 SynthCountByEnumWithState(buf);
1066 buf += ";\n\t";
1067 /// if (limit) {
1068 /// unsigned long startMutations = *enumState.mutationsPtr;
1069 /// do {
1070 /// unsigned long counter = 0;
1071 /// do {
1072 /// if (startMutations != *enumState.mutationsPtr)
1073 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001074 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001075 buf += "if (limit) {\n\t";
1076 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1077 buf += "do {\n\t\t";
1078 buf += "unsigned long counter = 0;\n\t\t";
1079 buf += "do {\n\t\t\t";
1080 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1081 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1082 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001083 buf += " = (";
1084 buf += elementTypeAsString;
1085 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001086 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001087 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001088
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001089 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001090 /// } while (counter < limit);
1091 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1092 /// objects:items count:16]);
1093 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001094 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001095 /// }
1096 /// else
1097 /// elem = nil;
1098 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001099 ///
1100 buf = ";\n\t";
1101 buf += "__continue_label_";
1102 buf += utostr(ObjCBcLabelNo.back());
1103 buf += ": ;";
1104 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001105 buf += "} while (counter < limit);\n\t";
1106 buf += "} while (limit = ";
1107 SynthCountByEnumWithState(buf);
1108 buf += ");\n\t";
1109 buf += elementName;
1110 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001111 buf += "__break_label_";
1112 buf += utostr(ObjCBcLabelNo.back());
1113 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001114 buf += "}\n\t";
1115 buf += "else\n\t\t";
1116 buf += elementName;
1117 buf += " = nil;\n";
1118 buf += "}\n";
1119 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001120 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001121 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001122 Stmts.pop_back();
1123 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001124 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001125}
1126
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001127/// RewriteObjCSynchronizedStmt -
1128/// This routine rewrites @synchronized(expr) stmt;
1129/// into:
1130/// objc_sync_enter(expr);
1131/// @try stmt @finally { objc_sync_exit(expr); }
1132///
1133Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1134 // Get the start location and compute the semi location.
1135 SourceLocation startLoc = S->getLocStart();
1136 const char *startBuf = SM->getCharacterData(startLoc);
1137
1138 assert((*startBuf == '@') && "bogus @synchronized location");
1139
1140 std::string buf;
1141 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001142 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001143 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1144 const char *endBuf = SM->getCharacterData(endLoc);
1145 endBuf++;
1146 const char *rparenBuf = strchr(endBuf, ')');
1147 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1148 buf = ");\n";
1149 // declare a new scope with two variables, _stack and _rethrow.
1150 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1151 buf += "int buf[18/*32-bit i386*/];\n";
1152 buf += "char *pointers[4];} _stack;\n";
1153 buf += "id volatile _rethrow = 0;\n";
1154 buf += "objc_exception_try_enter(&_stack);\n";
1155 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001156 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001157 startLoc = S->getSynchBody()->getLocEnd();
1158 startBuf = SM->getCharacterData(startLoc);
1159
1160 assert((*startBuf == '}') && "bogus @try block");
1161 SourceLocation lastCurlyLoc = startLoc;
1162 buf = "}\nelse {\n";
1163 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1164 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1165 // FIXME: This must be objc_sync_exit(syncExpr);
1166 buf += " objc_sync_exit();\n";
1167 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1168 buf += "}\n";
1169 buf += "}";
1170
Chris Lattneraadaf782008-01-31 19:51:04 +00001171 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001172 return 0;
1173}
1174
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001175Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001176 // Get the start location and compute the semi location.
1177 SourceLocation startLoc = S->getLocStart();
1178 const char *startBuf = SM->getCharacterData(startLoc);
1179
1180 assert((*startBuf == '@') && "bogus @try location");
1181
1182 std::string buf;
1183 // declare a new scope with two variables, _stack and _rethrow.
1184 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1185 buf += "int buf[18/*32-bit i386*/];\n";
1186 buf += "char *pointers[4];} _stack;\n";
1187 buf += "id volatile _rethrow = 0;\n";
1188 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001189 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001190
Chris Lattneraadaf782008-01-31 19:51:04 +00001191 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001192
1193 startLoc = S->getTryBody()->getLocEnd();
1194 startBuf = SM->getCharacterData(startLoc);
1195
1196 assert((*startBuf == '}') && "bogus @try block");
1197
1198 SourceLocation lastCurlyLoc = startLoc;
1199
1200 startLoc = startLoc.getFileLocWithOffset(1);
1201 buf = " /* @catch begin */ else {\n";
1202 buf += " id _caught = objc_exception_extract(&_stack);\n";
1203 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001204 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001205 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1206 buf += " else { /* @catch continue */";
1207
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001208 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001209
1210 bool sawIdTypedCatch = false;
1211 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001212 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001213 while (catchList) {
1214 Stmt *catchStmt = catchList->getCatchParamStmt();
1215
1216 if (catchList == S->getCatchStmts())
1217 buf = "if ("; // we are generating code for the first catch clause
1218 else
1219 buf = "else if (";
1220 startLoc = catchList->getLocStart();
1221 startBuf = SM->getCharacterData(startLoc);
1222
1223 assert((*startBuf == '@') && "bogus @catch location");
1224
1225 const char *lParenLoc = strchr(startBuf, '(');
1226
Steve Naroffbe4b3332008-02-01 22:08:12 +00001227 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001228 // Now rewrite the body...
1229 lastCatchBody = catchList->getCatchBody();
1230 SourceLocation rParenLoc = catchList->getRParenLoc();
1231 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1232 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1233 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1234 assert((*rParenBuf == ')') && "bogus @catch paren location");
1235 assert((*bodyBuf == '{') && "bogus @catch body location");
1236
1237 buf += "1) { id _tmp = _caught;";
1238 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1239 buf.c_str(), buf.size());
1240 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001241 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001242 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001243 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001244 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001245 sawIdTypedCatch = true;
1246 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001247 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001248
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001249 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001250 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001251 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001252 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001253 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001254 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001255 }
1256 }
1257 // Now rewrite the body...
1258 lastCatchBody = catchList->getCatchBody();
1259 SourceLocation rParenLoc = catchList->getRParenLoc();
1260 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1261 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1262 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1263 assert((*rParenBuf == ')') && "bogus @catch paren location");
1264 assert((*bodyBuf == '{') && "bogus @catch body location");
1265
1266 buf = " = _caught;";
1267 // Here we replace ") {" with "= _caught;" (which initializes and
1268 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001269 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001270 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001271 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001272 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001273 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001274 catchList = catchList->getNextCatchStmt();
1275 }
1276 // Complete the catch list...
1277 if (lastCatchBody) {
1278 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1279 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1280 assert((*bodyBuf == '}') && "bogus @catch body location");
1281 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1282 buf = " } } /* @catch end */\n";
1283
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001284 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001285
1286 // Set lastCurlyLoc
1287 lastCurlyLoc = lastCatchBody->getLocEnd();
1288 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001289 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001290 startLoc = finalStmt->getLocStart();
1291 startBuf = SM->getCharacterData(startLoc);
1292 assert((*startBuf == '@') && "bogus @finally start");
1293
1294 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001295 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001296
1297 Stmt *body = finalStmt->getFinallyBody();
1298 SourceLocation startLoc = body->getLocStart();
1299 SourceLocation endLoc = body->getLocEnd();
1300 const char *startBuf = SM->getCharacterData(startLoc);
1301 const char *endBuf = SM->getCharacterData(endLoc);
1302 assert((*startBuf == '{') && "bogus @finally body location");
1303 assert((*endBuf == '}') && "bogus @finally body location");
1304
1305 startLoc = startLoc.getFileLocWithOffset(1);
1306 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001307 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001308 endLoc = endLoc.getFileLocWithOffset(-1);
1309 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001310 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001311
1312 // Set lastCurlyLoc
1313 lastCurlyLoc = body->getLocEnd();
1314 }
1315 // Now emit the final closing curly brace...
1316 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1317 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001318 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001319 return 0;
1320}
1321
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001322Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001323 return 0;
1324}
1325
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001326Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001327 return 0;
1328}
1329
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001330// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001331// the throw expression is typically a message expression that's already
1332// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001333Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001334 // Get the start location and compute the semi location.
1335 SourceLocation startLoc = S->getLocStart();
1336 const char *startBuf = SM->getCharacterData(startLoc);
1337
1338 assert((*startBuf == '@') && "bogus @throw location");
1339
1340 std::string buf;
1341 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001342 if (S->getThrowExpr())
1343 buf = "objc_exception_throw(";
1344 else // add an implicit argument
1345 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001346 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001347 const char *semiBuf = strchr(startBuf, ';');
1348 assert((*semiBuf == ';') && "@throw: can't find ';'");
1349 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1350 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001351 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001352 return 0;
1353}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001354
Chris Lattnere64b7772007-10-24 16:57:36 +00001355Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001356 // Create a new string expression.
1357 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001358 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001359 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1360 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001361 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1362 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001363 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001364 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001365
Chris Lattner07506182007-11-30 22:53:43 +00001366 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001367 delete Exp;
1368 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001369}
1370
Steve Naroffb42f8412007-11-05 14:50:49 +00001371Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1372 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1373 // Create a call to sel_registerName("selName").
1374 llvm::SmallVector<Expr*, 8> SelExprs;
1375 QualType argType = Context->getPointerType(Context->CharTy);
1376 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1377 Exp->getSelector().getName().size(),
1378 false, argType, SourceLocation(),
1379 SourceLocation()));
1380 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1381 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001382 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001383 delete Exp;
1384 return SelExp;
1385}
1386
Steve Naroff934f2762007-10-24 22:48:43 +00001387CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1388 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001389 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001390 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001391
1392 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001393 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001394
1395 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001396 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001397 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1398
1399 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001400
Steve Naroff934f2762007-10-24 22:48:43 +00001401 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1402}
1403
Steve Naroffd5255f52007-11-01 13:24:47 +00001404static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1405 const char *&startRef, const char *&endRef) {
1406 while (startBuf < endBuf) {
1407 if (*startBuf == '<')
1408 startRef = startBuf; // mark the start.
1409 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001410 if (startRef && *startRef == '<') {
1411 endRef = startBuf; // mark the end.
1412 return true;
1413 }
1414 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001415 }
1416 startBuf++;
1417 }
1418 return false;
1419}
1420
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001421static void scanToNextArgument(const char *&argRef) {
1422 int angle = 0;
1423 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1424 if (*argRef == '<')
1425 angle++;
1426 else if (*argRef == '>')
1427 angle--;
1428 argRef++;
1429 }
1430 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1431}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001432
Steve Naroffd5255f52007-11-01 13:24:47 +00001433bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001434
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001435 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001436 return true;
1437
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001438 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001439 return true;
1440
Steve Naroffd5255f52007-11-01 13:24:47 +00001441 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001442 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001443 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001444 return true; // we have "Class <Protocol> *".
1445 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001446 return false;
1447}
1448
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001449void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001450 SourceLocation Loc;
1451 QualType Type;
1452 const FunctionTypeProto *proto = 0;
1453 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1454 Loc = VD->getLocation();
1455 Type = VD->getType();
1456 }
1457 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1458 Loc = FD->getLocation();
1459 // Check for ObjC 'id' and class types that have been adorned with protocol
1460 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1461 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1462 assert(funcType && "missing function type");
1463 proto = dyn_cast<FunctionTypeProto>(funcType);
1464 if (!proto)
1465 return;
1466 Type = proto->getResultType();
1467 }
1468 else
1469 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001470
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001471 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001472 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001473
1474 const char *endBuf = SM->getCharacterData(Loc);
1475 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001476 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001477 startBuf--; // scan backward (from the decl location) for return type.
1478 const char *startRef = 0, *endRef = 0;
1479 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1480 // Get the locations of the startRef, endRef.
1481 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1482 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1483 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001484 InsertText(LessLoc, "/*", 2);
1485 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001486 }
1487 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001488 if (!proto)
1489 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001490 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001491 const char *startBuf = SM->getCharacterData(Loc);
1492 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001493 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1494 if (needToScanForQualifiers(proto->getArgType(i))) {
1495 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001496
Steve Naroffd5255f52007-11-01 13:24:47 +00001497 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001498 // scan forward (from the decl location) for argument types.
1499 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001500 const char *startRef = 0, *endRef = 0;
1501 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1502 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001503 SourceLocation LessLoc =
1504 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1505 SourceLocation GreaterLoc =
1506 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001507 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001508 InsertText(LessLoc, "/*", 2);
1509 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001510 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001511 startBuf = ++endBuf;
1512 }
1513 else {
1514 while (*startBuf != ')' && *startBuf != ',')
1515 startBuf++; // scan forward (from the decl location) for argument types.
1516 startBuf++;
1517 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001518 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001519}
1520
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001521// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1522void RewriteTest::SynthSelGetUidFunctionDecl() {
1523 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1524 llvm::SmallVector<QualType, 16> ArgTys;
1525 ArgTys.push_back(Context->getPointerType(
1526 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001527 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001528 &ArgTys[0], ArgTys.size(),
1529 false /*isVariadic*/);
1530 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1531 SelGetUidIdent, getFuncType,
1532 FunctionDecl::Extern, false, 0);
1533}
1534
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001535// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1536void RewriteTest::SynthGetProtocolFunctionDecl() {
1537 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1538 llvm::SmallVector<QualType, 16> ArgTys;
1539 ArgTys.push_back(Context->getPointerType(
1540 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001541 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001542 &ArgTys[0], ArgTys.size(),
1543 false /*isVariadic*/);
1544 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1545 SelGetProtoIdent, getFuncType,
1546 FunctionDecl::Extern, false, 0);
1547}
1548
Steve Naroff09b266e2007-10-30 23:14:51 +00001549void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1550 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001551 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001552 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001553 return;
1554 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001555 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001556}
1557
Steve Naroffc0a123c2008-03-11 17:37:02 +00001558// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1559void RewriteTest::SynthSuperContructorFunctionDecl() {
1560 if (SuperContructorFunctionDecl)
1561 return;
1562 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1563 llvm::SmallVector<QualType, 16> ArgTys;
1564 QualType argT = Context->getObjCIdType();
1565 assert(!argT.isNull() && "Can't find 'id' type");
1566 ArgTys.push_back(argT);
1567 ArgTys.push_back(argT);
1568 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1569 &ArgTys[0], ArgTys.size(),
1570 false);
1571 SuperContructorFunctionDecl = new FunctionDecl(SourceLocation(),
1572 msgSendIdent, msgSendType,
1573 FunctionDecl::Extern, false, 0);
1574}
1575
Steve Naroff09b266e2007-10-30 23:14:51 +00001576// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1577void RewriteTest::SynthMsgSendFunctionDecl() {
1578 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1579 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001580 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001581 assert(!argT.isNull() && "Can't find 'id' type");
1582 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001583 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001584 assert(!argT.isNull() && "Can't find 'SEL' type");
1585 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001586 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001587 &ArgTys[0], ArgTys.size(),
1588 true /*isVariadic*/);
1589 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1590 msgSendIdent, msgSendType,
1591 FunctionDecl::Extern, false, 0);
1592}
1593
Steve Naroff874e2322007-11-15 10:28:18 +00001594// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1595void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1596 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1597 llvm::SmallVector<QualType, 16> ArgTys;
1598 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1599 &Context->Idents.get("objc_super"), 0);
1600 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1601 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1602 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001603 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001604 assert(!argT.isNull() && "Can't find 'SEL' type");
1605 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001606 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001607 &ArgTys[0], ArgTys.size(),
1608 true /*isVariadic*/);
1609 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1610 msgSendIdent, msgSendType,
1611 FunctionDecl::Extern, false, 0);
1612}
1613
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001614// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1615void RewriteTest::SynthMsgSendStretFunctionDecl() {
1616 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1617 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001618 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001619 assert(!argT.isNull() && "Can't find 'id' type");
1620 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001621 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001622 assert(!argT.isNull() && "Can't find 'SEL' type");
1623 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001624 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001625 &ArgTys[0], ArgTys.size(),
1626 true /*isVariadic*/);
1627 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1628 msgSendIdent, msgSendType,
1629 FunctionDecl::Extern, false, 0);
1630}
1631
1632// SynthMsgSendSuperStretFunctionDecl -
1633// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1634void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1635 IdentifierInfo *msgSendIdent =
1636 &Context->Idents.get("objc_msgSendSuper_stret");
1637 llvm::SmallVector<QualType, 16> ArgTys;
1638 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1639 &Context->Idents.get("objc_super"), 0);
1640 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1641 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1642 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001643 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001644 assert(!argT.isNull() && "Can't find 'SEL' type");
1645 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001646 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001647 &ArgTys[0], ArgTys.size(),
1648 true /*isVariadic*/);
1649 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1650 msgSendIdent, msgSendType,
1651 FunctionDecl::Extern, false, 0);
1652}
1653
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001654// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1655void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1656 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1657 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001658 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001659 assert(!argT.isNull() && "Can't find 'id' type");
1660 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001661 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001662 assert(!argT.isNull() && "Can't find 'SEL' type");
1663 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001664 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001665 &ArgTys[0], ArgTys.size(),
1666 true /*isVariadic*/);
1667 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1668 msgSendIdent, msgSendType,
1669 FunctionDecl::Extern, false, 0);
1670}
1671
Steve Naroff09b266e2007-10-30 23:14:51 +00001672// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1673void RewriteTest::SynthGetClassFunctionDecl() {
1674 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1675 llvm::SmallVector<QualType, 16> ArgTys;
1676 ArgTys.push_back(Context->getPointerType(
1677 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001678 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001679 &ArgTys[0], ArgTys.size(),
1680 false /*isVariadic*/);
1681 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1682 getClassIdent, getClassType,
1683 FunctionDecl::Extern, false, 0);
1684}
1685
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001686// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1687void RewriteTest::SynthGetMetaClassFunctionDecl() {
1688 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1689 llvm::SmallVector<QualType, 16> ArgTys;
1690 ArgTys.push_back(Context->getPointerType(
1691 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001692 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001693 &ArgTys[0], ArgTys.size(),
1694 false /*isVariadic*/);
1695 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1696 getClassIdent, getClassType,
1697 FunctionDecl::Extern, false, 0);
1698}
1699
Steve Naroff96984642007-11-08 14:30:50 +00001700// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1701void RewriteTest::SynthCFStringFunctionDecl() {
1702 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1703 llvm::SmallVector<QualType, 16> ArgTys;
1704 ArgTys.push_back(Context->getPointerType(
1705 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001706 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001707 &ArgTys[0], ArgTys.size(),
1708 false /*isVariadic*/);
1709 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1710 getClassIdent, getClassType,
1711 FunctionDecl::Extern, false, 0);
1712}
1713
Steve Naroffbeaf2992007-11-03 11:27:19 +00001714Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001715#if 1
1716 // This rewrite is specific to GCC, which has builtin support for CFString.
1717 if (!CFStringFunctionDecl)
1718 SynthCFStringFunctionDecl();
1719 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1720 llvm::SmallVector<Expr*, 8> StrExpr;
1721 StrExpr.push_back(Exp->getString());
1722 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1723 &StrExpr[0], StrExpr.size());
1724 // cast to NSConstantString *
1725 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001726 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001727 delete Exp;
1728 return cast;
1729#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001730 assert(ConstantStringClassReference && "Can't find constant string reference");
1731 llvm::SmallVector<Expr*, 4> InitExprs;
1732
1733 // Synthesize "(Class)&_NSConstantStringClassReference"
1734 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1735 ConstantStringClassReference->getType(),
1736 SourceLocation());
1737 QualType expType = Context->getPointerType(ClsRef->getType());
1738 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1739 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001740 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001741 SourceLocation());
1742 InitExprs.push_back(cast); // set the 'isa'.
1743 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1744 unsigned IntSize = static_cast<unsigned>(
1745 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1746 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1747 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1748 Exp->getLocStart());
1749 InitExprs.push_back(len); // set "int numBytes".
1750
1751 // struct NSConstantString
1752 QualType CFConstantStrType = Context->getCFConstantStringType();
1753 // (struct NSConstantString) { <exprs from above> }
1754 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1755 &InitExprs[0], InitExprs.size(),
1756 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001757 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001758 // struct NSConstantString *
1759 expType = Context->getPointerType(StrRep->getType());
1760 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1761 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001762 // cast to NSConstantString *
1763 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001764 ReplaceStmt(Exp, cast);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001765 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001766 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001767#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001768}
1769
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001770ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001771 // check if we are sending a message to 'super'
1772 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001773 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1774 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1775 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1776 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001777 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001778 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001779 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001780 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001781 if (ObjCInterfaceType *IT =
1782 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001783 if (IT->getDecl() ==
1784 CurMethodDecl->getClassInterface()->getSuperClass())
1785 return IT->getDecl();
1786 }
1787 }
1788 }
1789 }
1790 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001791 }
Steve Naroff874e2322007-11-15 10:28:18 +00001792 }
1793 return 0;
1794}
1795
1796// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1797QualType RewriteTest::getSuperStructType() {
1798 if (!SuperStructDecl) {
1799 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1800 &Context->Idents.get("objc_super"), 0);
1801 QualType FieldTypes[2];
1802
1803 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001804 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001805 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001806 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001807 // Create fields
1808 FieldDecl *FieldDecls[2];
1809
1810 for (unsigned i = 0; i < 2; ++i)
1811 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1812
1813 SuperStructDecl->defineBody(FieldDecls, 4);
1814 }
1815 return Context->getTagDeclType(SuperStructDecl);
1816}
1817
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001818Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001819 if (!SelGetUidFunctionDecl)
1820 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001821 if (!MsgSendFunctionDecl)
1822 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001823 if (!MsgSendSuperFunctionDecl)
1824 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001825 if (!MsgSendStretFunctionDecl)
1826 SynthMsgSendStretFunctionDecl();
1827 if (!MsgSendSuperStretFunctionDecl)
1828 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001829 if (!MsgSendFpretFunctionDecl)
1830 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001831 if (!GetClassFunctionDecl)
1832 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001833 if (!GetMetaClassFunctionDecl)
1834 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001835
Steve Naroff874e2322007-11-15 10:28:18 +00001836 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001837 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1838 // May need to use objc_msgSend_stret() as well.
1839 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001840 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001841 QualType resultType = mDecl->getResultType();
1842 if (resultType.getCanonicalType()->isStructureType()
1843 || resultType.getCanonicalType()->isUnionType())
1844 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001845 else if (resultType.getCanonicalType()->isRealFloatingType())
1846 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001847 }
Steve Naroff874e2322007-11-15 10:28:18 +00001848
Steve Naroff934f2762007-10-24 22:48:43 +00001849 // Synthesize a call to objc_msgSend().
1850 llvm::SmallVector<Expr*, 8> MsgExprs;
1851 IdentifierInfo *clsName = Exp->getClassName();
1852
1853 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1854 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001855 if (!strcmp(clsName->getName(), "super")) {
1856 MsgSendFlavor = MsgSendSuperFunctionDecl;
1857 if (MsgSendStretFlavor)
1858 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1859 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1860
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001861 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001862 CurMethodDecl->getClassInterface()->getSuperClass();
1863
1864 llvm::SmallVector<Expr*, 4> InitExprs;
1865
1866 // set the receiver to self, the first argument to all methods.
1867 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001868 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001869 SourceLocation()));
1870 llvm::SmallVector<Expr*, 8> ClsExprs;
1871 QualType argType = Context->getPointerType(Context->CharTy);
1872 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1873 SuperDecl->getIdentifier()->getLength(),
1874 false, argType, SourceLocation(),
1875 SourceLocation()));
1876 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1877 &ClsExprs[0],
1878 ClsExprs.size());
1879 // To turn off a warning, type-cast to 'id'
1880 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001881 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001882 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1883 // struct objc_super
1884 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001885 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001886
Steve Naroff23f41272008-03-11 18:14:26 +00001887 if (LangOpts.Microsoft) {
1888 SynthSuperContructorFunctionDecl();
1889 // Simulate a contructor call...
1890 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1891 superType, SourceLocation());
1892 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1893 superType, SourceLocation());
1894 } else {
1895 // (struct objc_super) { <exprs from above> }
1896 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1897 &InitExprs[0], InitExprs.size(),
1898 SourceLocation());
1899 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1900 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001901 // struct objc_super *
1902 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1903 Context->getPointerType(SuperRep->getType()),
1904 SourceLocation());
1905 MsgExprs.push_back(Unop);
1906 } else {
1907 llvm::SmallVector<Expr*, 8> ClsExprs;
1908 QualType argType = Context->getPointerType(Context->CharTy);
1909 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1910 clsName->getLength(),
1911 false, argType, SourceLocation(),
1912 SourceLocation()));
1913 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1914 &ClsExprs[0],
1915 ClsExprs.size());
1916 MsgExprs.push_back(Cls);
1917 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001918 } else { // instance message.
1919 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001920
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001921 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001922 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001923 if (MsgSendStretFlavor)
1924 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001925 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1926
1927 llvm::SmallVector<Expr*, 4> InitExprs;
1928
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001929 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001930 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001931 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001932
1933 llvm::SmallVector<Expr*, 8> ClsExprs;
1934 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001935 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1936 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001937 false, argType, SourceLocation(),
1938 SourceLocation()));
1939 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001940 &ClsExprs[0],
1941 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001942 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001943 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001944 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001945 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001946 // struct objc_super
1947 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00001948 Expr *SuperRep;
1949
1950 if (LangOpts.Microsoft) {
1951 SynthSuperContructorFunctionDecl();
1952 // Simulate a contructor call...
1953 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1954 superType, SourceLocation());
1955 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1956 superType, SourceLocation());
1957 } else {
1958 // (struct objc_super) { <exprs from above> }
1959 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1960 &InitExprs[0], InitExprs.size(),
1961 SourceLocation());
1962 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1963 }
Steve Naroff874e2322007-11-15 10:28:18 +00001964 // struct objc_super *
1965 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1966 Context->getPointerType(SuperRep->getType()),
1967 SourceLocation());
1968 MsgExprs.push_back(Unop);
1969 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001970 // Remove all type-casts because it may contain objc-style types; e.g.
1971 // Foo<Proto> *.
1972 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1973 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001974 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001975 MsgExprs.push_back(recExpr);
1976 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001977 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001978 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001979 llvm::SmallVector<Expr*, 8> SelExprs;
1980 QualType argType = Context->getPointerType(Context->CharTy);
1981 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1982 Exp->getSelector().getName().size(),
1983 false, argType, SourceLocation(),
1984 SourceLocation()));
1985 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1986 &SelExprs[0], SelExprs.size());
1987 MsgExprs.push_back(SelExp);
1988
1989 // Now push any user supplied arguments.
1990 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001991 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001992 // Make all implicit casts explicit...ICE comes in handy:-)
1993 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1994 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001995 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1996 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001997 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001998 }
1999 // Make id<P...> cast into an 'id' cast.
2000 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002001 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002002 while ((CE = dyn_cast<CastExpr>(userExpr)))
2003 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002004 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002005 userExpr, SourceLocation());
2006 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002007 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002008 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002009 // We've transferred the ownership to MsgExprs. Null out the argument in
2010 // the original expression, since we will delete it below.
2011 Exp->setArg(i, 0);
2012 }
Steve Naroffab972d32007-11-04 22:37:50 +00002013 // Generate the funky cast.
2014 CastExpr *cast;
2015 llvm::SmallVector<QualType, 8> ArgTypes;
2016 QualType returnType;
2017
2018 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002019 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2020 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2021 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002022 ArgTypes.push_back(Context->getObjCIdType());
2023 ArgTypes.push_back(Context->getObjCSelType());
2024 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002025 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00002026 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002027 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2028 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002029 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002030 ArgTypes.push_back(t);
2031 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002032 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2033 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002034 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002035 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002036 }
2037 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002038 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002039
2040 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002041 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2042 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002043
2044 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2045 // If we don't do this cast, we get the following bizarre warning/note:
2046 // xx.m:13: warning: function called through a non-compatible type
2047 // xx.m:13: note: if this code is reached, the program will abort
2048 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2049 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002050
Steve Naroffab972d32007-11-04 22:37:50 +00002051 // Now do the "normal" pointer to function cast.
2052 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002053 &ArgTypes[0], ArgTypes.size(),
2054 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00002055 castType = Context->getPointerType(castType);
2056 cast = new CastExpr(castType, cast, SourceLocation());
2057
2058 // Don't forget the parens to enforce the proper binding.
2059 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2060
2061 const FunctionType *FT = msgSendType->getAsFunctionType();
2062 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2063 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002064 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002065 if (MsgSendStretFlavor) {
2066 // We have the method which returns a struct/union. Must also generate
2067 // call to objc_msgSend_stret and hang both varieties on a conditional
2068 // expression which dictate which one to envoke depending on size of
2069 // method's return type.
2070
2071 // Create a reference to the objc_msgSend_stret() declaration.
2072 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2073 SourceLocation());
2074 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2075 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2076 SourceLocation());
2077 // Now do the "normal" pointer to function cast.
2078 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002079 &ArgTypes[0], ArgTypes.size(),
2080 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002081 castType = Context->getPointerType(castType);
2082 cast = new CastExpr(castType, cast, SourceLocation());
2083
2084 // Don't forget the parens to enforce the proper binding.
2085 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2086
2087 FT = msgSendType->getAsFunctionType();
2088 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2089 FT->getResultType(), SourceLocation());
2090
2091 // Build sizeof(returnType)
2092 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2093 returnType, Context->getSizeType(),
2094 SourceLocation(), SourceLocation());
2095 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2096 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2097 // For X86 it is more complicated and some kind of target specific routine
2098 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002099 unsigned IntSize =
2100 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002101 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2102 Context->IntTy,
2103 SourceLocation());
2104 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2105 BinaryOperator::LE,
2106 Context->IntTy,
2107 SourceLocation());
2108 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2109 ConditionalOperator *CondExpr =
2110 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002111 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002112 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002113 return ReplacingStmt;
2114}
2115
2116Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2117 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002118 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002119 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002120
Chris Lattnere64b7772007-10-24 16:57:36 +00002121 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002122 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002123}
2124
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002125/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2126/// call to objc_getProtocol("proto-name").
2127Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2128 if (!GetProtocolFunctionDecl)
2129 SynthGetProtocolFunctionDecl();
2130 // Create a call to objc_getProtocol("ProtocolName").
2131 llvm::SmallVector<Expr*, 8> ProtoExprs;
2132 QualType argType = Context->getPointerType(Context->CharTy);
2133 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2134 strlen(Exp->getProtocol()->getName()),
2135 false, argType, SourceLocation(),
2136 SourceLocation()));
2137 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2138 &ProtoExprs[0],
2139 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002140 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002141 delete Exp;
2142 return ProtoExp;
2143
2144}
2145
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002146/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002147/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002148void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002149 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002150 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2151 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002152 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002153 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002154 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002155 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002156 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002157 SourceLocation LocStart = CDecl->getLocStart();
2158 SourceLocation LocEnd = CDecl->getLocEnd();
2159
2160 const char *startBuf = SM->getCharacterData(LocStart);
2161 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002162 // If no ivars and no root or if its root, directly or indirectly,
2163 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002164 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002165 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002166 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002167 return;
2168 }
2169
2170 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002171 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002172 Result += "\nstruct ";
2173 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002174 if (LangOpts.Microsoft)
2175 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002176
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002177 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002178 const char *cursor = strchr(startBuf, '{');
2179 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002180 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002181
2182 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002183 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002184 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002185 Result = "\n struct ";
2186 Result += RCDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002187 if (LangOpts.Microsoft)
2188 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002189
Steve Narofff69cc5d2008-01-30 19:17:43 +00002190 // Note: We don't name the field decl. This simplifies the "codegen" for
2191 // accessing a superclasses instance variables (and is similar to what gcc
2192 // does internally). The unnamed struct field feature is enabled with
2193 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2194 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002195 Result += ";\n";
2196
2197 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002198 SourceLocation OnePastCurly =
2199 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2200 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002201 }
2202 cursor++; // past '{'
2203
2204 // Now comment out any visibility specifiers.
2205 while (cursor < endBuf) {
2206 if (*cursor == '@') {
2207 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002208 // Skip whitespace.
2209 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2210 /*scan*/;
2211
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002212 // FIXME: presence of @public, etc. inside comment results in
2213 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002214 if (!strncmp(cursor, "public", strlen("public")) ||
2215 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002216 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002217 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002218 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002219 // FIXME: If there are cases where '<' is used in ivar declaration part
2220 // of user code, then scan the ivar list and use needToScanForQualifiers
2221 // for type checking.
2222 else if (*cursor == '<') {
2223 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002224 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002225 cursor = strchr(cursor, '>');
2226 cursor++;
2227 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002228 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002229 }
Steve Narofffea763e82007-11-14 19:25:57 +00002230 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002231 }
Steve Narofffea763e82007-11-14 19:25:57 +00002232 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002233 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002234 } else { // we don't have any instance variables - insert super struct.
2235 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2236 Result += " {\n struct ";
2237 Result += RCDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002238 if (LangOpts.Microsoft)
2239 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002240
Steve Narofff69cc5d2008-01-30 19:17:43 +00002241 // Note: We don't name the field decl. This simplifies the "codegen" for
2242 // accessing a superclasses instance variables (and is similar to what gcc
2243 // does internally). The unnamed struct field feature is enabled with
2244 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2245 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002246 Result += ";\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002247 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002248 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002249 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002250 if (!ObjCSynthesizedStructs.insert(CDecl))
2251 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002252}
2253
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002254// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002255/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002256void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002257 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002258 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002259 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002260 const char *ClassName,
2261 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002262 if (MethodBegin == MethodEnd) return;
2263
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002264 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002265 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002266 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002267 SEL _cmd;
2268 char *method_types;
2269 void *_imp;
2270 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002271 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002272 Result += "\nstruct _objc_method {\n";
2273 Result += "\tSEL _cmd;\n";
2274 Result += "\tchar *method_types;\n";
2275 Result += "\tvoid *_imp;\n";
2276 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002277
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002278 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002279 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002280
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002281 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002282
2283 /* struct {
2284 struct _objc_method_list *next_method;
2285 int method_count;
2286 struct _objc_method method_list[];
2287 }
2288 */
2289 Result += "\nstatic struct {\n";
2290 Result += "\tstruct _objc_method_list *next_method;\n";
2291 Result += "\tint method_count;\n";
2292 Result += "\tstruct _objc_method method_list[";
2293 Result += utostr(MethodEnd-MethodBegin);
2294 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002295 Result += prefix;
2296 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2297 Result += "_METHODS_";
2298 Result += ClassName;
2299 Result += " __attribute__ ((section (\"__OBJC, __";
2300 Result += IsInstanceMethod ? "inst" : "cls";
2301 Result += "_meth\")))= ";
2302 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002303
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002304 Result += "\t,{{(SEL)\"";
2305 Result += (*MethodBegin)->getSelector().getName().c_str();
2306 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002307 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002308 Result += "\", \"";
2309 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002310 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002311 Result += MethodInternalNames[*MethodBegin];
2312 Result += "}\n";
2313 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2314 Result += "\t ,{(SEL)\"";
2315 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002316 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002317 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002318 Result += "\", \"";
2319 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002320 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002321 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002322 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002323 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002324 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002325}
2326
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002327/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2328void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002329 int NumProtocols,
2330 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002331 const char *ClassName,
2332 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002333 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002334 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002335 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002336 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002337 // Output struct protocol_methods holder of method selector and type.
2338 if (!objc_protocol_methods &&
2339 (PDecl->getNumInstanceMethods() > 0
2340 || PDecl->getNumClassMethods() > 0)) {
2341 /* struct protocol_methods {
2342 SEL _cmd;
2343 char *method_types;
2344 }
2345 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002346 Result += "\nstruct protocol_methods {\n";
2347 Result += "\tSEL _cmd;\n";
2348 Result += "\tchar *method_types;\n";
2349 Result += "};\n";
2350
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002351 objc_protocol_methods = true;
2352 }
2353 int NumMethods = PDecl->getNumInstanceMethods();
2354 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002355 /* struct _objc_protocol_method_list {
2356 int protocol_method_count;
2357 struct protocol_methods protocols[];
2358 }
2359 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002360 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002361 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002362 Result += "\tstruct protocol_methods protocols[";
2363 Result += utostr(NumMethods);
2364 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002365 Result += PDecl->getName();
2366 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2367 "{\n\t" + utostr(NumMethods) + "\n";
2368
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002369 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002371 E = PDecl->instmeth_end(); I != E; ++I) {
2372 if (I == PDecl->instmeth_begin())
2373 Result += "\t ,{{(SEL)\"";
2374 else
2375 Result += "\t ,{(SEL)\"";
2376 Result += (*I)->getSelector().getName().c_str();
2377 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002378 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002379 Result += "\", \"";
2380 Result += MethodTypeString;
2381 Result += "\"}\n";
2382 }
2383 Result += "\t }\n};\n";
2384 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002385
2386 // Output class methods declared in this protocol.
2387 NumMethods = PDecl->getNumClassMethods();
2388 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002389 /* struct _objc_protocol_method_list {
2390 int protocol_method_count;
2391 struct protocol_methods protocols[];
2392 }
2393 */
2394 Result += "\nstatic struct {\n";
2395 Result += "\tint protocol_method_count;\n";
2396 Result += "\tstruct protocol_methods protocols[";
2397 Result += utostr(NumMethods);
2398 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002399 Result += PDecl->getName();
2400 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2401 "{\n\t";
2402 Result += utostr(NumMethods);
2403 Result += "\n";
2404
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002405 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002406 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002407 E = PDecl->classmeth_end(); I != E; ++I) {
2408 if (I == PDecl->classmeth_begin())
2409 Result += "\t ,{{(SEL)\"";
2410 else
2411 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002412 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002413 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002414 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002415 Result += "\", \"";
2416 Result += MethodTypeString;
2417 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002418 }
2419 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002420 }
2421 // Output:
2422 /* struct _objc_protocol {
2423 // Objective-C 1.0 extensions
2424 struct _objc_protocol_extension *isa;
2425 char *protocol_name;
2426 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002427 struct _objc_protocol_method_list *instance_methods;
2428 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002429 };
2430 */
2431 static bool objc_protocol = false;
2432 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002433 Result += "\nstruct _objc_protocol {\n";
2434 Result += "\tstruct _objc_protocol_extension *isa;\n";
2435 Result += "\tchar *protocol_name;\n";
2436 Result += "\tstruct _objc_protocol **protocol_list;\n";
2437 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2438 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2439 Result += "};\n";
2440
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002441 objc_protocol = true;
2442 }
2443
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002444 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2445 Result += PDecl->getName();
2446 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2447 "{\n\t0, \"";
2448 Result += PDecl->getName();
2449 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002450 if (PDecl->getNumInstanceMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002451 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002452 Result += PDecl->getName();
2453 Result += ", ";
2454 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002455 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002456 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002457 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002458 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002459 Result += PDecl->getName();
2460 Result += "\n";
2461 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002462 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002463 Result += "0\n";
2464 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002465 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002466 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002467 /* struct _objc_protocol_list {
2468 struct _objc_protocol_list *next;
2469 int protocol_count;
2470 struct _objc_protocol *class_protocols[];
2471 }
2472 */
2473 Result += "\nstatic struct {\n";
2474 Result += "\tstruct _objc_protocol_list *next;\n";
2475 Result += "\tint protocol_count;\n";
2476 Result += "\tstruct _objc_protocol *class_protocols[";
2477 Result += utostr(NumProtocols);
2478 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002479 Result += prefix;
2480 Result += "_PROTOCOLS_";
2481 Result += ClassName;
2482 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2483 "{\n\t0, ";
2484 Result += utostr(NumProtocols);
2485 Result += "\n";
2486
2487 Result += "\t,{&_OBJC_PROTOCOL_";
2488 Result += Protocols[0]->getName();
2489 Result += " \n";
2490
2491 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002492 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002493 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002494 Result += PDecl->getName();
2495 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002496 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002497 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002498 }
2499}
2500
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002501/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002502/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002503void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002504 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002506 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002507 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002508 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2509 CDecl = CDecl->getNextClassCategory())
2510 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2511 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002512
Chris Lattnereb44eee2007-12-23 01:40:15 +00002513 std::string FullCategoryName = ClassDecl->getName();
2514 FullCategoryName += '_';
2515 FullCategoryName += IDecl->getName();
2516
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002517 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002518 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002519 true, "CATEGORY_", FullCategoryName.c_str(),
2520 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002521
2522 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002523 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002524 false, "CATEGORY_", FullCategoryName.c_str(),
2525 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002526
2527 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002528 // Null CDecl is case of a category implementation with no category interface
2529 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002530 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002531 CDecl->getNumReferencedProtocols(),
2532 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002533 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002534
2535 /* struct _objc_category {
2536 char *category_name;
2537 char *class_name;
2538 struct _objc_method_list *instance_methods;
2539 struct _objc_method_list *class_methods;
2540 struct _objc_protocol_list *protocols;
2541 // Objective-C 1.0 extensions
2542 uint32_t size; // sizeof (struct _objc_category)
2543 struct _objc_property_list *instance_properties; // category's own
2544 // @property decl.
2545 };
2546 */
2547
2548 static bool objc_category = false;
2549 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002550 Result += "\nstruct _objc_category {\n";
2551 Result += "\tchar *category_name;\n";
2552 Result += "\tchar *class_name;\n";
2553 Result += "\tstruct _objc_method_list *instance_methods;\n";
2554 Result += "\tstruct _objc_method_list *class_methods;\n";
2555 Result += "\tstruct _objc_protocol_list *protocols;\n";
2556 Result += "\tunsigned int size;\n";
2557 Result += "\tstruct _objc_property_list *instance_properties;\n";
2558 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002559 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002560 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002561 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2562 Result += FullCategoryName;
2563 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2564 Result += IDecl->getName();
2565 Result += "\"\n\t, \"";
2566 Result += ClassDecl->getName();
2567 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002568
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002569 if (IDecl->getNumInstanceMethods() > 0) {
2570 Result += "\t, (struct _objc_method_list *)"
2571 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2572 Result += FullCategoryName;
2573 Result += "\n";
2574 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002575 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002576 Result += "\t, 0\n";
2577 if (IDecl->getNumClassMethods() > 0) {
2578 Result += "\t, (struct _objc_method_list *)"
2579 "&_OBJC_CATEGORY_CLASS_METHODS_";
2580 Result += FullCategoryName;
2581 Result += "\n";
2582 }
2583 else
2584 Result += "\t, 0\n";
2585
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002586 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002587 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2588 Result += FullCategoryName;
2589 Result += "\n";
2590 }
2591 else
2592 Result += "\t, 0\n";
2593 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002594}
2595
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002596/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2597/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002598void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2599 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002600 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002601 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002602 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002603 if (LangOpts.Microsoft)
2604 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002605 Result += ", ";
2606 Result += ivar->getName();
2607 Result += ")";
2608}
2609
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002610//===----------------------------------------------------------------------===//
2611// Meta Data Emission
2612//===----------------------------------------------------------------------===//
2613
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002614void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002615 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002616 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002617
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002618 // Explictly declared @interface's are already synthesized.
2619 if (CDecl->ImplicitInterfaceDecl()) {
2620 // FIXME: Implementation of a class with no @interface (legacy) doese not
2621 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002622 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002623 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002624
Chris Lattnerbe6df082007-12-12 07:56:42 +00002625 // Build _objc_ivar_list metadata for classes ivars if needed
2626 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2627 ? IDecl->getImplDeclNumIvars()
2628 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002629 if (NumIvars > 0) {
2630 static bool objc_ivar = false;
2631 if (!objc_ivar) {
2632 /* struct _objc_ivar {
2633 char *ivar_name;
2634 char *ivar_type;
2635 int ivar_offset;
2636 };
2637 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002638 Result += "\nstruct _objc_ivar {\n";
2639 Result += "\tchar *ivar_name;\n";
2640 Result += "\tchar *ivar_type;\n";
2641 Result += "\tint ivar_offset;\n";
2642 Result += "};\n";
2643
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002644 objc_ivar = true;
2645 }
2646
Steve Naroff946a6932008-03-11 00:12:29 +00002647 /* struct {
2648 int ivar_count;
2649 struct _objc_ivar ivar_list[nIvars];
2650 };
2651 */
2652 Result += "\nstatic struct {\n";
2653 Result += "\tint ivar_count;\n";
2654 Result += "\tstruct _objc_ivar ivar_list[";
2655 Result += utostr(NumIvars);
2656 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002657 Result += IDecl->getName();
2658 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2659 "{\n\t";
2660 Result += utostr(NumIvars);
2661 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002662
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002663 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002664 if (IDecl->getImplDeclNumIvars() > 0) {
2665 IVI = IDecl->ivar_begin();
2666 IVE = IDecl->ivar_end();
2667 } else {
2668 IVI = CDecl->ivar_begin();
2669 IVE = CDecl->ivar_end();
2670 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002671 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002672 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002673 Result += "\", \"";
2674 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002675 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2676 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002677 Result += StrEncoding;
2678 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002679 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002680 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002681 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002682 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002683 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002684 Result += "\", \"";
2685 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002686 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2687 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002688 Result += StrEncoding;
2689 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002690 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002691 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002692 }
2693
2694 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002695 }
2696
2697 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002698 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002699 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002700
2701 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002702 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002703 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002704
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002705 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002706 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002707 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002708 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002709
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002710
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002711 // Declaration of class/meta-class metadata
2712 /* struct _objc_class {
2713 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002714 const char *super_class_name;
2715 char *name;
2716 long version;
2717 long info;
2718 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002719 struct _objc_ivar_list *ivars;
2720 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002721 struct objc_cache *cache;
2722 struct objc_protocol_list *protocols;
2723 const char *ivar_layout;
2724 struct _objc_class_ext *ext;
2725 };
2726 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002727 static bool objc_class = false;
2728 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002729 Result += "\nstruct _objc_class {\n";
2730 Result += "\tstruct _objc_class *isa;\n";
2731 Result += "\tconst char *super_class_name;\n";
2732 Result += "\tchar *name;\n";
2733 Result += "\tlong version;\n";
2734 Result += "\tlong info;\n";
2735 Result += "\tlong instance_size;\n";
2736 Result += "\tstruct _objc_ivar_list *ivars;\n";
2737 Result += "\tstruct _objc_method_list *methods;\n";
2738 Result += "\tstruct objc_cache *cache;\n";
2739 Result += "\tstruct _objc_protocol_list *protocols;\n";
2740 Result += "\tconst char *ivar_layout;\n";
2741 Result += "\tstruct _objc_class_ext *ext;\n";
2742 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002743 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002744 }
2745
2746 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002747 ObjCInterfaceDecl *RootClass = 0;
2748 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002749 while (SuperClass) {
2750 RootClass = SuperClass;
2751 SuperClass = SuperClass->getSuperClass();
2752 }
2753 SuperClass = CDecl->getSuperClass();
2754
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002755 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2756 Result += CDecl->getName();
2757 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2758 "{\n\t(struct _objc_class *)\"";
2759 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2760 Result += "\"";
2761
2762 if (SuperClass) {
2763 Result += ", \"";
2764 Result += SuperClass->getName();
2765 Result += "\", \"";
2766 Result += CDecl->getName();
2767 Result += "\"";
2768 }
2769 else {
2770 Result += ", 0, \"";
2771 Result += CDecl->getName();
2772 Result += "\"";
2773 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002774 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002775 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002776 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002777 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002778 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002779 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002780 Result += "\n";
2781 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002782 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002783 Result += ", 0\n";
2784 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002785 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002786 Result += CDecl->getName();
2787 Result += ",0,0\n";
2788 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002789 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002790 Result += "\t,0,0,0,0\n";
2791 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002792
2793 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002794 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2795 Result += CDecl->getName();
2796 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2797 "{\n\t&_OBJC_METACLASS_";
2798 Result += CDecl->getName();
2799 if (SuperClass) {
2800 Result += ", \"";
2801 Result += SuperClass->getName();
2802 Result += "\", \"";
2803 Result += CDecl->getName();
2804 Result += "\"";
2805 }
2806 else {
2807 Result += ", 0, \"";
2808 Result += CDecl->getName();
2809 Result += "\"";
2810 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002811 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002812 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002813 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002814 Result += ",0";
2815 else {
2816 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002817 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002818 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002819 if (LangOpts.Microsoft)
2820 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002821 Result += ")";
2822 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002823 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002824 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002825 Result += CDecl->getName();
2826 Result += "\n\t";
2827 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002828 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002829 Result += ",0";
2830 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002831 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002832 Result += CDecl->getName();
2833 Result += ", 0\n\t";
2834 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002835 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002836 Result += ",0,0";
2837 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002838 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002839 Result += CDecl->getName();
2840 Result += ", 0,0\n";
2841 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002842 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002843 Result += ",0,0,0\n";
2844 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002845}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002846
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002847/// RewriteImplementations - This routine rewrites all method implementations
2848/// and emits meta-data.
2849
2850void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002851 int ClsDefCount = ClassImplementation.size();
2852 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002853
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002854 if (ClsDefCount == 0 && CatDefCount == 0)
2855 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002856 // Rewrite implemented methods
2857 for (int i = 0; i < ClsDefCount; i++)
2858 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002859
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002860 for (int i = 0; i < CatDefCount; i++)
2861 RewriteImplementationDecl(CategoryImplementation[i]);
2862
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002863 // This is needed for use of offsetof
2864 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002865
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002866 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002867 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002868 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002869
2870 // For each implemented category, write out all its meta data.
2871 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002872 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002873
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002874 // Write objc_symtab metadata
2875 /*
2876 struct _objc_symtab
2877 {
2878 long sel_ref_cnt;
2879 SEL *refs;
2880 short cls_def_cnt;
2881 short cat_def_cnt;
2882 void *defs[cls_def_cnt + cat_def_cnt];
2883 };
2884 */
2885
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002886 Result += "\nstruct _objc_symtab {\n";
2887 Result += "\tlong sel_ref_cnt;\n";
2888 Result += "\tSEL *refs;\n";
2889 Result += "\tshort cls_def_cnt;\n";
2890 Result += "\tshort cat_def_cnt;\n";
2891 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2892 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002893
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002894 Result += "static struct _objc_symtab "
2895 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2896 Result += "\t0, 0, " + utostr(ClsDefCount)
2897 + ", " + utostr(CatDefCount) + "\n";
2898 for (int i = 0; i < ClsDefCount; i++) {
2899 Result += "\t,&_OBJC_CLASS_";
2900 Result += ClassImplementation[i]->getName();
2901 Result += "\n";
2902 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002903
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002904 for (int i = 0; i < CatDefCount; i++) {
2905 Result += "\t,&_OBJC_CATEGORY_";
2906 Result += CategoryImplementation[i]->getClassInterface()->getName();
2907 Result += "_";
2908 Result += CategoryImplementation[i]->getName();
2909 Result += "\n";
2910 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002911
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002912 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002913
2914 // Write objc_module metadata
2915
2916 /*
2917 struct _objc_module {
2918 long version;
2919 long size;
2920 const char *name;
2921 struct _objc_symtab *symtab;
2922 }
2923 */
2924
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002925 Result += "\nstruct _objc_module {\n";
2926 Result += "\tlong version;\n";
2927 Result += "\tlong size;\n";
2928 Result += "\tconst char *name;\n";
2929 Result += "\tstruct _objc_symtab *symtab;\n";
2930 Result += "};\n\n";
2931 Result += "static struct _objc_module "
2932 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002933 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2934 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002935 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002936
2937 if (LangOpts.Microsoft) {
2938 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2939 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2940 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2941 Result += "&_OBJC_MODULES;\n";
2942 Result += "#pragma data_seg(pop)\n\n";
2943 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002944}
Chris Lattner311ff022007-10-16 22:36:42 +00002945