blob: 52775a25b5f7df2ae3ce305ac2e62e06747f9c16 [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 Narofff69cc5d2008-01-30 19:17:43 +000038 unsigned RewriteFailedDiag;
39
Chris Lattner01c57482007-10-17 22:35:30 +000040 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000041 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000042 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000045 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
46 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
47 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
49 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000050 llvm::SmallVector<Stmt *, 32> Stmts;
51 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000052 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000053
54 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000055 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000056 FunctionDecl *MsgSendStretFunctionDecl;
57 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000058 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000059 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000060 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000061 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000062 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000063 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000064
Steve Naroffbeaf2992007-11-03 11:27:19 +000065 // ObjC string constant support.
66 FileVarDecl *ConstantStringClassReference;
67 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000068
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000069 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000070 int BcLabelCount;
71
Steve Naroff874e2322007-11-15 10:28:18 +000072 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000074 RecordDecl *SuperStructDecl;
75
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000076 // Needed for header files being rewritten
77 bool IsHeader;
78
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000079 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000080 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000081 void Initialize(ASTContext &context);
82
Chris Lattner8a12c272007-10-11 18:38:32 +000083
Chris Lattnerf04da132007-10-24 17:06:59 +000084 // Top Level Driver code.
85 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000086 void HandleDeclInMainFile(Decl *D);
Steve Naroff0113c9d2008-01-28 21:34:52 +000087 RewriteTest(bool isHeader, Diagnostic &D) : Diags(D) {
Steve Narofff69cc5d2008-01-30 19:17:43 +000088 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +000089 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
90 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +000091 }
Chris Lattnerf04da132007-10-24 17:06:59 +000092 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000093
94 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +000095 // If replacement succeeded or warning disabled return with no warning.
96 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000097 return;
98
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000099 SourceRange Range = Old->getSourceRange();
100 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
101 0, 0, &Range, 1);
102 }
103
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000104 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000105 // If insertion succeeded or warning disabled return with no warning.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000106 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
107 SilenceRewriteMacroWarning)
108 return;
109
110 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
111 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000112
Chris Lattneraadaf782008-01-31 19:51:04 +0000113 void RemoveText(SourceLocation Loc, unsigned StrLen) {
114 // If removal succeeded or warning disabled return with no warning.
115 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
116 return;
117
118 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
119 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000120
Chris Lattneraadaf782008-01-31 19:51:04 +0000121 void ReplaceText(SourceLocation Start, unsigned OrigLength,
122 const char *NewStr, unsigned NewLength) {
123 // If removal succeeded or warning disabled return with no warning.
124 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
125 SilenceRewriteMacroWarning)
126 return;
127
128 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
129 }
130
Chris Lattnerf04da132007-10-24 17:06:59 +0000131 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000132 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000133 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000135 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
136 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000137 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000138 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
139 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
140 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
141 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
142 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
143 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000144 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000145 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000146 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000147 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000148 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000149
Chris Lattnerf04da132007-10-24 17:06:59 +0000150 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000151 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000152 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000153 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000154 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000155 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000156 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000157 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000158 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000159 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000160 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
161 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
162 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000163 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
164 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000165 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
166 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000167 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000168 Stmt *RewriteBreakStmt(BreakStmt *S);
169 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000170 void SynthCountByEnumWithState(std::string &buf);
171
Steve Naroff09b266e2007-10-30 23:14:51 +0000172 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000173 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000174 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000175 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000176 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000177 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000178 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000179 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000180 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000181 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000182
Chris Lattnerf04da132007-10-24 17:06:59 +0000183 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000185 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000186
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000187 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000188 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000189
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
191 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000192 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000193 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000194 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000195 const char *ClassName,
196 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000197
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000198 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000199 int NumProtocols,
200 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000201 const char *ClassName,
202 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000203 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000204 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000205 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
206 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000207 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000208 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000209 };
210}
211
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000212static bool IsHeaderFile(const std::string &Filename) {
213 std::string::size_type DotPos = Filename.rfind('.');
214
215 if (DotPos == std::string::npos) {
216 // no file extension
217 return false;
218 }
219
220 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
221 // C header: .h
222 // C++ header: .hh or .H;
223 return Ext == "h" || Ext == "hh" || Ext == "H";
224}
225
226ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
227 Diagnostic &Diags) {
228 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattnere365c502007-11-30 22:25:36 +0000229}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000230
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000231void RewriteTest::Initialize(ASTContext &context) {
232 Context = &context;
233 SM = &Context->getSourceManager();
234 MsgSendFunctionDecl = 0;
235 MsgSendSuperFunctionDecl = 0;
236 MsgSendStretFunctionDecl = 0;
237 MsgSendSuperStretFunctionDecl = 0;
238 MsgSendFpretFunctionDecl = 0;
239 GetClassFunctionDecl = 0;
240 GetMetaClassFunctionDecl = 0;
241 SelGetUidFunctionDecl = 0;
242 CFStringFunctionDecl = 0;
243 GetProtocolFunctionDecl = 0;
244 ConstantStringClassReference = 0;
245 NSStringRecord = 0;
246 CurMethodDecl = 0;
247 SuperStructDecl = 0;
248 BcLabelCount = 0;
249
250 // Get the ID and start/end of the main file.
251 MainFileID = SM->getMainFileID();
252 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
253 MainFileStart = MainBuf->getBufferStart();
254 MainFileEnd = MainBuf->getBufferEnd();
255
256
257 Rewrite.setSourceMgr(Context->getSourceManager());
258 // declaring objc_selector outside the parameter list removes a silly
259 // scope related warning...
260 const char *s = "#pragma once\n"
261 "struct objc_selector; struct objc_class;\n"
262 "#ifndef OBJC_SUPER\n"
263 "struct objc_super { struct objc_object *o; "
264 "struct objc_object *superClass; };\n"
265 "#define OBJC_SUPER\n"
266 "#endif\n"
267 "#ifndef _REWRITER_typedef_Protocol\n"
268 "typedef struct objc_object Protocol;\n"
269 "#define _REWRITER_typedef_Protocol\n"
270 "#endif\n"
271 "extern struct objc_object *objc_msgSend"
272 "(struct objc_object *, struct objc_selector *, ...);\n"
273 "extern struct objc_object *objc_msgSendSuper"
274 "(struct objc_super *, struct objc_selector *, ...);\n"
275 "extern struct objc_object *objc_msgSend_stret"
276 "(struct objc_object *, struct objc_selector *, ...);\n"
277 "extern struct objc_object *objc_msgSendSuper_stret"
278 "(struct objc_super *, struct objc_selector *, ...);\n"
279 "extern struct objc_object *objc_msgSend_fpret"
280 "(struct objc_object *, struct objc_selector *, ...);\n"
281 "extern struct objc_object *objc_getClass"
282 "(const char *);\n"
283 "extern struct objc_object *objc_getMetaClass"
284 "(const char *);\n"
285 "extern void objc_exception_throw(struct objc_object *);\n"
286 "extern void objc_exception_try_enter(void *);\n"
287 "extern void objc_exception_try_exit(void *);\n"
288 "extern struct objc_object *objc_exception_extract(void *);\n"
289 "extern int objc_exception_match"
290 "(struct objc_class *, struct objc_object *, ...);\n"
291 "extern Protocol *objc_getProtocol(const char *);\n"
292 "#include <objc/objc.h>\n"
293 "#ifndef __FASTENUMERATIONSTATE\n"
294 "struct __objcFastEnumerationState {\n\t"
295 "unsigned long state;\n\t"
296 "id *itemsPtr;\n\t"
297 "unsigned long *mutationsPtr;\n\t"
298 "unsigned long extra[5];\n};\n"
299 "#define __FASTENUMERATIONSTATE\n"
300 "#endif\n";
301 if (IsHeader) {
302 // insert the whole string when rewriting a header file
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000303 InsertText(SourceLocation::getFileLoc(MainFileID, 0), s, strlen(s));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000304 }
305 else {
306 // Not rewriting header, exclude the #pragma once pragma
307 const char *p = s + strlen("#pragma once\n");
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000308 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000309 }
310}
311
312
Chris Lattnerf04da132007-10-24 17:06:59 +0000313//===----------------------------------------------------------------------===//
314// Top Level Driver Code
315//===----------------------------------------------------------------------===//
316
Chris Lattner8a12c272007-10-11 18:38:32 +0000317void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000318 // Two cases: either the decl could be in the main file, or it could be in a
319 // #included file. If the former, rewrite it now. If the later, check to see
320 // if we rewrote the #include/#import.
321 SourceLocation Loc = D->getLocation();
322 Loc = SM->getLogicalLoc(Loc);
323
324 // If this is for a builtin, ignore it.
325 if (Loc.isInvalid()) return;
326
Steve Naroffebf2b562007-10-23 23:50:29 +0000327 // Look for built-in declarations that we need to refer during the rewrite.
328 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000329 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000330 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
331 // declared in <Foundation/NSString.h>
332 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
333 ConstantStringClassReference = FVD;
334 return;
335 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000336 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000337 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000338 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000339 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000340 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000341 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000342 } else if (ObjCForwardProtocolDecl *FP =
343 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000344 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000345 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000346 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000347 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
348 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000349}
350
Chris Lattnerf04da132007-10-24 17:06:59 +0000351/// HandleDeclInMainFile - This is called for each top-level decl defined in the
352/// main file of the input.
353void RewriteTest::HandleDeclInMainFile(Decl *D) {
354 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
355 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000356 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000357
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000358 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000359 if (Stmt *Body = MD->getBody()) {
360 //Body->dump();
361 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000362 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000363 CurMethodDecl = 0;
364 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000365 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000366 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000367 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000368 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000369 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000370 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000371 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000372 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000373 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000374 if (VD->getInit())
375 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
376 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000377 // Nothing yet.
378}
379
380RewriteTest::~RewriteTest() {
381 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000382
383 // Rewrite tabs if we care.
384 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000385
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000386 RewriteInclude();
387
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000388 // Rewrite Objective-c meta data*
389 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000390 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000391
Chris Lattnerf04da132007-10-24 17:06:59 +0000392 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
393 // we are done.
394 if (const RewriteBuffer *RewriteBuf =
395 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000396 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000397 std::string S(RewriteBuf->begin(), RewriteBuf->end());
398 printf("%s\n", S.c_str());
399 } else {
400 printf("No changes\n");
401 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000402 // Emit metadata.
403 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000404}
405
Chris Lattnerf04da132007-10-24 17:06:59 +0000406//===----------------------------------------------------------------------===//
407// Syntactic (non-AST) Rewriting Code
408//===----------------------------------------------------------------------===//
409
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000410void RewriteTest::RewriteInclude() {
411 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
412 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
413 const char *MainBufStart = MainBuf.first;
414 const char *MainBufEnd = MainBuf.second;
415 size_t ImportLen = strlen("import");
416 size_t IncludeLen = strlen("include");
417
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000418 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000419 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
420 if (*BufPtr == '#') {
421 if (++BufPtr == MainBufEnd)
422 return;
423 while (*BufPtr == ' ' || *BufPtr == '\t')
424 if (++BufPtr == MainBufEnd)
425 return;
426 if (!strncmp(BufPtr, "import", ImportLen)) {
427 // replace import with include
428 SourceLocation ImportLoc =
429 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000430 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000431 BufPtr += ImportLen;
432 }
433 }
434 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000435}
436
Chris Lattnerf04da132007-10-24 17:06:59 +0000437void RewriteTest::RewriteTabs() {
438 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
439 const char *MainBufStart = MainBuf.first;
440 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000441
Chris Lattnerf04da132007-10-24 17:06:59 +0000442 // Loop over the whole file, looking for tabs.
443 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
444 if (*BufPtr != '\t')
445 continue;
446
447 // Okay, we found a tab. This tab will turn into at least one character,
448 // but it depends on which 'virtual column' it is in. Compute that now.
449 unsigned VCol = 0;
450 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
451 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
452 ++VCol;
453
454 // Okay, now that we know the virtual column, we know how many spaces to
455 // insert. We assume 8-character tab-stops.
456 unsigned Spaces = 8-(VCol & 7);
457
458 // Get the location of the tab.
459 SourceLocation TabLoc =
460 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
461
462 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000463 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000464 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000465}
466
467
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000468void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000469 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000470 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000471
472 // Get the start location and compute the semi location.
473 SourceLocation startLoc = ClassDecl->getLocation();
474 const char *startBuf = SM->getCharacterData(startLoc);
475 const char *semiPtr = strchr(startBuf, ';');
476
477 // Translate to typedef's that forward reference structs with the same name
478 // as the class. As a convenience, we include the original declaration
479 // as a comment.
480 std::string typedefString;
481 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000482 typedefString.append(startBuf, semiPtr-startBuf+1);
483 typedefString += "\n";
484 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000485 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000486 typedefString += "#ifndef _REWRITER_typedef_";
487 typedefString += ForwardDecl->getName();
488 typedefString += "\n";
489 typedefString += "#define _REWRITER_typedef_";
490 typedefString += ForwardDecl->getName();
491 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000492 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000493 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000494 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000495 }
496
497 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000498 ReplaceText(startLoc, semiPtr-startBuf+1,
499 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000500}
501
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000502void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000503 SourceLocation LocStart = Method->getLocStart();
504 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000505
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000506 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000507 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000508 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000509 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000510 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000511 }
512}
513
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000514void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000515{
516 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000517 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000518 SourceLocation Loc = Property->getLocation();
519
Chris Lattneraadaf782008-01-31 19:51:04 +0000520 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000521
522 // FIXME: handle properties that are declared across multiple lines.
523 }
524}
525
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000526void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000527 SourceLocation LocStart = CatDecl->getLocStart();
528
529 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000530 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000531
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000532 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000533 E = CatDecl->instmeth_end(); I != E; ++I)
534 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000535 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000536 E = CatDecl->classmeth_end(); I != E; ++I)
537 RewriteMethodDeclaration(*I);
538
Steve Naroff423cb562007-10-30 13:30:57 +0000539 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000540 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000541}
542
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000543void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000544 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000545
Steve Naroff752d6ef2007-10-30 16:42:30 +0000546 SourceLocation LocStart = PDecl->getLocStart();
547
548 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000549 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000550
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000551 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000552 E = PDecl->instmeth_end(); I != E; ++I)
553 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000554 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000555 E = PDecl->classmeth_end(); I != E; ++I)
556 RewriteMethodDeclaration(*I);
557
Steve Naroff752d6ef2007-10-30 16:42:30 +0000558 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000559 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000560 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000561
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000562 // Must comment out @optional/@required
563 const char *startBuf = SM->getCharacterData(LocStart);
564 const char *endBuf = SM->getCharacterData(LocEnd);
565 for (const char *p = startBuf; p < endBuf; p++) {
566 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
567 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000568 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000569 ReplaceText(OptionalLoc, strlen("@optional"),
570 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000571
572 }
573 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
574 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000575 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000576 ReplaceText(OptionalLoc, strlen("@required"),
577 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000578
579 }
580 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000581}
582
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000583void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000584 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000585 if (LocStart.isInvalid())
586 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000587 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000588 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000589}
590
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000591void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000592 std::string &ResultStr) {
593 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000594 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000595 ResultStr += "id";
596 else
597 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000598 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000599
600 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000601 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000602
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000603 if (OMD->isInstance())
604 NameStr += "_I_";
605 else
606 NameStr += "_C_";
607
608 NameStr += OMD->getClassInterface()->getName();
609 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000610
611 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000612 if (ObjCCategoryImplDecl *CID =
613 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000614 NameStr += CID->getName();
615 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000616 }
617 // Append selector names, replacing ':' with '_'
618 const char *selName = OMD->getSelector().getName().c_str();
619 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000620 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000621 else {
622 std::string selString = OMD->getSelector().getName();
623 int len = selString.size();
624 for (int i = 0; i < len; i++)
625 if (selString[i] == ':')
626 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000627 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000628 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000629 // Remember this name for metadata emission
630 MethodInternalNames[OMD] = NameStr;
631 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000632
633 // Rewrite arguments
634 ResultStr += "(";
635
636 // invisible arguments
637 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000638 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000639 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000640 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000641 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000642 ResultStr += selfTy.getAsString();
643 }
644 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000645 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000646
647 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000648 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000649 ResultStr += " _cmd";
650
651 // Method arguments.
652 for (int i = 0; i < OMD->getNumParams(); i++) {
653 ParmVarDecl *PDecl = OMD->getParamDecl(i);
654 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000655 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000656 ResultStr += "id";
657 else
658 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000659 ResultStr += " ";
660 ResultStr += PDecl->getName();
661 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000662 if (OMD->isVariadic())
663 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000664 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000665
666}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000667void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000668 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
669 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000670
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000671 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000672 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000673 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000674 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000675
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000676 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000677 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
678 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000679 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000680 ObjCMethodDecl *OMD = *I;
681 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000682 SourceLocation LocStart = OMD->getLocStart();
683 SourceLocation LocEnd = OMD->getBody()->getLocStart();
684
685 const char *startBuf = SM->getCharacterData(LocStart);
686 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000687 ReplaceText(LocStart, endBuf-startBuf,
688 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000689 }
690
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000691 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000692 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
693 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000694 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000695 ObjCMethodDecl *OMD = *I;
696 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000697 SourceLocation LocStart = OMD->getLocStart();
698 SourceLocation LocEnd = OMD->getBody()->getLocStart();
699
700 const char *startBuf = SM->getCharacterData(LocStart);
701 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000702 ReplaceText(LocStart, endBuf-startBuf,
703 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000704 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000705 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000706 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000707 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000708 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000709}
710
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000712 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000713 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000714 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000715 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000716 ResultStr += ClassDecl->getName();
717 ResultStr += "\n";
718 ResultStr += "#define _REWRITER_typedef_";
719 ResultStr += ClassDecl->getName();
720 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000721 ResultStr += "typedef struct ";
722 ResultStr += ClassDecl->getName();
723 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000724 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000725 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000726
727 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000728 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000729 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000730 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000731
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000732 RewriteProperties(ClassDecl->getNumPropertyDecl(),
733 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000735 E = ClassDecl->instmeth_end(); I != E; ++I)
736 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000737 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000738 E = ClassDecl->classmeth_end(); I != E; ++I)
739 RewriteMethodDeclaration(*I);
740
Steve Naroff2feac5e2007-10-30 03:43:13 +0000741 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000742 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000743}
744
Steve Naroff7e3411b2007-11-15 02:58:25 +0000745Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000746 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000747 if (IV->isFreeIvar()) {
748 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
749 IV->getLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000750 ReplaceStmt(IV, Replacement);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000751 delete IV;
752 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000753 } else {
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000754#if 0
755 /// This code is not right. It seems unnecessary. It breaks use of
756 /// ivar reference used as 'receiver' of an expression; as in:
757 /// [newInv->_container addObject:0];
Steve Naroffc2a689b2007-11-15 11:33:00 +0000758 if (CurMethodDecl) {
759 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000760 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000761 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
762 IdentifierInfo *II = intT->getDecl()->getIdentifier();
763 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
764 II, 0);
765 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
766
767 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
768 // Don't forget the parens to enforce the proper binding.
769 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000770 ReplaceStmt(IV->getBase(), PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +0000771 delete IV->getBase();
772 return PE;
773 }
774 }
775 }
Fariborz Jahanian7da8d942008-01-23 20:34:40 +0000776#endif
Steve Naroff7e3411b2007-11-15 02:58:25 +0000777 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000778 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000779}
780
Chris Lattnerf04da132007-10-24 17:06:59 +0000781//===----------------------------------------------------------------------===//
782// Function Body / Expression rewriting
783//===----------------------------------------------------------------------===//
784
Steve Narofff3473a72007-11-09 15:20:18 +0000785Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000786 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
787 isa<DoStmt>(S) || isa<ForStmt>(S))
788 Stmts.push_back(S);
789 else if (isa<ObjCForCollectionStmt>(S)) {
790 Stmts.push_back(S);
791 ObjCBcLabelNo.push_back(++BcLabelCount);
792 }
793
Chris Lattner338d1e22008-01-31 05:10:40 +0000794 SourceLocation OrigStmtEnd = S->getLocEnd();
795
796 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000797 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
798 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000799 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000800 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000801 if (newStmt)
802 *CI = newStmt;
803 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000804
805 // Handle specific things.
806 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
807 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000808
809 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
810 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000811
812 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
813 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000814
Steve Naroffbeaf2992007-11-03 11:27:19 +0000815 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
816 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000817
Steve Naroff934f2762007-10-24 22:48:43 +0000818 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
819 // Before we rewrite it, put the original message expression in a comment.
820 SourceLocation startLoc = MessExpr->getLocStart();
821 SourceLocation endLoc = MessExpr->getLocEnd();
822
823 const char *startBuf = SM->getCharacterData(startLoc);
824 const char *endBuf = SM->getCharacterData(endLoc);
825
826 std::string messString;
827 messString += "// ";
828 messString.append(startBuf, endBuf-startBuf+1);
829 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000830
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000831 // FIXME: Missing definition of
832 // InsertText(clang::SourceLocation, char const*, unsigned int).
833 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000834 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000835 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000836 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000837 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000838
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000839 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
840 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000841
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000842 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
843 return RewriteObjCSynchronizedStmt(StmtTry);
844
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000845 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
846 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000847
848 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
849 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000850
851 if (ObjCForCollectionStmt *StmtForCollection =
852 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000853 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000854 if (BreakStmt *StmtBreakStmt =
855 dyn_cast<BreakStmt>(S))
856 return RewriteBreakStmt(StmtBreakStmt);
857 if (ContinueStmt *StmtContinueStmt =
858 dyn_cast<ContinueStmt>(S))
859 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000860
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000861 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
862 isa<DoStmt>(S) || isa<ForStmt>(S)) {
863 assert(!Stmts.empty() && "Statement stack is empty");
864 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
865 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
866 && "Statement stack mismatch");
867 Stmts.pop_back();
868 }
Steve Naroff874e2322007-11-15 10:28:18 +0000869#if 0
870 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
871 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
872 // Get the new text.
873 std::ostringstream Buf;
874 Replacement->printPretty(Buf);
875 const std::string &Str = Buf.str();
876
877 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000878 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000879 delete S;
880 return Replacement;
881 }
882#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000883 // Return this stmt unmodified.
884 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000885}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000886
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000887/// SynthCountByEnumWithState - To print:
888/// ((unsigned int (*)
889/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
890/// (void *)objc_msgSend)((id)l_collection,
891/// sel_registerName(
892/// "countByEnumeratingWithState:objects:count:"),
893/// &enumState,
894/// (id *)items, (unsigned int)16)
895///
896void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
897 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
898 "id *, unsigned int))(void *)objc_msgSend)";
899 buf += "\n\t\t";
900 buf += "((id)l_collection,\n\t\t";
901 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
902 buf += "\n\t\t";
903 buf += "&enumState, "
904 "(id *)items, (unsigned int)16)";
905}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000906
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000907/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
908/// statement to exit to its outer synthesized loop.
909///
910Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
911 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
912 return S;
913 // replace break with goto __break_label
914 std::string buf;
915
916 SourceLocation startLoc = S->getLocStart();
917 buf = "goto __break_label_";
918 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000919 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000920
921 return 0;
922}
923
924/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
925/// statement to continue with its inner synthesized loop.
926///
927Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
928 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
929 return S;
930 // replace continue with goto __continue_label
931 std::string buf;
932
933 SourceLocation startLoc = S->getLocStart();
934 buf = "goto __continue_label_";
935 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000936 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000937
938 return 0;
939}
940
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000941/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000942/// It rewrites:
943/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000944
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000945/// Into:
946/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000947/// type elem;
948/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000949/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000950/// id l_collection = (id)collection;
951/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
952/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000953/// if (limit) {
954/// unsigned long startMutations = *enumState.mutationsPtr;
955/// do {
956/// unsigned long counter = 0;
957/// do {
958/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000959/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000960/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000961/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000962/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000963/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000964/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
965/// objects:items count:16]);
966/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000967/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000968/// }
969/// else
970/// elem = nil;
971/// }
972///
Chris Lattner338d1e22008-01-31 05:10:40 +0000973Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
974 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000975 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
976 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
977 "ObjCForCollectionStmt Statement stack mismatch");
978 assert(!ObjCBcLabelNo.empty() &&
979 "ObjCForCollectionStmt - Label No stack empty");
980
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000981 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000982 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000983 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000984 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000985 std::string buf;
986 buf = "\n{\n\t";
987 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
988 // type elem;
989 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000990 elementTypeAsString = ElementType.getAsString();
991 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000992 buf += " ";
993 elementName = DS->getDecl()->getName();
994 buf += elementName;
995 buf += ";\n\t";
996 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000997 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000998 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000999 elementTypeAsString = DR->getDecl()->getType().getAsString();
1000 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001001 else
1002 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1003
1004 // struct __objcFastEnumerationState enumState = { 0 };
1005 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1006 // id items[16];
1007 buf += "id items[16];\n\t";
1008 // id l_collection = (id)
1009 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001010 // Find start location of 'collection' the hard way!
1011 const char *startCollectionBuf = startBuf;
1012 startCollectionBuf += 3; // skip 'for'
1013 startCollectionBuf = strchr(startCollectionBuf, '(');
1014 startCollectionBuf++; // skip '('
1015 // find 'in' and skip it.
1016 while (*startCollectionBuf != ' ' ||
1017 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1018 (*(startCollectionBuf+3) != ' ' &&
1019 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1020 startCollectionBuf++;
1021 startCollectionBuf += 3;
1022
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001023 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001024 ReplaceText(startLoc, startCollectionBuf - startBuf,
1025 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001026 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001027 SourceLocation rightParenLoc = S->getRParenLoc();
1028 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1029 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001030 buf = ";\n\t";
1031
1032 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1033 // objects:items count:16];
1034 // which is synthesized into:
1035 // unsigned int limit =
1036 // ((unsigned int (*)
1037 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1038 // (void *)objc_msgSend)((id)l_collection,
1039 // sel_registerName(
1040 // "countByEnumeratingWithState:objects:count:"),
1041 // (struct __objcFastEnumerationState *)&state,
1042 // (id *)items, (unsigned int)16);
1043 buf += "unsigned long limit =\n\t\t";
1044 SynthCountByEnumWithState(buf);
1045 buf += ";\n\t";
1046 /// if (limit) {
1047 /// unsigned long startMutations = *enumState.mutationsPtr;
1048 /// do {
1049 /// unsigned long counter = 0;
1050 /// do {
1051 /// if (startMutations != *enumState.mutationsPtr)
1052 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001053 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001054 buf += "if (limit) {\n\t";
1055 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1056 buf += "do {\n\t\t";
1057 buf += "unsigned long counter = 0;\n\t\t";
1058 buf += "do {\n\t\t\t";
1059 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1060 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1061 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001062 buf += " = (";
1063 buf += elementTypeAsString;
1064 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001065 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001066 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001067
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001068 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001069 /// } while (counter < limit);
1070 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1071 /// objects:items count:16]);
1072 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001073 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001074 /// }
1075 /// else
1076 /// elem = nil;
1077 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001078 ///
1079 buf = ";\n\t";
1080 buf += "__continue_label_";
1081 buf += utostr(ObjCBcLabelNo.back());
1082 buf += ": ;";
1083 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001084 buf += "} while (counter < limit);\n\t";
1085 buf += "} while (limit = ";
1086 SynthCountByEnumWithState(buf);
1087 buf += ");\n\t";
1088 buf += elementName;
1089 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001090 buf += "__break_label_";
1091 buf += utostr(ObjCBcLabelNo.back());
1092 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001093 buf += "}\n\t";
1094 buf += "else\n\t\t";
1095 buf += elementName;
1096 buf += " = nil;\n";
1097 buf += "}\n";
1098 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001099 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001100 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001101 Stmts.pop_back();
1102 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001103 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001104}
1105
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001106/// RewriteObjCSynchronizedStmt -
1107/// This routine rewrites @synchronized(expr) stmt;
1108/// into:
1109/// objc_sync_enter(expr);
1110/// @try stmt @finally { objc_sync_exit(expr); }
1111///
1112Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1113 // Get the start location and compute the semi location.
1114 SourceLocation startLoc = S->getLocStart();
1115 const char *startBuf = SM->getCharacterData(startLoc);
1116
1117 assert((*startBuf == '@') && "bogus @synchronized location");
1118
1119 std::string buf;
1120 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001121 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001122 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1123 const char *endBuf = SM->getCharacterData(endLoc);
1124 endBuf++;
1125 const char *rparenBuf = strchr(endBuf, ')');
1126 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1127 buf = ");\n";
1128 // declare a new scope with two variables, _stack and _rethrow.
1129 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1130 buf += "int buf[18/*32-bit i386*/];\n";
1131 buf += "char *pointers[4];} _stack;\n";
1132 buf += "id volatile _rethrow = 0;\n";
1133 buf += "objc_exception_try_enter(&_stack);\n";
1134 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001135 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001136 startLoc = S->getSynchBody()->getLocEnd();
1137 startBuf = SM->getCharacterData(startLoc);
1138
1139 assert((*startBuf == '}') && "bogus @try block");
1140 SourceLocation lastCurlyLoc = startLoc;
1141 buf = "}\nelse {\n";
1142 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1143 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1144 // FIXME: This must be objc_sync_exit(syncExpr);
1145 buf += " objc_sync_exit();\n";
1146 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1147 buf += "}\n";
1148 buf += "}";
1149
Chris Lattneraadaf782008-01-31 19:51:04 +00001150 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001151 return 0;
1152}
1153
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001154Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001155 // Get the start location and compute the semi location.
1156 SourceLocation startLoc = S->getLocStart();
1157 const char *startBuf = SM->getCharacterData(startLoc);
1158
1159 assert((*startBuf == '@') && "bogus @try location");
1160
1161 std::string buf;
1162 // declare a new scope with two variables, _stack and _rethrow.
1163 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1164 buf += "int buf[18/*32-bit i386*/];\n";
1165 buf += "char *pointers[4];} _stack;\n";
1166 buf += "id volatile _rethrow = 0;\n";
1167 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001168 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001169
Chris Lattneraadaf782008-01-31 19:51:04 +00001170 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001171
1172 startLoc = S->getTryBody()->getLocEnd();
1173 startBuf = SM->getCharacterData(startLoc);
1174
1175 assert((*startBuf == '}') && "bogus @try block");
1176
1177 SourceLocation lastCurlyLoc = startLoc;
1178
1179 startLoc = startLoc.getFileLocWithOffset(1);
1180 buf = " /* @catch begin */ else {\n";
1181 buf += " id _caught = objc_exception_extract(&_stack);\n";
1182 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001183 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001184 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1185 buf += " else { /* @catch continue */";
1186
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001187 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001188
1189 bool sawIdTypedCatch = false;
1190 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001191 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001192 while (catchList) {
1193 Stmt *catchStmt = catchList->getCatchParamStmt();
1194
1195 if (catchList == S->getCatchStmts())
1196 buf = "if ("; // we are generating code for the first catch clause
1197 else
1198 buf = "else if (";
1199 startLoc = catchList->getLocStart();
1200 startBuf = SM->getCharacterData(startLoc);
1201
1202 assert((*startBuf == '@') && "bogus @catch location");
1203
1204 const char *lParenLoc = strchr(startBuf, '(');
1205
Steve Naroffe12e6922008-02-01 20:02:07 +00001206 if (!catchStmt) { // handle "..."
1207 // Now rewrite the body...
1208 lastCatchBody = catchList->getCatchBody();
1209 SourceLocation rParenLoc = catchList->getRParenLoc();
1210 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1211 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1212 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1213 assert((*rParenBuf == ')') && "bogus @catch paren location");
1214 assert((*bodyBuf == '{') && "bogus @catch body location");
1215
1216 buf += "1) { id _tmp = _caught;";
1217 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1218 buf.c_str(), buf.size());
1219 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001220 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001221 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001222 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001223 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001224 sawIdTypedCatch = true;
1225 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001226 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001227
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001228 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001229 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001230 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001231 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001232 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001233 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001234 }
1235 }
1236 // Now rewrite the body...
1237 lastCatchBody = catchList->getCatchBody();
1238 SourceLocation rParenLoc = catchList->getRParenLoc();
1239 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1240 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1241 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1242 assert((*rParenBuf == ')') && "bogus @catch paren location");
1243 assert((*bodyBuf == '{') && "bogus @catch body location");
1244
1245 buf = " = _caught;";
1246 // Here we replace ") {" with "= _caught;" (which initializes and
1247 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001248 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001249 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001250 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001251 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001252 // make sure all the catch bodies get rewritten!
1253 // FIXME: this call should be removed when the iterator for ObjCAtTryStmt
1254 // is fixed. Currently, it only returns the first catch statement!
1255 RewriteFunctionBodyOrGlobalInitializer(lastCatchBody);
Steve Naroff75730982007-11-07 04:08:17 +00001256 catchList = catchList->getNextCatchStmt();
1257 }
1258 // Complete the catch list...
1259 if (lastCatchBody) {
1260 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1261 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1262 assert((*bodyBuf == '}') && "bogus @catch body location");
1263 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1264 buf = " } } /* @catch end */\n";
1265
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001266 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001267
1268 // Set lastCurlyLoc
1269 lastCurlyLoc = lastCatchBody->getLocEnd();
1270 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001271 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001272 startLoc = finalStmt->getLocStart();
1273 startBuf = SM->getCharacterData(startLoc);
1274 assert((*startBuf == '@') && "bogus @finally start");
1275
1276 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001277 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001278
1279 Stmt *body = finalStmt->getFinallyBody();
1280 SourceLocation startLoc = body->getLocStart();
1281 SourceLocation endLoc = body->getLocEnd();
1282 const char *startBuf = SM->getCharacterData(startLoc);
1283 const char *endBuf = SM->getCharacterData(endLoc);
1284 assert((*startBuf == '{') && "bogus @finally body location");
1285 assert((*endBuf == '}') && "bogus @finally body location");
1286
1287 startLoc = startLoc.getFileLocWithOffset(1);
1288 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001289 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001290 endLoc = endLoc.getFileLocWithOffset(-1);
1291 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001292 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001293
1294 // Set lastCurlyLoc
1295 lastCurlyLoc = body->getLocEnd();
1296 }
1297 // Now emit the final closing curly brace...
1298 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1299 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001300 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001301 return 0;
1302}
1303
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001304Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001305 return 0;
1306}
1307
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001308Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001309 return 0;
1310}
1311
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001312// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001313// the throw expression is typically a message expression that's already
1314// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001315Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001316 // Get the start location and compute the semi location.
1317 SourceLocation startLoc = S->getLocStart();
1318 const char *startBuf = SM->getCharacterData(startLoc);
1319
1320 assert((*startBuf == '@') && "bogus @throw location");
1321
1322 std::string buf;
1323 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001324 if (S->getThrowExpr())
1325 buf = "objc_exception_throw(";
1326 else // add an implicit argument
1327 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001328 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001329 const char *semiBuf = strchr(startBuf, ';');
1330 assert((*semiBuf == ';') && "@throw: can't find ';'");
1331 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1332 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001333 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001334 return 0;
1335}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001336
Chris Lattnere64b7772007-10-24 16:57:36 +00001337Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001338 // Create a new string expression.
1339 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001340 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001341 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1342 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001343 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1344 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001345 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001346 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001347
Chris Lattner07506182007-11-30 22:53:43 +00001348 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001349 delete Exp;
1350 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001351}
1352
Steve Naroffb42f8412007-11-05 14:50:49 +00001353Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1354 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1355 // Create a call to sel_registerName("selName").
1356 llvm::SmallVector<Expr*, 8> SelExprs;
1357 QualType argType = Context->getPointerType(Context->CharTy);
1358 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1359 Exp->getSelector().getName().size(),
1360 false, argType, SourceLocation(),
1361 SourceLocation()));
1362 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1363 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001364 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001365 delete Exp;
1366 return SelExp;
1367}
1368
Steve Naroff934f2762007-10-24 22:48:43 +00001369CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1370 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001371 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001372 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001373
1374 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001375 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001376
1377 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001378 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001379 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1380
1381 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001382
Steve Naroff934f2762007-10-24 22:48:43 +00001383 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1384}
1385
Steve Naroffd5255f52007-11-01 13:24:47 +00001386static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1387 const char *&startRef, const char *&endRef) {
1388 while (startBuf < endBuf) {
1389 if (*startBuf == '<')
1390 startRef = startBuf; // mark the start.
1391 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001392 if (startRef && *startRef == '<') {
1393 endRef = startBuf; // mark the end.
1394 return true;
1395 }
1396 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001397 }
1398 startBuf++;
1399 }
1400 return false;
1401}
1402
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001403static void scanToNextArgument(const char *&argRef) {
1404 int angle = 0;
1405 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1406 if (*argRef == '<')
1407 angle++;
1408 else if (*argRef == '>')
1409 angle--;
1410 argRef++;
1411 }
1412 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1413}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001414
Steve Naroffd5255f52007-11-01 13:24:47 +00001415bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001416
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001417 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001418 return true;
1419
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001420 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001421 return true;
1422
Steve Naroffd5255f52007-11-01 13:24:47 +00001423 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001424 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001425 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001426 return true; // we have "Class <Protocol> *".
1427 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001428 return false;
1429}
1430
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001431void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001432 SourceLocation Loc;
1433 QualType Type;
1434 const FunctionTypeProto *proto = 0;
1435 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1436 Loc = VD->getLocation();
1437 Type = VD->getType();
1438 }
1439 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1440 Loc = FD->getLocation();
1441 // Check for ObjC 'id' and class types that have been adorned with protocol
1442 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1443 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1444 assert(funcType && "missing function type");
1445 proto = dyn_cast<FunctionTypeProto>(funcType);
1446 if (!proto)
1447 return;
1448 Type = proto->getResultType();
1449 }
1450 else
1451 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001452
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001453 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001454 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001455
1456 const char *endBuf = SM->getCharacterData(Loc);
1457 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001458 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001459 startBuf--; // scan backward (from the decl location) for return type.
1460 const char *startRef = 0, *endRef = 0;
1461 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1462 // Get the locations of the startRef, endRef.
1463 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1464 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1465 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001466 InsertText(LessLoc, "/*", 2);
1467 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001468 }
1469 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001470 if (!proto)
1471 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001472 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001473 const char *startBuf = SM->getCharacterData(Loc);
1474 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001475 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1476 if (needToScanForQualifiers(proto->getArgType(i))) {
1477 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001478
Steve Naroffd5255f52007-11-01 13:24:47 +00001479 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001480 // scan forward (from the decl location) for argument types.
1481 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001482 const char *startRef = 0, *endRef = 0;
1483 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1484 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001485 SourceLocation LessLoc =
1486 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1487 SourceLocation GreaterLoc =
1488 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001489 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001490 InsertText(LessLoc, "/*", 2);
1491 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001492 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001493 startBuf = ++endBuf;
1494 }
1495 else {
1496 while (*startBuf != ')' && *startBuf != ',')
1497 startBuf++; // scan forward (from the decl location) for argument types.
1498 startBuf++;
1499 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001500 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001501}
1502
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001503// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1504void RewriteTest::SynthSelGetUidFunctionDecl() {
1505 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1506 llvm::SmallVector<QualType, 16> ArgTys;
1507 ArgTys.push_back(Context->getPointerType(
1508 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001509 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001510 &ArgTys[0], ArgTys.size(),
1511 false /*isVariadic*/);
1512 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1513 SelGetUidIdent, getFuncType,
1514 FunctionDecl::Extern, false, 0);
1515}
1516
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001517// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1518void RewriteTest::SynthGetProtocolFunctionDecl() {
1519 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1520 llvm::SmallVector<QualType, 16> ArgTys;
1521 ArgTys.push_back(Context->getPointerType(
1522 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001523 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001524 &ArgTys[0], ArgTys.size(),
1525 false /*isVariadic*/);
1526 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1527 SelGetProtoIdent, getFuncType,
1528 FunctionDecl::Extern, false, 0);
1529}
1530
Steve Naroff09b266e2007-10-30 23:14:51 +00001531void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1532 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001533 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001534 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001535 return;
1536 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001537 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001538}
1539
1540// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1541void RewriteTest::SynthMsgSendFunctionDecl() {
1542 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1543 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001544 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001545 assert(!argT.isNull() && "Can't find 'id' type");
1546 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001547 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001548 assert(!argT.isNull() && "Can't find 'SEL' type");
1549 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001550 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001551 &ArgTys[0], ArgTys.size(),
1552 true /*isVariadic*/);
1553 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1554 msgSendIdent, msgSendType,
1555 FunctionDecl::Extern, false, 0);
1556}
1557
Steve Naroff874e2322007-11-15 10:28:18 +00001558// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1559void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1560 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1561 llvm::SmallVector<QualType, 16> ArgTys;
1562 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1563 &Context->Idents.get("objc_super"), 0);
1564 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1565 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1566 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001567 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001568 assert(!argT.isNull() && "Can't find 'SEL' type");
1569 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001570 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001571 &ArgTys[0], ArgTys.size(),
1572 true /*isVariadic*/);
1573 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1574 msgSendIdent, msgSendType,
1575 FunctionDecl::Extern, false, 0);
1576}
1577
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001578// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1579void RewriteTest::SynthMsgSendStretFunctionDecl() {
1580 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1581 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001582 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001583 assert(!argT.isNull() && "Can't find 'id' type");
1584 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001585 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001586 assert(!argT.isNull() && "Can't find 'SEL' type");
1587 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001588 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001589 &ArgTys[0], ArgTys.size(),
1590 true /*isVariadic*/);
1591 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1592 msgSendIdent, msgSendType,
1593 FunctionDecl::Extern, false, 0);
1594}
1595
1596// SynthMsgSendSuperStretFunctionDecl -
1597// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1598void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1599 IdentifierInfo *msgSendIdent =
1600 &Context->Idents.get("objc_msgSendSuper_stret");
1601 llvm::SmallVector<QualType, 16> ArgTys;
1602 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1603 &Context->Idents.get("objc_super"), 0);
1604 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1605 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1606 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001607 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001608 assert(!argT.isNull() && "Can't find 'SEL' type");
1609 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001610 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001611 &ArgTys[0], ArgTys.size(),
1612 true /*isVariadic*/);
1613 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1614 msgSendIdent, msgSendType,
1615 FunctionDecl::Extern, false, 0);
1616}
1617
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001618// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1619void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1620 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1621 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001622 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001623 assert(!argT.isNull() && "Can't find 'id' type");
1624 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001625 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001626 assert(!argT.isNull() && "Can't find 'SEL' type");
1627 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001628 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001629 &ArgTys[0], ArgTys.size(),
1630 true /*isVariadic*/);
1631 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1632 msgSendIdent, msgSendType,
1633 FunctionDecl::Extern, false, 0);
1634}
1635
Steve Naroff09b266e2007-10-30 23:14:51 +00001636// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1637void RewriteTest::SynthGetClassFunctionDecl() {
1638 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1639 llvm::SmallVector<QualType, 16> ArgTys;
1640 ArgTys.push_back(Context->getPointerType(
1641 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001642 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001643 &ArgTys[0], ArgTys.size(),
1644 false /*isVariadic*/);
1645 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1646 getClassIdent, getClassType,
1647 FunctionDecl::Extern, false, 0);
1648}
1649
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001650// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1651void RewriteTest::SynthGetMetaClassFunctionDecl() {
1652 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1653 llvm::SmallVector<QualType, 16> ArgTys;
1654 ArgTys.push_back(Context->getPointerType(
1655 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001656 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001657 &ArgTys[0], ArgTys.size(),
1658 false /*isVariadic*/);
1659 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1660 getClassIdent, getClassType,
1661 FunctionDecl::Extern, false, 0);
1662}
1663
Steve Naroff96984642007-11-08 14:30:50 +00001664// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1665void RewriteTest::SynthCFStringFunctionDecl() {
1666 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1667 llvm::SmallVector<QualType, 16> ArgTys;
1668 ArgTys.push_back(Context->getPointerType(
1669 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001670 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001671 &ArgTys[0], ArgTys.size(),
1672 false /*isVariadic*/);
1673 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1674 getClassIdent, getClassType,
1675 FunctionDecl::Extern, false, 0);
1676}
1677
Steve Naroffbeaf2992007-11-03 11:27:19 +00001678Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001679#if 1
1680 // This rewrite is specific to GCC, which has builtin support for CFString.
1681 if (!CFStringFunctionDecl)
1682 SynthCFStringFunctionDecl();
1683 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1684 llvm::SmallVector<Expr*, 8> StrExpr;
1685 StrExpr.push_back(Exp->getString());
1686 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1687 &StrExpr[0], StrExpr.size());
1688 // cast to NSConstantString *
1689 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001690 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001691 delete Exp;
1692 return cast;
1693#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001694 assert(ConstantStringClassReference && "Can't find constant string reference");
1695 llvm::SmallVector<Expr*, 4> InitExprs;
1696
1697 // Synthesize "(Class)&_NSConstantStringClassReference"
1698 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1699 ConstantStringClassReference->getType(),
1700 SourceLocation());
1701 QualType expType = Context->getPointerType(ClsRef->getType());
1702 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1703 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001704 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001705 SourceLocation());
1706 InitExprs.push_back(cast); // set the 'isa'.
1707 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1708 unsigned IntSize = static_cast<unsigned>(
1709 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1710 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1711 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1712 Exp->getLocStart());
1713 InitExprs.push_back(len); // set "int numBytes".
1714
1715 // struct NSConstantString
1716 QualType CFConstantStrType = Context->getCFConstantStringType();
1717 // (struct NSConstantString) { <exprs from above> }
1718 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1719 &InitExprs[0], InitExprs.size(),
1720 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001721 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001722 // struct NSConstantString *
1723 expType = Context->getPointerType(StrRep->getType());
1724 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1725 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001726 // cast to NSConstantString *
1727 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001728 ReplaceStmt(Exp, cast);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001729 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001730 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001731#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001732}
1733
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001734ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001735 // check if we are sending a message to 'super'
1736 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001737 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1738 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1739 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1740 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001741 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001742 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001743 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001744 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001745 if (ObjCInterfaceType *IT =
1746 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001747 if (IT->getDecl() ==
1748 CurMethodDecl->getClassInterface()->getSuperClass())
1749 return IT->getDecl();
1750 }
1751 }
1752 }
1753 }
1754 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001755 }
Steve Naroff874e2322007-11-15 10:28:18 +00001756 }
1757 return 0;
1758}
1759
1760// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1761QualType RewriteTest::getSuperStructType() {
1762 if (!SuperStructDecl) {
1763 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1764 &Context->Idents.get("objc_super"), 0);
1765 QualType FieldTypes[2];
1766
1767 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001768 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001769 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001770 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001771 // Create fields
1772 FieldDecl *FieldDecls[2];
1773
1774 for (unsigned i = 0; i < 2; ++i)
1775 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1776
1777 SuperStructDecl->defineBody(FieldDecls, 4);
1778 }
1779 return Context->getTagDeclType(SuperStructDecl);
1780}
1781
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001782Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001783 if (!SelGetUidFunctionDecl)
1784 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001785 if (!MsgSendFunctionDecl)
1786 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001787 if (!MsgSendSuperFunctionDecl)
1788 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001789 if (!MsgSendStretFunctionDecl)
1790 SynthMsgSendStretFunctionDecl();
1791 if (!MsgSendSuperStretFunctionDecl)
1792 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001793 if (!MsgSendFpretFunctionDecl)
1794 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001795 if (!GetClassFunctionDecl)
1796 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001797 if (!GetMetaClassFunctionDecl)
1798 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001799
Steve Naroff874e2322007-11-15 10:28:18 +00001800 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001801 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1802 // May need to use objc_msgSend_stret() as well.
1803 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001804 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001805 QualType resultType = mDecl->getResultType();
1806 if (resultType.getCanonicalType()->isStructureType()
1807 || resultType.getCanonicalType()->isUnionType())
1808 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001809 else if (resultType.getCanonicalType()->isRealFloatingType())
1810 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001811 }
Steve Naroff874e2322007-11-15 10:28:18 +00001812
Steve Naroff934f2762007-10-24 22:48:43 +00001813 // Synthesize a call to objc_msgSend().
1814 llvm::SmallVector<Expr*, 8> MsgExprs;
1815 IdentifierInfo *clsName = Exp->getClassName();
1816
1817 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1818 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001819 if (!strcmp(clsName->getName(), "super")) {
1820 MsgSendFlavor = MsgSendSuperFunctionDecl;
1821 if (MsgSendStretFlavor)
1822 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1823 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1824
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001825 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001826 CurMethodDecl->getClassInterface()->getSuperClass();
1827
1828 llvm::SmallVector<Expr*, 4> InitExprs;
1829
1830 // set the receiver to self, the first argument to all methods.
1831 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001832 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001833 SourceLocation()));
1834 llvm::SmallVector<Expr*, 8> ClsExprs;
1835 QualType argType = Context->getPointerType(Context->CharTy);
1836 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1837 SuperDecl->getIdentifier()->getLength(),
1838 false, argType, SourceLocation(),
1839 SourceLocation()));
1840 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1841 &ClsExprs[0],
1842 ClsExprs.size());
1843 // To turn off a warning, type-cast to 'id'
1844 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001845 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001846 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1847 // struct objc_super
1848 QualType superType = getSuperStructType();
1849 // (struct objc_super) { <exprs from above> }
1850 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1851 &InitExprs[0], InitExprs.size(),
1852 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001853 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001854 superType, ILE, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001855 // struct objc_super *
1856 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1857 Context->getPointerType(SuperRep->getType()),
1858 SourceLocation());
1859 MsgExprs.push_back(Unop);
1860 } else {
1861 llvm::SmallVector<Expr*, 8> ClsExprs;
1862 QualType argType = Context->getPointerType(Context->CharTy);
1863 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1864 clsName->getLength(),
1865 false, argType, SourceLocation(),
1866 SourceLocation()));
1867 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1868 &ClsExprs[0],
1869 ClsExprs.size());
1870 MsgExprs.push_back(Cls);
1871 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001872 } else { // instance message.
1873 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001874
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001875 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001876 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001877 if (MsgSendStretFlavor)
1878 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001879 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1880
1881 llvm::SmallVector<Expr*, 4> InitExprs;
1882
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001883 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001885 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001886
1887 llvm::SmallVector<Expr*, 8> ClsExprs;
1888 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001889 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1890 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001891 false, argType, SourceLocation(),
1892 SourceLocation()));
1893 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001894 &ClsExprs[0],
1895 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001896 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001897 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001898 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001899 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001900 // struct objc_super
1901 QualType superType = getSuperStructType();
1902 // (struct objc_super) { <exprs from above> }
1903 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1904 &InitExprs[0], InitExprs.size(),
1905 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001906 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffe9b12192008-01-14 18:19:28 +00001907 superType, ILE, false);
Steve Naroff874e2322007-11-15 10:28:18 +00001908 // struct objc_super *
1909 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1910 Context->getPointerType(SuperRep->getType()),
1911 SourceLocation());
1912 MsgExprs.push_back(Unop);
1913 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001914 // Remove all type-casts because it may contain objc-style types; e.g.
1915 // Foo<Proto> *.
1916 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1917 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001918 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001919 MsgExprs.push_back(recExpr);
1920 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001921 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001922 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001923 llvm::SmallVector<Expr*, 8> SelExprs;
1924 QualType argType = Context->getPointerType(Context->CharTy);
1925 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1926 Exp->getSelector().getName().size(),
1927 false, argType, SourceLocation(),
1928 SourceLocation()));
1929 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1930 &SelExprs[0], SelExprs.size());
1931 MsgExprs.push_back(SelExp);
1932
1933 // Now push any user supplied arguments.
1934 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001935 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001936 // Make all implicit casts explicit...ICE comes in handy:-)
1937 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1938 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001939 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1940 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001941 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001942 }
1943 // Make id<P...> cast into an 'id' cast.
1944 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001945 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001946 while ((CE = dyn_cast<CastExpr>(userExpr)))
1947 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001948 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001949 userExpr, SourceLocation());
1950 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001951 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001952 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001953 // We've transferred the ownership to MsgExprs. Null out the argument in
1954 // the original expression, since we will delete it below.
1955 Exp->setArg(i, 0);
1956 }
Steve Naroffab972d32007-11-04 22:37:50 +00001957 // Generate the funky cast.
1958 CastExpr *cast;
1959 llvm::SmallVector<QualType, 8> ArgTypes;
1960 QualType returnType;
1961
1962 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001963 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1964 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1965 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001966 ArgTypes.push_back(Context->getObjCIdType());
1967 ArgTypes.push_back(Context->getObjCSelType());
1968 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001969 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001970 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001971 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1972 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001973 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001974 ArgTypes.push_back(t);
1975 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001976 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1977 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001978 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001980 }
1981 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001982 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001983
1984 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001985 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1986 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001987
1988 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1989 // If we don't do this cast, we get the following bizarre warning/note:
1990 // xx.m:13: warning: function called through a non-compatible type
1991 // xx.m:13: note: if this code is reached, the program will abort
1992 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1993 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001994
Steve Naroffab972d32007-11-04 22:37:50 +00001995 // Now do the "normal" pointer to function cast.
1996 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001997 &ArgTypes[0], ArgTypes.size(),
1998 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001999 castType = Context->getPointerType(castType);
2000 cast = new CastExpr(castType, cast, SourceLocation());
2001
2002 // Don't forget the parens to enforce the proper binding.
2003 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2004
2005 const FunctionType *FT = msgSendType->getAsFunctionType();
2006 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2007 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002008 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002009 if (MsgSendStretFlavor) {
2010 // We have the method which returns a struct/union. Must also generate
2011 // call to objc_msgSend_stret and hang both varieties on a conditional
2012 // expression which dictate which one to envoke depending on size of
2013 // method's return type.
2014
2015 // Create a reference to the objc_msgSend_stret() declaration.
2016 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2017 SourceLocation());
2018 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2019 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2020 SourceLocation());
2021 // Now do the "normal" pointer to function cast.
2022 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002023 &ArgTypes[0], ArgTypes.size(),
2024 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002025 castType = Context->getPointerType(castType);
2026 cast = new CastExpr(castType, cast, SourceLocation());
2027
2028 // Don't forget the parens to enforce the proper binding.
2029 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2030
2031 FT = msgSendType->getAsFunctionType();
2032 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2033 FT->getResultType(), SourceLocation());
2034
2035 // Build sizeof(returnType)
2036 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2037 returnType, Context->getSizeType(),
2038 SourceLocation(), SourceLocation());
2039 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2040 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2041 // For X86 it is more complicated and some kind of target specific routine
2042 // is needed to decide what to do.
2043 unsigned IntSize = static_cast<unsigned>(
2044 Context->getTypeSize(Context->IntTy, SourceLocation()));
2045
2046 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2047 Context->IntTy,
2048 SourceLocation());
2049 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2050 BinaryOperator::LE,
2051 Context->IntTy,
2052 SourceLocation());
2053 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2054 ConditionalOperator *CondExpr =
2055 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002056 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002057 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002058 return ReplacingStmt;
2059}
2060
2061Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2062 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002063 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002064 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002065
Chris Lattnere64b7772007-10-24 16:57:36 +00002066 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002067 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002068}
2069
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002070/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2071/// call to objc_getProtocol("proto-name").
2072Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2073 if (!GetProtocolFunctionDecl)
2074 SynthGetProtocolFunctionDecl();
2075 // Create a call to objc_getProtocol("ProtocolName").
2076 llvm::SmallVector<Expr*, 8> ProtoExprs;
2077 QualType argType = Context->getPointerType(Context->CharTy);
2078 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2079 strlen(Exp->getProtocol()->getName()),
2080 false, argType, SourceLocation(),
2081 SourceLocation()));
2082 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2083 &ProtoExprs[0],
2084 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002085 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002086 delete Exp;
2087 return ProtoExp;
2088
2089}
2090
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002091/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002092/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002093void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002094 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002095 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2096 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002097 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002098 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002099 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002100 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002101 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002102 SourceLocation LocStart = CDecl->getLocStart();
2103 SourceLocation LocEnd = CDecl->getLocEnd();
2104
2105 const char *startBuf = SM->getCharacterData(LocStart);
2106 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002107 // If no ivars and no root or if its root, directly or indirectly,
2108 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002109 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002110 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002111 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002112 return;
2113 }
2114
2115 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002116 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002117 Result += "\nstruct ";
2118 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00002119
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002120 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002121 const char *cursor = strchr(startBuf, '{');
2122 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002123 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002124
2125 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002126 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002127 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002128 Result = "\n struct ";
2129 Result += RCDecl->getName();
Steve Narofff69cc5d2008-01-30 19:17:43 +00002130 // Note: We don't name the field decl. This simplifies the "codegen" for
2131 // accessing a superclasses instance variables (and is similar to what gcc
2132 // does internally). The unnamed struct field feature is enabled with
2133 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2134 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002135 Result += ";\n";
2136
2137 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002138 SourceLocation OnePastCurly =
2139 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2140 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002141 }
2142 cursor++; // past '{'
2143
2144 // Now comment out any visibility specifiers.
2145 while (cursor < endBuf) {
2146 if (*cursor == '@') {
2147 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002148 // Skip whitespace.
2149 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2150 /*scan*/;
2151
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002152 // FIXME: presence of @public, etc. inside comment results in
2153 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002154 if (!strncmp(cursor, "public", strlen("public")) ||
2155 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002156 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002157 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002158 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002159 // FIXME: If there are cases where '<' is used in ivar declaration part
2160 // of user code, then scan the ivar list and use needToScanForQualifiers
2161 // for type checking.
2162 else if (*cursor == '<') {
2163 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002164 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002165 cursor = strchr(cursor, '>');
2166 cursor++;
2167 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002168 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002169 }
Steve Narofffea763e82007-11-14 19:25:57 +00002170 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002171 }
Steve Narofffea763e82007-11-14 19:25:57 +00002172 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002173 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002174 } else { // we don't have any instance variables - insert super struct.
2175 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2176 Result += " {\n struct ";
2177 Result += RCDecl->getName();
Steve Narofff69cc5d2008-01-30 19:17:43 +00002178 // Note: We don't name the field decl. This simplifies the "codegen" for
2179 // accessing a superclasses instance variables (and is similar to what gcc
2180 // does internally). The unnamed struct field feature is enabled with
2181 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2182 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002183 Result += ";\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002184 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002185 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002186 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002187 if (!ObjCSynthesizedStructs.insert(CDecl))
2188 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002189}
2190
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002191// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002192/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002193void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002194 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002195 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002196 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002197 const char *ClassName,
2198 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002199 if (MethodBegin == MethodEnd) return;
2200
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002201 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002202 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002203 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002204 SEL _cmd;
2205 char *method_types;
2206 void *_imp;
2207 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002208 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002209 Result += "\nstruct _objc_method {\n";
2210 Result += "\tSEL _cmd;\n";
2211 Result += "\tchar *method_types;\n";
2212 Result += "\tvoid *_imp;\n";
2213 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002214
2215 /* struct _objc_method_list {
2216 struct _objc_method_list *next_method;
2217 int method_count;
2218 struct _objc_method method_list[];
2219 }
2220 */
2221 Result += "\nstruct _objc_method_list {\n";
2222 Result += "\tstruct _objc_method_list *next_method;\n";
2223 Result += "\tint method_count;\n";
2224 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002225 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002226 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002227
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002228 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002229 Result += "\nstatic struct _objc_method_list _OBJC_";
2230 Result += prefix;
2231 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2232 Result += "_METHODS_";
2233 Result += ClassName;
2234 Result += " __attribute__ ((section (\"__OBJC, __";
2235 Result += IsInstanceMethod ? "inst" : "cls";
2236 Result += "_meth\")))= ";
2237 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002238
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002239 Result += "\t,{{(SEL)\"";
2240 Result += (*MethodBegin)->getSelector().getName().c_str();
2241 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002242 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002243 Result += "\", \"";
2244 Result += MethodTypeString;
2245 Result += "\", ";
2246 Result += MethodInternalNames[*MethodBegin];
2247 Result += "}\n";
2248 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2249 Result += "\t ,{(SEL)\"";
2250 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002251 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002252 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002253 Result += "\", \"";
2254 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002255 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002256 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002257 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002258 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002259 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002260}
2261
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002262/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2263void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002264 int NumProtocols,
2265 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002266 const char *ClassName,
2267 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002268 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002269 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002270 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002271 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002272 // Output struct protocol_methods holder of method selector and type.
2273 if (!objc_protocol_methods &&
2274 (PDecl->getNumInstanceMethods() > 0
2275 || PDecl->getNumClassMethods() > 0)) {
2276 /* struct protocol_methods {
2277 SEL _cmd;
2278 char *method_types;
2279 }
2280 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002281 Result += "\nstruct protocol_methods {\n";
2282 Result += "\tSEL _cmd;\n";
2283 Result += "\tchar *method_types;\n";
2284 Result += "};\n";
2285
2286 /* struct _objc_protocol_method_list {
2287 int protocol_method_count;
2288 struct protocol_methods protocols[];
2289 }
2290 */
2291 Result += "\nstruct _objc_protocol_method_list {\n";
2292 Result += "\tint protocol_method_count;\n";
2293 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002294 objc_protocol_methods = true;
2295 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002296
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002297 int NumMethods = PDecl->getNumInstanceMethods();
2298 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002299 Result += "\nstatic struct _objc_protocol_method_list "
2300 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2301 Result += PDecl->getName();
2302 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2303 "{\n\t" + utostr(NumMethods) + "\n";
2304
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002305 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002306 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002307 E = PDecl->instmeth_end(); I != E; ++I) {
2308 if (I == PDecl->instmeth_begin())
2309 Result += "\t ,{{(SEL)\"";
2310 else
2311 Result += "\t ,{(SEL)\"";
2312 Result += (*I)->getSelector().getName().c_str();
2313 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002314 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002315 Result += "\", \"";
2316 Result += MethodTypeString;
2317 Result += "\"}\n";
2318 }
2319 Result += "\t }\n};\n";
2320 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002321
2322 // Output class methods declared in this protocol.
2323 NumMethods = PDecl->getNumClassMethods();
2324 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002325 Result += "\nstatic struct _objc_protocol_method_list "
2326 "_OBJC_PROTOCOL_CLASS_METHODS_";
2327 Result += PDecl->getName();
2328 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2329 "{\n\t";
2330 Result += utostr(NumMethods);
2331 Result += "\n";
2332
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002333 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002334 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002335 E = PDecl->classmeth_end(); I != E; ++I) {
2336 if (I == PDecl->classmeth_begin())
2337 Result += "\t ,{{(SEL)\"";
2338 else
2339 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002340 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002341 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002342 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002343 Result += "\", \"";
2344 Result += MethodTypeString;
2345 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002346 }
2347 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002348 }
2349 // Output:
2350 /* struct _objc_protocol {
2351 // Objective-C 1.0 extensions
2352 struct _objc_protocol_extension *isa;
2353 char *protocol_name;
2354 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002355 struct _objc_protocol_method_list *instance_methods;
2356 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002357 };
2358 */
2359 static bool objc_protocol = false;
2360 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002361 Result += "\nstruct _objc_protocol {\n";
2362 Result += "\tstruct _objc_protocol_extension *isa;\n";
2363 Result += "\tchar *protocol_name;\n";
2364 Result += "\tstruct _objc_protocol **protocol_list;\n";
2365 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2366 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2367 Result += "};\n";
2368
2369 /* struct _objc_protocol_list {
2370 struct _objc_protocol_list *next;
2371 int protocol_count;
2372 struct _objc_protocol *class_protocols[];
2373 }
2374 */
2375 Result += "\nstruct _objc_protocol_list {\n";
2376 Result += "\tstruct _objc_protocol_list *next;\n";
2377 Result += "\tint protocol_count;\n";
2378 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2379 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002380 objc_protocol = true;
2381 }
2382
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002383 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2384 Result += PDecl->getName();
2385 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2386 "{\n\t0, \"";
2387 Result += PDecl->getName();
2388 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002389 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002390 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2391 Result += PDecl->getName();
2392 Result += ", ";
2393 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002394 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002395 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002396 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002397 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2398 Result += PDecl->getName();
2399 Result += "\n";
2400 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002401 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002402 Result += "0\n";
2403 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002404 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002405 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002406 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2407 Result += prefix;
2408 Result += "_PROTOCOLS_";
2409 Result += ClassName;
2410 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2411 "{\n\t0, ";
2412 Result += utostr(NumProtocols);
2413 Result += "\n";
2414
2415 Result += "\t,{&_OBJC_PROTOCOL_";
2416 Result += Protocols[0]->getName();
2417 Result += " \n";
2418
2419 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002420 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002421 Result += "\t ,&_OBJC_PROTOCOL_";
2422 Result += PDecl->getName();
2423 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002424 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002425 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002426 }
2427}
2428
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002429/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002430/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002432 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002433 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002434 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002435 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002436 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2437 CDecl = CDecl->getNextClassCategory())
2438 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2439 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002440
Chris Lattnereb44eee2007-12-23 01:40:15 +00002441 std::string FullCategoryName = ClassDecl->getName();
2442 FullCategoryName += '_';
2443 FullCategoryName += IDecl->getName();
2444
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002445 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002446 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002447 true, "CATEGORY_", FullCategoryName.c_str(),
2448 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002449
2450 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002451 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002452 false, "CATEGORY_", FullCategoryName.c_str(),
2453 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002454
2455 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002456 // Null CDecl is case of a category implementation with no category interface
2457 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002458 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002459 CDecl->getNumReferencedProtocols(),
2460 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002461 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002462
2463 /* struct _objc_category {
2464 char *category_name;
2465 char *class_name;
2466 struct _objc_method_list *instance_methods;
2467 struct _objc_method_list *class_methods;
2468 struct _objc_protocol_list *protocols;
2469 // Objective-C 1.0 extensions
2470 uint32_t size; // sizeof (struct _objc_category)
2471 struct _objc_property_list *instance_properties; // category's own
2472 // @property decl.
2473 };
2474 */
2475
2476 static bool objc_category = false;
2477 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002478 Result += "\nstruct _objc_category {\n";
2479 Result += "\tchar *category_name;\n";
2480 Result += "\tchar *class_name;\n";
2481 Result += "\tstruct _objc_method_list *instance_methods;\n";
2482 Result += "\tstruct _objc_method_list *class_methods;\n";
2483 Result += "\tstruct _objc_protocol_list *protocols;\n";
2484 Result += "\tunsigned int size;\n";
2485 Result += "\tstruct _objc_property_list *instance_properties;\n";
2486 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002487 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002488 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002489 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2490 Result += FullCategoryName;
2491 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2492 Result += IDecl->getName();
2493 Result += "\"\n\t, \"";
2494 Result += ClassDecl->getName();
2495 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002496
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002497 if (IDecl->getNumInstanceMethods() > 0) {
2498 Result += "\t, (struct _objc_method_list *)"
2499 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2500 Result += FullCategoryName;
2501 Result += "\n";
2502 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002503 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002504 Result += "\t, 0\n";
2505 if (IDecl->getNumClassMethods() > 0) {
2506 Result += "\t, (struct _objc_method_list *)"
2507 "&_OBJC_CATEGORY_CLASS_METHODS_";
2508 Result += FullCategoryName;
2509 Result += "\n";
2510 }
2511 else
2512 Result += "\t, 0\n";
2513
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002514 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002515 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2516 Result += FullCategoryName;
2517 Result += "\n";
2518 }
2519 else
2520 Result += "\t, 0\n";
2521 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002522}
2523
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002524/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2525/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002526void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2527 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002528 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002529 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002530 Result += IDecl->getName();
2531 Result += ", ";
2532 Result += ivar->getName();
2533 Result += ")";
2534}
2535
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002536//===----------------------------------------------------------------------===//
2537// Meta Data Emission
2538//===----------------------------------------------------------------------===//
2539
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002540void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002541 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002542 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002543
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002544 // Explictly declared @interface's are already synthesized.
2545 if (CDecl->ImplicitInterfaceDecl()) {
2546 // FIXME: Implementation of a class with no @interface (legacy) doese not
2547 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002548 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002549 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002550
Chris Lattnerbe6df082007-12-12 07:56:42 +00002551 // Build _objc_ivar_list metadata for classes ivars if needed
2552 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2553 ? IDecl->getImplDeclNumIvars()
2554 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002555 if (NumIvars > 0) {
2556 static bool objc_ivar = false;
2557 if (!objc_ivar) {
2558 /* struct _objc_ivar {
2559 char *ivar_name;
2560 char *ivar_type;
2561 int ivar_offset;
2562 };
2563 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002564 Result += "\nstruct _objc_ivar {\n";
2565 Result += "\tchar *ivar_name;\n";
2566 Result += "\tchar *ivar_type;\n";
2567 Result += "\tint ivar_offset;\n";
2568 Result += "};\n";
2569
2570 /* struct _objc_ivar_list {
2571 int ivar_count;
2572 struct _objc_ivar ivar_list[];
2573 };
2574 */
2575 Result += "\nstruct _objc_ivar_list {\n";
2576 Result += "\tint ivar_count;\n";
2577 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002578 objc_ivar = true;
2579 }
2580
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002581 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2582 Result += IDecl->getName();
2583 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2584 "{\n\t";
2585 Result += utostr(NumIvars);
2586 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002587
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002588 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002589 if (IDecl->getImplDeclNumIvars() > 0) {
2590 IVI = IDecl->ivar_begin();
2591 IVE = IDecl->ivar_end();
2592 } else {
2593 IVI = CDecl->ivar_begin();
2594 IVE = CDecl->ivar_end();
2595 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002596 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002597 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002598 Result += "\", \"";
2599 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002600 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2601 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002602 Result += StrEncoding;
2603 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002604 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002605 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002606 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002607 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002608 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002609 Result += "\", \"";
2610 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002611 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2612 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002613 Result += StrEncoding;
2614 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002615 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002616 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002617 }
2618
2619 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002620 }
2621
2622 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002623 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002624 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002625
2626 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002627 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002628 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002629
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002630 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002631 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002632 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002633 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002634
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002635
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002636 // Declaration of class/meta-class metadata
2637 /* struct _objc_class {
2638 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002639 const char *super_class_name;
2640 char *name;
2641 long version;
2642 long info;
2643 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002644 struct _objc_ivar_list *ivars;
2645 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002646 struct objc_cache *cache;
2647 struct objc_protocol_list *protocols;
2648 const char *ivar_layout;
2649 struct _objc_class_ext *ext;
2650 };
2651 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002652 static bool objc_class = false;
2653 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002654 Result += "\nstruct _objc_class {\n";
2655 Result += "\tstruct _objc_class *isa;\n";
2656 Result += "\tconst char *super_class_name;\n";
2657 Result += "\tchar *name;\n";
2658 Result += "\tlong version;\n";
2659 Result += "\tlong info;\n";
2660 Result += "\tlong instance_size;\n";
2661 Result += "\tstruct _objc_ivar_list *ivars;\n";
2662 Result += "\tstruct _objc_method_list *methods;\n";
2663 Result += "\tstruct objc_cache *cache;\n";
2664 Result += "\tstruct _objc_protocol_list *protocols;\n";
2665 Result += "\tconst char *ivar_layout;\n";
2666 Result += "\tstruct _objc_class_ext *ext;\n";
2667 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002668 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002669 }
2670
2671 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002672 ObjCInterfaceDecl *RootClass = 0;
2673 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002674 while (SuperClass) {
2675 RootClass = SuperClass;
2676 SuperClass = SuperClass->getSuperClass();
2677 }
2678 SuperClass = CDecl->getSuperClass();
2679
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002680 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2681 Result += CDecl->getName();
2682 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2683 "{\n\t(struct _objc_class *)\"";
2684 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2685 Result += "\"";
2686
2687 if (SuperClass) {
2688 Result += ", \"";
2689 Result += SuperClass->getName();
2690 Result += "\", \"";
2691 Result += CDecl->getName();
2692 Result += "\"";
2693 }
2694 else {
2695 Result += ", 0, \"";
2696 Result += CDecl->getName();
2697 Result += "\"";
2698 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002699 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002700 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002701 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002702 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002703 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002704 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002705 Result += "\n";
2706 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002707 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002708 Result += ", 0\n";
2709 if (CDecl->getNumIntfRefProtocols() > 0) {
2710 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2711 Result += CDecl->getName();
2712 Result += ",0,0\n";
2713 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002714 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002715 Result += "\t,0,0,0,0\n";
2716 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002717
2718 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002719 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2720 Result += CDecl->getName();
2721 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2722 "{\n\t&_OBJC_METACLASS_";
2723 Result += CDecl->getName();
2724 if (SuperClass) {
2725 Result += ", \"";
2726 Result += SuperClass->getName();
2727 Result += "\", \"";
2728 Result += CDecl->getName();
2729 Result += "\"";
2730 }
2731 else {
2732 Result += ", 0, \"";
2733 Result += CDecl->getName();
2734 Result += "\"";
2735 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002736 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002737 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002738 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002739 Result += ",0";
2740 else {
2741 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002742 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002743 Result += CDecl->getName();
2744 Result += ")";
2745 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002746 if (NumIvars > 0) {
2747 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2748 Result += CDecl->getName();
2749 Result += "\n\t";
2750 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002751 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002752 Result += ",0";
2753 if (IDecl->getNumInstanceMethods() > 0) {
2754 Result += ", &_OBJC_INSTANCE_METHODS_";
2755 Result += CDecl->getName();
2756 Result += ", 0\n\t";
2757 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002758 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002759 Result += ",0,0";
2760 if (CDecl->getNumIntfRefProtocols() > 0) {
2761 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2762 Result += CDecl->getName();
2763 Result += ", 0,0\n";
2764 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002765 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002766 Result += ",0,0,0\n";
2767 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002768}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002769
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002770/// RewriteImplementations - This routine rewrites all method implementations
2771/// and emits meta-data.
2772
2773void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002774 int ClsDefCount = ClassImplementation.size();
2775 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002776
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002777 if (ClsDefCount == 0 && CatDefCount == 0)
2778 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002779 // Rewrite implemented methods
2780 for (int i = 0; i < ClsDefCount; i++)
2781 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002782
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002783 for (int i = 0; i < CatDefCount; i++)
2784 RewriteImplementationDecl(CategoryImplementation[i]);
2785
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002786 // This is needed for use of offsetof
2787 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002788
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002789 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002790 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002791 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002792
2793 // For each implemented category, write out all its meta data.
2794 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002795 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002796
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002797 // Write objc_symtab metadata
2798 /*
2799 struct _objc_symtab
2800 {
2801 long sel_ref_cnt;
2802 SEL *refs;
2803 short cls_def_cnt;
2804 short cat_def_cnt;
2805 void *defs[cls_def_cnt + cat_def_cnt];
2806 };
2807 */
2808
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002809 Result += "\nstruct _objc_symtab {\n";
2810 Result += "\tlong sel_ref_cnt;\n";
2811 Result += "\tSEL *refs;\n";
2812 Result += "\tshort cls_def_cnt;\n";
2813 Result += "\tshort cat_def_cnt;\n";
2814 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2815 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002816
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002817 Result += "static struct _objc_symtab "
2818 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2819 Result += "\t0, 0, " + utostr(ClsDefCount)
2820 + ", " + utostr(CatDefCount) + "\n";
2821 for (int i = 0; i < ClsDefCount; i++) {
2822 Result += "\t,&_OBJC_CLASS_";
2823 Result += ClassImplementation[i]->getName();
2824 Result += "\n";
2825 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002826
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002827 for (int i = 0; i < CatDefCount; i++) {
2828 Result += "\t,&_OBJC_CATEGORY_";
2829 Result += CategoryImplementation[i]->getClassInterface()->getName();
2830 Result += "_";
2831 Result += CategoryImplementation[i]->getName();
2832 Result += "\n";
2833 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002834
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002835 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002836
2837 // Write objc_module metadata
2838
2839 /*
2840 struct _objc_module {
2841 long version;
2842 long size;
2843 const char *name;
2844 struct _objc_symtab *symtab;
2845 }
2846 */
2847
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002848 Result += "\nstruct _objc_module {\n";
2849 Result += "\tlong version;\n";
2850 Result += "\tlong size;\n";
2851 Result += "\tconst char *name;\n";
2852 Result += "\tstruct _objc_symtab *symtab;\n";
2853 Result += "};\n\n";
2854 Result += "static struct _objc_module "
2855 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002856 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2857 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002858 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002859
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002860}
Chris Lattner311ff022007-10-16 22:36:42 +00002861