blob: 5dc36923fcb4c266edb6d097db2a136ecb37e828 [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//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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 Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Steve Naroff874e2322007-11-15 10:28:18 +000023#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000024using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000025using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000026
Chris Lattner77cd2a02007-10-11 00:43:27 +000027namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000028 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000029 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000030 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000032 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000033 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000034 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
35 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000037 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000038 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000039
40 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000041 FunctionDecl *MsgSendSuperFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000042 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000043 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000044 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000045
Steve Naroffbeaf2992007-11-03 11:27:19 +000046 // ObjC string constant support.
47 FileVarDecl *ConstantStringClassReference;
48 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000049
Steve Naroff874e2322007-11-15 10:28:18 +000050 // Needed for super.
51 ObjcMethodDecl *CurMethodDecl;
52 RecordDecl *SuperStructDecl;
53
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000054 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000055 public:
Chris Lattner01c57482007-10-17 22:35:30 +000056 void Initialize(ASTContext &context, unsigned mainFileID) {
57 Context = &context;
58 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000059 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000060 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000061 MsgSendSuperFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000062 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000063 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000064 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000065 ConstantStringClassReference = 0;
66 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000067 CurMethodDecl = 0;
68 SuperStructDecl = 0;
69
Chris Lattner01c57482007-10-17 22:35:30 +000070 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000071 // declaring objc_selector outside the parameter list removes a silly
72 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000073 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000074 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000075 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +000076 "struct objc_super { struct objc_object *receiver; struct objc_class *super; };\n"
77 "extern struct objc_object *objc_msgSendSuper"
78 "(struct objc_super *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +000079 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000080 "(const char *);\n"
81 "extern void objc_exception_throw(struct objc_object *);\n"
82 "extern void objc_exception_try_enter(void *);\n"
83 "extern void objc_exception_try_exit(void *);\n"
84 "extern struct objc_object *objc_exception_extract(void *);\n"
85 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +000086 "(struct objc_class *, struct objc_object *, ...);\n"
87 "#include <Objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +000088
Steve Naroffab972d32007-11-04 22:37:50 +000089 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
90 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000091 }
Chris Lattner8a12c272007-10-11 18:38:32 +000092
Chris Lattnerf04da132007-10-24 17:06:59 +000093 // Top Level Driver code.
94 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000095 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000096 ~RewriteTest();
97
98 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000099 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000100 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000101 void RewriteTabs();
102 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000103 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000104 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000105 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000106 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000107 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000108 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000109 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000110 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000111 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +0000112 void RewriteObjcQualifiedInterfaceTypes(
113 const FunctionTypeProto *proto, FunctionDecl *FD);
114 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000115 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
116 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000117
Chris Lattnerf04da132007-10-24 17:06:59 +0000118 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000119 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000120 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000121 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000122 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000123 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000124 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000125 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
126 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
127 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000128 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000129 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
130 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000131 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000132 void SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000133 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000134 void SynthCFStringFunctionDecl();
135
Chris Lattnerf04da132007-10-24 17:06:59 +0000136 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000137 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
138 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000139
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000140 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
141 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000142
Steve Naroff0416fb92007-11-11 17:19:15 +0000143 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000144 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000145 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000146 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000147 const char *ClassName,
148 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000149
150 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
151 int NumProtocols,
152 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000153 const char *ClassName,
154 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000155 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
156 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000157 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
158 ObjcIvarDecl *ivar,
159 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000160 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000161 };
162}
163
Chris Lattner8a12c272007-10-11 18:38:32 +0000164ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000165
Chris Lattnerf04da132007-10-24 17:06:59 +0000166//===----------------------------------------------------------------------===//
167// Top Level Driver Code
168//===----------------------------------------------------------------------===//
169
Chris Lattner8a12c272007-10-11 18:38:32 +0000170void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000171 // Two cases: either the decl could be in the main file, or it could be in a
172 // #included file. If the former, rewrite it now. If the later, check to see
173 // if we rewrote the #include/#import.
174 SourceLocation Loc = D->getLocation();
175 Loc = SM->getLogicalLoc(Loc);
176
177 // If this is for a builtin, ignore it.
178 if (Loc.isInvalid()) return;
179
Steve Naroffebf2b562007-10-23 23:50:29 +0000180 // Look for built-in declarations that we need to refer during the rewrite.
181 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000182 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000183 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
184 // declared in <Foundation/NSString.h>
185 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
186 ConstantStringClassReference = FVD;
187 return;
188 }
Steve Naroffbef11852007-10-26 20:53:56 +0000189 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
190 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000191 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
192 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000193 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
194 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000195 } else if (ObjcForwardProtocolDecl *FP =
196 dyn_cast<ObjcForwardProtocolDecl>(D)){
197 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000198 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000199 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000200 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
201 return HandleDeclInMainFile(D);
202
Chris Lattnerf04da132007-10-24 17:06:59 +0000203 // Otherwise, see if there is a #import in the main file that should be
204 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000205 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000206}
207
Chris Lattnerf04da132007-10-24 17:06:59 +0000208/// HandleDeclInMainFile - This is called for each top-level decl defined in the
209/// main file of the input.
210void RewriteTest::HandleDeclInMainFile(Decl *D) {
211 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
212 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000213 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000214
215 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000216 if (Stmt *Body = MD->getBody()) {
217 //Body->dump();
218 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000219 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000220 CurMethodDecl = 0;
221 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000222 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000223 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
224 ClassImplementation.push_back(CI);
225 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
226 CategoryImplementation.push_back(CI);
227 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
228 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000229 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
230 if (VD->getInit())
231 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
232 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000233 // Nothing yet.
234}
235
236RewriteTest::~RewriteTest() {
237 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000238
239 // Rewrite tabs if we care.
240 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000241
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000242 // Rewrite Objective-c meta data*
243 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000244 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000245
Chris Lattnerf04da132007-10-24 17:06:59 +0000246 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
247 // we are done.
248 if (const RewriteBuffer *RewriteBuf =
249 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000250 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000251 std::string S(RewriteBuf->begin(), RewriteBuf->end());
252 printf("%s\n", S.c_str());
253 } else {
254 printf("No changes\n");
255 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000256 // Emit metadata.
257 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000258}
259
Chris Lattnerf04da132007-10-24 17:06:59 +0000260//===----------------------------------------------------------------------===//
261// Syntactic (non-AST) Rewriting Code
262//===----------------------------------------------------------------------===//
263
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000264void RewriteTest::RewriteInclude(SourceLocation Loc) {
265 // Rip up the #include stack to the main file.
266 SourceLocation IncLoc = Loc, NextLoc = Loc;
267 do {
268 IncLoc = Loc;
269 Loc = SM->getLogicalLoc(NextLoc);
270 NextLoc = SM->getIncludeLoc(Loc);
271 } while (!NextLoc.isInvalid());
272
273 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
274 // IncLoc indicates the header that was included if it is useful.
275 IncLoc = SM->getLogicalLoc(IncLoc);
276 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
277 Loc == LastIncLoc)
278 return;
279 LastIncLoc = Loc;
280
281 unsigned IncCol = SM->getColumnNumber(Loc);
282 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
283
284 // Replace the #import with #include.
285 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
286}
287
Chris Lattnerf04da132007-10-24 17:06:59 +0000288void RewriteTest::RewriteTabs() {
289 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
290 const char *MainBufStart = MainBuf.first;
291 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000292
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 // Loop over the whole file, looking for tabs.
294 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
295 if (*BufPtr != '\t')
296 continue;
297
298 // Okay, we found a tab. This tab will turn into at least one character,
299 // but it depends on which 'virtual column' it is in. Compute that now.
300 unsigned VCol = 0;
301 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
302 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
303 ++VCol;
304
305 // Okay, now that we know the virtual column, we know how many spaces to
306 // insert. We assume 8-character tab-stops.
307 unsigned Spaces = 8-(VCol & 7);
308
309 // Get the location of the tab.
310 SourceLocation TabLoc =
311 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
312
313 // Rewrite the single tab character into a sequence of spaces.
314 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
315 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000316}
317
318
Chris Lattnerf04da132007-10-24 17:06:59 +0000319void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
320 int numDecls = ClassDecl->getNumForwardDecls();
321 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
322
323 // Get the start location and compute the semi location.
324 SourceLocation startLoc = ClassDecl->getLocation();
325 const char *startBuf = SM->getCharacterData(startLoc);
326 const char *semiPtr = strchr(startBuf, ';');
327
328 // Translate to typedef's that forward reference structs with the same name
329 // as the class. As a convenience, we include the original declaration
330 // as a comment.
331 std::string typedefString;
332 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000333 typedefString.append(startBuf, semiPtr-startBuf+1);
334 typedefString += "\n";
335 for (int i = 0; i < numDecls; i++) {
336 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000337 typedefString += "#ifndef _REWRITER_typedef_";
338 typedefString += ForwardDecl->getName();
339 typedefString += "\n";
340 typedefString += "#define _REWRITER_typedef_";
341 typedefString += ForwardDecl->getName();
342 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000343 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000344 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000345 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000346 }
347
348 // Replace the @class with typedefs corresponding to the classes.
349 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
350 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000351}
352
Steve Naroff71c0a952007-11-13 23:01:27 +0000353void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000354 for (int i = 0; i < nMethods; i++) {
355 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000356 SourceLocation LocStart = Method->getLocStart();
357 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000358
Steve Naroff1d098f62007-11-14 14:34:23 +0000359 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
360 Rewrite.InsertText(LocStart, "/* ", 3);
361 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
362 } else {
363 Rewrite.InsertText(LocStart, "// ", 3);
364 }
Steve Naroff423cb562007-10-30 13:30:57 +0000365 }
366}
367
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000368void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
369{
370 for (int i = 0; i < nProperties; i++) {
371 ObjcPropertyDecl *Property = Properties[i];
372 SourceLocation Loc = Property->getLocation();
373
374 Rewrite.ReplaceText(Loc, 0, "// ", 3);
375
376 // FIXME: handle properties that are declared across multiple lines.
377 }
378}
379
Steve Naroff423cb562007-10-30 13:30:57 +0000380void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
381 SourceLocation LocStart = CatDecl->getLocStart();
382
383 // FIXME: handle category headers that are declared across multiple lines.
384 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
385
Steve Naroff71c0a952007-11-13 23:01:27 +0000386 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
387 CatDecl->getInstanceMethods());
388 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
389 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000390 // Lastly, comment out the @end.
391 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
392}
393
Steve Naroff752d6ef2007-10-30 16:42:30 +0000394void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000395 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000396
Steve Naroff752d6ef2007-10-30 16:42:30 +0000397 SourceLocation LocStart = PDecl->getLocStart();
398
399 // FIXME: handle protocol headers that are declared across multiple lines.
400 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
401
Steve Naroff71c0a952007-11-13 23:01:27 +0000402 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
403 PDecl->getInstanceMethods());
404 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
405 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000406 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000407 SourceLocation LocEnd = PDecl->getAtEndLoc();
408 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000409
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000410 // Must comment out @optional/@required
411 const char *startBuf = SM->getCharacterData(LocStart);
412 const char *endBuf = SM->getCharacterData(LocEnd);
413 for (const char *p = startBuf; p < endBuf; p++) {
414 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
415 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000416 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000417 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
418 CommentedOptional.c_str(), CommentedOptional.size());
419
420 }
421 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
422 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000423 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000424 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
425 CommentedRequired.c_str(), CommentedRequired.size());
426
427 }
428 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000429}
430
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000431void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
432 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000433 if (LocStart.isInvalid())
434 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000435 // FIXME: handle forward protocol that are declared across multiple lines.
436 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
437}
438
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000439void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
440 std::string &ResultStr) {
441 ResultStr += "\nstatic ";
442 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000443 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000444
445 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000446 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000447
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000448 if (OMD->isInstance())
449 NameStr += "_I_";
450 else
451 NameStr += "_C_";
452
453 NameStr += OMD->getClassInterface()->getName();
454 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000455
456 NamedDecl *MethodContext = OMD->getMethodContext();
457 if (ObjcCategoryImplDecl *CID =
458 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000459 NameStr += CID->getName();
460 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000461 }
462 // Append selector names, replacing ':' with '_'
463 const char *selName = OMD->getSelector().getName().c_str();
464 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000465 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000466 else {
467 std::string selString = OMD->getSelector().getName();
468 int len = selString.size();
469 for (int i = 0; i < len; i++)
470 if (selString[i] == ':')
471 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000472 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000473 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000474 // Remember this name for metadata emission
475 MethodInternalNames[OMD] = NameStr;
476 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000477
478 // Rewrite arguments
479 ResultStr += "(";
480
481 // invisible arguments
482 if (OMD->isInstance()) {
483 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
484 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000485 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
486 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000487 ResultStr += selfTy.getAsString();
488 }
489 else
490 ResultStr += Context->getObjcIdType().getAsString();
491
492 ResultStr += " self, ";
493 ResultStr += Context->getObjcSelType().getAsString();
494 ResultStr += " _cmd";
495
496 // Method arguments.
497 for (int i = 0; i < OMD->getNumParams(); i++) {
498 ParmVarDecl *PDecl = OMD->getParamDecl(i);
499 ResultStr += ", ";
500 ResultStr += PDecl->getType().getAsString();
501 ResultStr += " ";
502 ResultStr += PDecl->getName();
503 }
504 ResultStr += ")";
505
506}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000507void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
508 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
509 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000510
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000511 if (IMD)
512 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
513 else
514 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000515
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000516 int numMethods = IMD ? IMD->getNumInstanceMethods()
517 : CID->getNumInstanceMethods();
518
519 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000520 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000521 ObjcMethodDecl *OMD;
522 if (IMD)
523 OMD = IMD->getInstanceMethods()[i];
524 else
525 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000526 RewriteObjcMethodDecl(OMD, ResultStr);
527 SourceLocation LocStart = OMD->getLocStart();
528 SourceLocation LocEnd = OMD->getBody()->getLocStart();
529
530 const char *startBuf = SM->getCharacterData(LocStart);
531 const char *endBuf = SM->getCharacterData(LocEnd);
532 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
533 ResultStr.c_str(), ResultStr.size());
534 }
535
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000536 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
537 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000538 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000539 ObjcMethodDecl *OMD;
540 if (IMD)
541 OMD = IMD->getClassMethods()[i];
542 else
543 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000544 RewriteObjcMethodDecl(OMD, ResultStr);
545 SourceLocation LocStart = OMD->getLocStart();
546 SourceLocation LocEnd = OMD->getBody()->getLocStart();
547
548 const char *startBuf = SM->getCharacterData(LocStart);
549 const char *endBuf = SM->getCharacterData(LocEnd);
550 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
551 ResultStr.c_str(), ResultStr.size());
552 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000553 if (IMD)
554 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
555 else
556 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000557}
558
Steve Naroffbef11852007-10-26 20:53:56 +0000559void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000560 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000561 if (!ObjcForwardDecls.count(ClassDecl)) {
562 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000563 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000564 ResultStr += ClassDecl->getName();
565 ResultStr += "\n";
566 ResultStr += "#define _REWRITER_typedef_";
567 ResultStr += ClassDecl->getName();
568 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000569 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000570 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000571 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000572
573 // Mark this typedef as having been generated.
574 ObjcForwardDecls.insert(ClassDecl);
575 }
Steve Narofff908a872007-10-30 02:23:23 +0000576 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
577
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000578 RewriteProperties(ClassDecl->getNumPropertyDecl(),
579 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000580 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
581 ClassDecl->getInstanceMethods());
582 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
583 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000584
Steve Naroff2feac5e2007-10-30 03:43:13 +0000585 // Lastly, comment out the @end.
586 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000587}
588
Steve Naroff7e3411b2007-11-15 02:58:25 +0000589Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
590 ObjcIvarDecl *D = IV->getDecl();
591 if (IV->isFreeIvar()) {
592 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
593 IV->getLocation());
594 Rewrite.ReplaceStmt(IV, Replacement);
595 delete IV;
596 return Replacement;
597 }
598 else
599 return IV;
600}
601
Chris Lattnerf04da132007-10-24 17:06:59 +0000602//===----------------------------------------------------------------------===//
603// Function Body / Expression rewriting
604//===----------------------------------------------------------------------===//
605
Steve Narofff3473a72007-11-09 15:20:18 +0000606Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000607 // Otherwise, just rewrite all children.
608 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
609 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000610 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000611 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000612 if (newStmt)
613 *CI = newStmt;
614 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000615
616 // Handle specific things.
617 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
618 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000619
620 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
621 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000622
623 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
624 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000625
626 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
627 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000628
Steve Naroff934f2762007-10-24 22:48:43 +0000629 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
630 // Before we rewrite it, put the original message expression in a comment.
631 SourceLocation startLoc = MessExpr->getLocStart();
632 SourceLocation endLoc = MessExpr->getLocEnd();
633
634 const char *startBuf = SM->getCharacterData(startLoc);
635 const char *endBuf = SM->getCharacterData(endLoc);
636
637 std::string messString;
638 messString += "// ";
639 messString.append(startBuf, endBuf-startBuf+1);
640 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000641
Steve Naroff934f2762007-10-24 22:48:43 +0000642 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
643 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
644 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000645 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000646 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000647 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000648
649 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
650 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000651
652 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
653 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000654#if 0
655 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
656 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
657 // Get the new text.
658 std::ostringstream Buf;
659 Replacement->printPretty(Buf);
660 const std::string &Str = Buf.str();
661
662 printf("CAST = %s\n", &Str[0]);
663 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
664 delete S;
665 return Replacement;
666 }
667#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000668 // Return this stmt unmodified.
669 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000670}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000671
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000672Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000673 // Get the start location and compute the semi location.
674 SourceLocation startLoc = S->getLocStart();
675 const char *startBuf = SM->getCharacterData(startLoc);
676
677 assert((*startBuf == '@') && "bogus @try location");
678
679 std::string buf;
680 // declare a new scope with two variables, _stack and _rethrow.
681 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
682 buf += "int buf[18/*32-bit i386*/];\n";
683 buf += "char *pointers[4];} _stack;\n";
684 buf += "id volatile _rethrow = 0;\n";
685 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000686 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000687
688 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
689
690 startLoc = S->getTryBody()->getLocEnd();
691 startBuf = SM->getCharacterData(startLoc);
692
693 assert((*startBuf == '}') && "bogus @try block");
694
695 SourceLocation lastCurlyLoc = startLoc;
696
697 startLoc = startLoc.getFileLocWithOffset(1);
698 buf = " /* @catch begin */ else {\n";
699 buf += " id _caught = objc_exception_extract(&_stack);\n";
700 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000701 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000702 buf += " _rethrow = objc_exception_extract(&_stack);\n";
703 buf += " else { /* @catch continue */";
704
Chris Lattner28d1fe82007-11-08 04:41:51 +0000705 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000706
707 bool sawIdTypedCatch = false;
708 Stmt *lastCatchBody = 0;
709 ObjcAtCatchStmt *catchList = S->getCatchStmts();
710 while (catchList) {
711 Stmt *catchStmt = catchList->getCatchParamStmt();
712
713 if (catchList == S->getCatchStmts())
714 buf = "if ("; // we are generating code for the first catch clause
715 else
716 buf = "else if (";
717 startLoc = catchList->getLocStart();
718 startBuf = SM->getCharacterData(startLoc);
719
720 assert((*startBuf == '@') && "bogus @catch location");
721
722 const char *lParenLoc = strchr(startBuf, '(');
723
724 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
725 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
726 if (t == Context->getObjcIdType()) {
727 buf += "1) { ";
728 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
729 buf.c_str(), buf.size());
730 sawIdTypedCatch = true;
731 } else if (const PointerType *pType = t->getAsPointerType()) {
732 ObjcInterfaceType *cls; // Should be a pointer to a class.
733
734 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
735 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000736 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000737 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000738 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000739 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
740 buf.c_str(), buf.size());
741 }
742 }
743 // Now rewrite the body...
744 lastCatchBody = catchList->getCatchBody();
745 SourceLocation rParenLoc = catchList->getRParenLoc();
746 SourceLocation bodyLoc = lastCatchBody->getLocStart();
747 const char *bodyBuf = SM->getCharacterData(bodyLoc);
748 const char *rParenBuf = SM->getCharacterData(rParenLoc);
749 assert((*rParenBuf == ')') && "bogus @catch paren location");
750 assert((*bodyBuf == '{') && "bogus @catch body location");
751
752 buf = " = _caught;";
753 // Here we replace ") {" with "= _caught;" (which initializes and
754 // declares the @catch parameter).
755 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
756 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000757 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000758 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000759 }
Steve Naroff75730982007-11-07 04:08:17 +0000760 catchList = catchList->getNextCatchStmt();
761 }
762 // Complete the catch list...
763 if (lastCatchBody) {
764 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
765 const char *bodyBuf = SM->getCharacterData(bodyLoc);
766 assert((*bodyBuf == '}') && "bogus @catch body location");
767 bodyLoc = bodyLoc.getFileLocWithOffset(1);
768 buf = " } } /* @catch end */\n";
769
Chris Lattner28d1fe82007-11-08 04:41:51 +0000770 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000771
772 // Set lastCurlyLoc
773 lastCurlyLoc = lastCatchBody->getLocEnd();
774 }
775 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
776 startLoc = finalStmt->getLocStart();
777 startBuf = SM->getCharacterData(startLoc);
778 assert((*startBuf == '@') && "bogus @finally start");
779
780 buf = "/* @finally */";
781 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
782
783 Stmt *body = finalStmt->getFinallyBody();
784 SourceLocation startLoc = body->getLocStart();
785 SourceLocation endLoc = body->getLocEnd();
786 const char *startBuf = SM->getCharacterData(startLoc);
787 const char *endBuf = SM->getCharacterData(endLoc);
788 assert((*startBuf == '{') && "bogus @finally body location");
789 assert((*endBuf == '}') && "bogus @finally body location");
790
791 startLoc = startLoc.getFileLocWithOffset(1);
792 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000793 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000794 endLoc = endLoc.getFileLocWithOffset(-1);
795 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000796 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000797
798 // Set lastCurlyLoc
799 lastCurlyLoc = body->getLocEnd();
800 }
801 // Now emit the final closing curly brace...
802 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
803 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000804 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000805 return 0;
806}
807
808Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
809 return 0;
810}
811
812Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
813 return 0;
814}
815
Steve Naroff2bd03922007-11-07 15:32:26 +0000816// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
817// the throw expression is typically a message expression that's already
818// been rewritten! (which implies the SourceLocation's are invalid).
819Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
820 // Get the start location and compute the semi location.
821 SourceLocation startLoc = S->getLocStart();
822 const char *startBuf = SM->getCharacterData(startLoc);
823
824 assert((*startBuf == '@') && "bogus @throw location");
825
826 std::string buf;
827 /* void objc_exception_throw(id) __attribute__((noreturn)); */
828 buf = "objc_exception_throw(";
829 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
830 const char *semiBuf = strchr(startBuf, ';');
831 assert((*semiBuf == ';') && "@throw: can't find ';'");
832 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
833 buf = ");";
834 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
835 return 0;
836}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000837
Chris Lattnere64b7772007-10-24 16:57:36 +0000838Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000839 // Create a new string expression.
840 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000841 std::string StrEncoding;
842 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
843 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
844 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000845 SourceLocation(), SourceLocation());
846 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000847 delete Exp;
848 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000849}
850
Steve Naroffb42f8412007-11-05 14:50:49 +0000851Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
852 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
853 // Create a call to sel_registerName("selName").
854 llvm::SmallVector<Expr*, 8> SelExprs;
855 QualType argType = Context->getPointerType(Context->CharTy);
856 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
857 Exp->getSelector().getName().size(),
858 false, argType, SourceLocation(),
859 SourceLocation()));
860 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
861 &SelExprs[0], SelExprs.size());
862 Rewrite.ReplaceStmt(Exp, SelExp);
863 delete Exp;
864 return SelExp;
865}
866
Steve Naroff934f2762007-10-24 22:48:43 +0000867CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
868 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000869 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000870 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000871
872 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000873 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000874
875 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000876 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000877 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
878
879 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000880
Steve Naroff934f2762007-10-24 22:48:43 +0000881 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
882}
883
Steve Naroffd5255f52007-11-01 13:24:47 +0000884static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
885 const char *&startRef, const char *&endRef) {
886 while (startBuf < endBuf) {
887 if (*startBuf == '<')
888 startRef = startBuf; // mark the start.
889 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000890 if (startRef && *startRef == '<') {
891 endRef = startBuf; // mark the end.
892 return true;
893 }
894 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000895 }
896 startBuf++;
897 }
898 return false;
899}
900
901bool RewriteTest::needToScanForQualifiers(QualType T) {
902 // FIXME: we don't currently represent "id <Protocol>" in the type system.
903 if (T == Context->getObjcIdType())
904 return true;
905
906 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000907 Type *pointeeType = pType->getPointeeType().getTypePtr();
908 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
909 return true; // we have "Class <Protocol> *".
910 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000911 return false;
912}
913
914void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
915 const FunctionTypeProto *proto, FunctionDecl *FD) {
916
917 if (needToScanForQualifiers(proto->getResultType())) {
918 // Since types are unique, we need to scan the buffer.
919 SourceLocation Loc = FD->getLocation();
920
921 const char *endBuf = SM->getCharacterData(Loc);
922 const char *startBuf = endBuf;
923 while (*startBuf != ';')
924 startBuf--; // scan backward (from the decl location) for return type.
925 const char *startRef = 0, *endRef = 0;
926 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
927 // Get the locations of the startRef, endRef.
928 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
929 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
930 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000931 Rewrite.InsertText(LessLoc, "/*", 2);
932 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000933 }
934 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000935 // Now check arguments.
936 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
937 if (needToScanForQualifiers(proto->getArgType(i))) {
938 // Since types are unique, we need to scan the buffer.
939 SourceLocation Loc = FD->getLocation();
940
941 const char *startBuf = SM->getCharacterData(Loc);
942 const char *endBuf = startBuf;
943 while (*endBuf != ';')
944 endBuf++; // scan forward (from the decl location) for argument types.
945 const char *startRef = 0, *endRef = 0;
946 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
947 // Get the locations of the startRef, endRef.
948 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
949 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
950 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000951 Rewrite.InsertText(LessLoc, "/*", 2);
952 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000953 }
954 }
955 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000956}
957
Steve Naroff09b266e2007-10-30 23:14:51 +0000958void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
959 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000960 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000961 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000962 return;
963 }
964 // Check for ObjC 'id' and class types that have been adorned with protocol
965 // information (id<p>, C<p>*). The protocol references need to be rewritten!
966 const FunctionType *funcType = FD->getType()->getAsFunctionType();
967 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000968 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
969 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000970}
971
972// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
973void RewriteTest::SynthMsgSendFunctionDecl() {
974 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
975 llvm::SmallVector<QualType, 16> ArgTys;
976 QualType argT = Context->getObjcIdType();
977 assert(!argT.isNull() && "Can't find 'id' type");
978 ArgTys.push_back(argT);
979 argT = Context->getObjcSelType();
980 assert(!argT.isNull() && "Can't find 'SEL' type");
981 ArgTys.push_back(argT);
982 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
983 &ArgTys[0], ArgTys.size(),
984 true /*isVariadic*/);
985 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
986 msgSendIdent, msgSendType,
987 FunctionDecl::Extern, false, 0);
988}
989
Steve Naroff874e2322007-11-15 10:28:18 +0000990// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
991void RewriteTest::SynthMsgSendSuperFunctionDecl() {
992 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
993 llvm::SmallVector<QualType, 16> ArgTys;
994 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
995 &Context->Idents.get("objc_super"), 0);
996 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
997 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
998 ArgTys.push_back(argT);
999 argT = Context->getObjcSelType();
1000 assert(!argT.isNull() && "Can't find 'SEL' type");
1001 ArgTys.push_back(argT);
1002 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1003 &ArgTys[0], ArgTys.size(),
1004 true /*isVariadic*/);
1005 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1006 msgSendIdent, msgSendType,
1007 FunctionDecl::Extern, false, 0);
1008}
1009
Steve Naroff09b266e2007-10-30 23:14:51 +00001010// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1011void RewriteTest::SynthGetClassFunctionDecl() {
1012 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1013 llvm::SmallVector<QualType, 16> ArgTys;
1014 ArgTys.push_back(Context->getPointerType(
1015 Context->CharTy.getQualifiedType(QualType::Const)));
1016 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1017 &ArgTys[0], ArgTys.size(),
1018 false /*isVariadic*/);
1019 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1020 getClassIdent, getClassType,
1021 FunctionDecl::Extern, false, 0);
1022}
1023
Steve Naroff96984642007-11-08 14:30:50 +00001024// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1025void RewriteTest::SynthCFStringFunctionDecl() {
1026 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1027 llvm::SmallVector<QualType, 16> ArgTys;
1028 ArgTys.push_back(Context->getPointerType(
1029 Context->CharTy.getQualifiedType(QualType::Const)));
1030 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1031 &ArgTys[0], ArgTys.size(),
1032 false /*isVariadic*/);
1033 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1034 getClassIdent, getClassType,
1035 FunctionDecl::Extern, false, 0);
1036}
1037
Steve Naroffbeaf2992007-11-03 11:27:19 +00001038Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001039#if 1
1040 // This rewrite is specific to GCC, which has builtin support for CFString.
1041 if (!CFStringFunctionDecl)
1042 SynthCFStringFunctionDecl();
1043 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1044 llvm::SmallVector<Expr*, 8> StrExpr;
1045 StrExpr.push_back(Exp->getString());
1046 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1047 &StrExpr[0], StrExpr.size());
1048 // cast to NSConstantString *
1049 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1050 Rewrite.ReplaceStmt(Exp, cast);
1051 delete Exp;
1052 return cast;
1053#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001054 assert(ConstantStringClassReference && "Can't find constant string reference");
1055 llvm::SmallVector<Expr*, 4> InitExprs;
1056
1057 // Synthesize "(Class)&_NSConstantStringClassReference"
1058 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1059 ConstantStringClassReference->getType(),
1060 SourceLocation());
1061 QualType expType = Context->getPointerType(ClsRef->getType());
1062 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1063 expType, SourceLocation());
1064 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1065 SourceLocation());
1066 InitExprs.push_back(cast); // set the 'isa'.
1067 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1068 unsigned IntSize = static_cast<unsigned>(
1069 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1070 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1071 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1072 Exp->getLocStart());
1073 InitExprs.push_back(len); // set "int numBytes".
1074
1075 // struct NSConstantString
1076 QualType CFConstantStrType = Context->getCFConstantStringType();
1077 // (struct NSConstantString) { <exprs from above> }
1078 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1079 &InitExprs[0], InitExprs.size(),
1080 SourceLocation());
1081 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1082 // struct NSConstantString *
1083 expType = Context->getPointerType(StrRep->getType());
1084 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1085 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001086 // cast to NSConstantString *
1087 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001088 Rewrite.ReplaceStmt(Exp, cast);
1089 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001090 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001091#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001092}
1093
Steve Naroff874e2322007-11-15 10:28:18 +00001094ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1095 if (CurMethodDecl) { // check if we are sending a message to 'super'
1096 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1097 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1098 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1099 if (!strcmp(PVD->getName(), "self")) {
1100 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1101 if (ObjcInterfaceType *IT =
1102 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1103 if (IT->getDecl() ==
1104 CurMethodDecl->getClassInterface()->getSuperClass())
1105 return IT->getDecl();
1106 }
1107 }
1108 }
1109 }
1110 }
1111 }
1112 }
1113 return 0;
1114}
1115
1116// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1117QualType RewriteTest::getSuperStructType() {
1118 if (!SuperStructDecl) {
1119 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1120 &Context->Idents.get("objc_super"), 0);
1121 QualType FieldTypes[2];
1122
1123 // struct objc_object *receiver;
1124 FieldTypes[0] = Context->getObjcIdType();
1125 // struct objc_class *super;
1126 FieldTypes[1] = Context->getObjcClassType();
1127 // Create fields
1128 FieldDecl *FieldDecls[2];
1129
1130 for (unsigned i = 0; i < 2; ++i)
1131 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1132
1133 SuperStructDecl->defineBody(FieldDecls, 4);
1134 }
1135 return Context->getTagDeclType(SuperStructDecl);
1136}
1137
Steve Naroff934f2762007-10-24 22:48:43 +00001138Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001139 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001140 if (!MsgSendFunctionDecl)
1141 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001142 if (!MsgSendSuperFunctionDecl)
1143 SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001144 if (!GetClassFunctionDecl)
1145 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001146
Steve Naroff874e2322007-11-15 10:28:18 +00001147 // default to objc_msgSend().
1148 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1149
Steve Naroff934f2762007-10-24 22:48:43 +00001150 // Synthesize a call to objc_msgSend().
1151 llvm::SmallVector<Expr*, 8> MsgExprs;
1152 IdentifierInfo *clsName = Exp->getClassName();
1153
1154 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1155 if (clsName) { // class message.
1156 llvm::SmallVector<Expr*, 8> ClsExprs;
1157 QualType argType = Context->getPointerType(Context->CharTy);
1158 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1159 clsName->getLength(),
1160 false, argType, SourceLocation(),
1161 SourceLocation()));
1162 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1163 &ClsExprs[0], ClsExprs.size());
1164 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001165 } else { // instance message.
1166 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001167
1168 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1169 MsgSendFlavor = MsgSendSuperFunctionDecl;
1170 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1171
1172 llvm::SmallVector<Expr*, 4> InitExprs;
1173
1174 InitExprs.push_back(recExpr); // set the 'receiver'.
1175
1176 llvm::SmallVector<Expr*, 8> ClsExprs;
1177 QualType argType = Context->getPointerType(Context->CharTy);
1178 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1179 ID->getIdentifier()->getLength(),
1180 false, argType, SourceLocation(),
1181 SourceLocation()));
1182 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1183 &ClsExprs[0], ClsExprs.size());
1184 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1185 // struct objc_super
1186 QualType superType = getSuperStructType();
1187 // (struct objc_super) { <exprs from above> }
1188 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1189 &InitExprs[0], InitExprs.size(),
1190 SourceLocation());
1191 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1192 // struct objc_super *
1193 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1194 Context->getPointerType(SuperRep->getType()),
1195 SourceLocation());
1196 MsgExprs.push_back(Unop);
1197 } else {
1198 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1199 MsgExprs.push_back(recExpr);
1200 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001201 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001202 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001203 llvm::SmallVector<Expr*, 8> SelExprs;
1204 QualType argType = Context->getPointerType(Context->CharTy);
1205 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1206 Exp->getSelector().getName().size(),
1207 false, argType, SourceLocation(),
1208 SourceLocation()));
1209 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1210 &SelExprs[0], SelExprs.size());
1211 MsgExprs.push_back(SelExp);
1212
1213 // Now push any user supplied arguments.
1214 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001215 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001216 // Make all implicit casts explicit...ICE comes in handy:-)
1217 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1218 // Reuse the ICE type, it is exactly what the doctor ordered.
1219 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1220 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001221 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001222 // We've transferred the ownership to MsgExprs. Null out the argument in
1223 // the original expression, since we will delete it below.
1224 Exp->setArg(i, 0);
1225 }
Steve Naroffab972d32007-11-04 22:37:50 +00001226 // Generate the funky cast.
1227 CastExpr *cast;
1228 llvm::SmallVector<QualType, 8> ArgTypes;
1229 QualType returnType;
1230
1231 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001232 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1233 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1234 else
1235 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001236 ArgTypes.push_back(Context->getObjcSelType());
1237 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1238 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001239 for (int i = 0; i < mDecl->getNumParams(); i++) {
1240 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001241 ArgTypes.push_back(t);
1242 }
Steve Naroffab972d32007-11-04 22:37:50 +00001243 returnType = mDecl->getResultType();
1244 } else {
1245 returnType = Context->getObjcIdType();
1246 }
1247 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001248 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001249
1250 // Create a reference to the objc_msgSend() declaration.
Steve Naroff874e2322007-11-15 10:28:18 +00001251 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001252
1253 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1254 // If we don't do this cast, we get the following bizarre warning/note:
1255 // xx.m:13: warning: function called through a non-compatible type
1256 // xx.m:13: note: if this code is reached, the program will abort
1257 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1258 SourceLocation());
1259
1260 // Now do the "normal" pointer to function cast.
1261 QualType castType = Context->getFunctionType(returnType,
1262 &ArgTypes[0], ArgTypes.size(),
1263 false/*FIXME:variadic*/);
1264 castType = Context->getPointerType(castType);
1265 cast = new CastExpr(castType, cast, SourceLocation());
1266
1267 // Don't forget the parens to enforce the proper binding.
1268 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1269
1270 const FunctionType *FT = msgSendType->getAsFunctionType();
1271 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1272 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001273 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001274 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001275
Chris Lattnere64b7772007-10-24 16:57:36 +00001276 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001277 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001278}
1279
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001280/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1281/// an objective-c class with ivars.
1282void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1283 std::string &Result) {
1284 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1285 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001286 // Do not synthesize more than once.
1287 if (ObjcSynthesizedStructs.count(CDecl))
1288 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001289 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1290 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1291 // Do it for the root
1292 SynthesizeObjcInternalStruct(RCDecl, Result);
1293 }
1294
Steve Naroff03300712007-11-12 13:56:41 +00001295 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001296 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001297 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001298 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1299 return;
Fariborz Jahanian95673922007-11-14 22:26:25 +00001300 // FIXME: This has potential of causing problem. If
1301 // SynthesizeObjcInternalStruct is ever called recursively.
Steve Narofffea763e82007-11-14 19:25:57 +00001302 Result += "\nstruct ";
1303 Result += CDecl->getName();
1304
1305 SourceLocation LocStart = CDecl->getLocStart();
1306 SourceLocation LocEnd = CDecl->getLocEnd();
1307
1308 const char *startBuf = SM->getCharacterData(LocStart);
1309 const char *endBuf = SM->getCharacterData(LocEnd);
1310
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001311 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001312 const char *cursor = strchr(startBuf, '{');
1313 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001314 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001315
1316 // rewrite the original header *without* disturbing the '{'
1317 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1318 Result.c_str(), Result.size());
1319 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1320 Result = "\n struct ";
1321 Result += RCDecl->getName();
1322 Result += " _";
1323 Result += RCDecl->getName();
1324 Result += ";\n";
1325
1326 // insert the super class structure definition.
1327 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1328 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1329 }
1330 cursor++; // past '{'
1331
1332 // Now comment out any visibility specifiers.
1333 while (cursor < endBuf) {
1334 if (*cursor == '@') {
1335 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001336 // Skip whitespace.
1337 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1338 /*scan*/;
1339
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001340 // FIXME: presence of @public, etc. inside comment results in
1341 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001342 if (!strncmp(cursor, "public", strlen("public")) ||
1343 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001344 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001345 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001346 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001347 // FIXME: If there are cases where '<' is used in ivar declaration part
1348 // of user code, then scan the ivar list and use needToScanForQualifiers
1349 // for type checking.
1350 else if (*cursor == '<') {
1351 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1352 Rewrite.InsertText(atLoc, "/* ", 3);
1353 cursor = strchr(cursor, '>');
1354 cursor++;
1355 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1356 Rewrite.InsertText(atLoc, " */", 3);
1357 }
Steve Narofffea763e82007-11-14 19:25:57 +00001358 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001359 }
Steve Narofffea763e82007-11-14 19:25:57 +00001360 // Don't forget to add a ';'!!
1361 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1362 } else { // we don't have any instance variables - insert super struct.
1363 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1364 Result += " {\n struct ";
1365 Result += RCDecl->getName();
1366 Result += " _";
1367 Result += RCDecl->getName();
1368 Result += ";\n};\n";
1369 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1370 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001371 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001372 // Mark this struct as having been generated.
1373 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001374 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001375}
1376
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001377// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1378/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001379void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001380 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001381 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001382 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001383 const char *ClassName,
1384 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001385 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001386 if (NumMethods > 0 && !objc_impl_method) {
1387 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001388 SEL _cmd;
1389 char *method_types;
1390 void *_imp;
1391 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001392 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001393 Result += "\nstruct _objc_method {\n";
1394 Result += "\tSEL _cmd;\n";
1395 Result += "\tchar *method_types;\n";
1396 Result += "\tvoid *_imp;\n";
1397 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001398
1399 /* struct _objc_method_list {
1400 struct _objc_method_list *next_method;
1401 int method_count;
1402 struct _objc_method method_list[];
1403 }
1404 */
1405 Result += "\nstruct _objc_method_list {\n";
1406 Result += "\tstruct _objc_method_list *next_method;\n";
1407 Result += "\tint method_count;\n";
1408 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001409 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001410 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001411 // Build _objc_method_list for class's methods if needed
1412 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001413 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001414 Result += prefix;
1415 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1416 Result += "_METHODS_";
1417 Result += ClassName;
1418 Result += " __attribute__ ((section (\"__OBJC, __";
1419 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001420 Result += "_meth\")))= ";
1421 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1422
1423 Result += "\t,{{(SEL)\"";
1424 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001425 std::string MethodTypeString;
1426 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1427 Result += "\", \"";
1428 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001429 Result += "\", ";
1430 Result += MethodInternalNames[Methods[0]];
1431 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001432 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001433 Result += "\t ,{(SEL)\"";
1434 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001435 std::string MethodTypeString;
1436 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1437 Result += "\", \"";
1438 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001439 Result += "\", ";
1440 Result += MethodInternalNames[Methods[i]];
1441 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001442 }
1443 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001444 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001445}
1446
1447/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1448void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1449 int NumProtocols,
1450 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001451 const char *ClassName,
1452 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001453 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001454 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001455 for (int i = 0; i < NumProtocols; i++) {
1456 ObjcProtocolDecl *PDecl = Protocols[i];
1457 // Output struct protocol_methods holder of method selector and type.
1458 if (!objc_protocol_methods &&
1459 (PDecl->getNumInstanceMethods() > 0
1460 || PDecl->getNumClassMethods() > 0)) {
1461 /* struct protocol_methods {
1462 SEL _cmd;
1463 char *method_types;
1464 }
1465 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001466 Result += "\nstruct protocol_methods {\n";
1467 Result += "\tSEL _cmd;\n";
1468 Result += "\tchar *method_types;\n";
1469 Result += "};\n";
1470
1471 /* struct _objc_protocol_method_list {
1472 int protocol_method_count;
1473 struct protocol_methods protocols[];
1474 }
1475 */
1476 Result += "\nstruct _objc_protocol_method_list {\n";
1477 Result += "\tint protocol_method_count;\n";
1478 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001479 objc_protocol_methods = true;
1480 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001481
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001482 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001483 int NumMethods = PDecl->getNumInstanceMethods();
1484 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001485 Result += "\nstatic struct _objc_protocol_method_list "
1486 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1487 Result += PDecl->getName();
1488 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1489 "{\n\t" + utostr(NumMethods) + "\n";
1490
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001491 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001492 Result += "\t,{{(SEL)\"";
1493 Result += Methods[0]->getSelector().getName().c_str();
1494 Result += "\", \"\"}\n";
1495
1496 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001497 Result += "\t ,{(SEL)\"";
1498 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001499 std::string MethodTypeString;
1500 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1501 Result += "\", \"";
1502 Result += MethodTypeString;
1503 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001504 }
1505 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001506 }
1507
1508 // Output class methods declared in this protocol.
1509 NumMethods = PDecl->getNumClassMethods();
1510 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001511 Result += "\nstatic struct _objc_protocol_method_list "
1512 "_OBJC_PROTOCOL_CLASS_METHODS_";
1513 Result += PDecl->getName();
1514 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1515 "{\n\t";
1516 Result += utostr(NumMethods);
1517 Result += "\n";
1518
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001519 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001520 Result += "\t,{{(SEL)\"";
1521 Result += Methods[0]->getSelector().getName().c_str();
1522 Result += "\", \"\"}\n";
1523
1524 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001525 Result += "\t ,{(SEL)\"";
1526 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001527 std::string MethodTypeString;
1528 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1529 Result += "\", \"";
1530 Result += MethodTypeString;
1531 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001532 }
1533 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001534 }
1535 // Output:
1536 /* struct _objc_protocol {
1537 // Objective-C 1.0 extensions
1538 struct _objc_protocol_extension *isa;
1539 char *protocol_name;
1540 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001541 struct _objc_protocol_method_list *instance_methods;
1542 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001543 };
1544 */
1545 static bool objc_protocol = false;
1546 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001547 Result += "\nstruct _objc_protocol {\n";
1548 Result += "\tstruct _objc_protocol_extension *isa;\n";
1549 Result += "\tchar *protocol_name;\n";
1550 Result += "\tstruct _objc_protocol **protocol_list;\n";
1551 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1552 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1553 Result += "};\n";
1554
1555 /* struct _objc_protocol_list {
1556 struct _objc_protocol_list *next;
1557 int protocol_count;
1558 struct _objc_protocol *class_protocols[];
1559 }
1560 */
1561 Result += "\nstruct _objc_protocol_list {\n";
1562 Result += "\tstruct _objc_protocol_list *next;\n";
1563 Result += "\tint protocol_count;\n";
1564 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1565 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001566 objc_protocol = true;
1567 }
1568
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001569 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1570 Result += PDecl->getName();
1571 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1572 "{\n\t0, \"";
1573 Result += PDecl->getName();
1574 Result += "\", 0, ";
1575 if (PDecl->getInstanceMethods() > 0) {
1576 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1577 Result += PDecl->getName();
1578 Result += ", ";
1579 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001580 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001581 Result += "0, ";
1582 if (PDecl->getClassMethods() > 0) {
1583 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1584 Result += PDecl->getName();
1585 Result += "\n";
1586 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001587 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001588 Result += "0\n";
1589 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001590 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001591 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001592 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1593 Result += prefix;
1594 Result += "_PROTOCOLS_";
1595 Result += ClassName;
1596 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1597 "{\n\t0, ";
1598 Result += utostr(NumProtocols);
1599 Result += "\n";
1600
1601 Result += "\t,{&_OBJC_PROTOCOL_";
1602 Result += Protocols[0]->getName();
1603 Result += " \n";
1604
1605 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001606 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001607 Result += "\t ,&_OBJC_PROTOCOL_";
1608 Result += PDecl->getName();
1609 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001610 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001611 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001612 }
1613}
1614
1615/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1616/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001617void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1618 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001619 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1620 // Find category declaration for this implementation.
1621 ObjcCategoryDecl *CDecl;
1622 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1623 CDecl = CDecl->getNextClassCategory())
1624 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1625 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001626
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001627 char *FullCategoryName = (char*)alloca(
1628 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1629 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1630
1631 // Build _objc_method_list for class's instance methods if needed
1632 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1633 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001634 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001635 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001636
1637 // Build _objc_method_list for class's class methods if needed
1638 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1639 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001640 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001641 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001642
1643 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001644 // Null CDecl is case of a category implementation with no category interface
1645 if (CDecl)
1646 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1647 CDecl->getNumReferencedProtocols(),
1648 "CATEGORY",
1649 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001650
1651 /* struct _objc_category {
1652 char *category_name;
1653 char *class_name;
1654 struct _objc_method_list *instance_methods;
1655 struct _objc_method_list *class_methods;
1656 struct _objc_protocol_list *protocols;
1657 // Objective-C 1.0 extensions
1658 uint32_t size; // sizeof (struct _objc_category)
1659 struct _objc_property_list *instance_properties; // category's own
1660 // @property decl.
1661 };
1662 */
1663
1664 static bool objc_category = false;
1665 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001666 Result += "\nstruct _objc_category {\n";
1667 Result += "\tchar *category_name;\n";
1668 Result += "\tchar *class_name;\n";
1669 Result += "\tstruct _objc_method_list *instance_methods;\n";
1670 Result += "\tstruct _objc_method_list *class_methods;\n";
1671 Result += "\tstruct _objc_protocol_list *protocols;\n";
1672 Result += "\tunsigned int size;\n";
1673 Result += "\tstruct _objc_property_list *instance_properties;\n";
1674 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001675 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001676 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001677 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1678 Result += FullCategoryName;
1679 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1680 Result += IDecl->getName();
1681 Result += "\"\n\t, \"";
1682 Result += ClassDecl->getName();
1683 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001684
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001685 if (IDecl->getNumInstanceMethods() > 0) {
1686 Result += "\t, (struct _objc_method_list *)"
1687 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1688 Result += FullCategoryName;
1689 Result += "\n";
1690 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001691 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001692 Result += "\t, 0\n";
1693 if (IDecl->getNumClassMethods() > 0) {
1694 Result += "\t, (struct _objc_method_list *)"
1695 "&_OBJC_CATEGORY_CLASS_METHODS_";
1696 Result += FullCategoryName;
1697 Result += "\n";
1698 }
1699 else
1700 Result += "\t, 0\n";
1701
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001702 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001703 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1704 Result += FullCategoryName;
1705 Result += "\n";
1706 }
1707 else
1708 Result += "\t, 0\n";
1709 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001710}
1711
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001712/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1713/// ivar offset.
1714void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1715 ObjcIvarDecl *ivar,
1716 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001717 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001718 Result += IDecl->getName();
1719 Result += ", ";
1720 Result += ivar->getName();
1721 Result += ")";
1722}
1723
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001724//===----------------------------------------------------------------------===//
1725// Meta Data Emission
1726//===----------------------------------------------------------------------===//
1727
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001728void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1729 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001730 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1731
1732 // Build _objc_ivar_list metadata for classes ivars if needed
1733 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1734 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001735 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001736
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001737 SynthesizeObjcInternalStruct(CDecl, Result);
1738
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001739 if (NumIvars > 0) {
1740 static bool objc_ivar = false;
1741 if (!objc_ivar) {
1742 /* struct _objc_ivar {
1743 char *ivar_name;
1744 char *ivar_type;
1745 int ivar_offset;
1746 };
1747 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001748 Result += "\nstruct _objc_ivar {\n";
1749 Result += "\tchar *ivar_name;\n";
1750 Result += "\tchar *ivar_type;\n";
1751 Result += "\tint ivar_offset;\n";
1752 Result += "};\n";
1753
1754 /* struct _objc_ivar_list {
1755 int ivar_count;
1756 struct _objc_ivar ivar_list[];
1757 };
1758 */
1759 Result += "\nstruct _objc_ivar_list {\n";
1760 Result += "\tint ivar_count;\n";
1761 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001762 objc_ivar = true;
1763 }
1764
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001765 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1766 Result += IDecl->getName();
1767 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1768 "{\n\t";
1769 Result += utostr(NumIvars);
1770 Result += "\n";
1771
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001772 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1773 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001774 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001775 Result += "\t,{{\"";
1776 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001777 Result += "\", \"";
1778 std::string StrEncoding;
1779 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1780 Result += StrEncoding;
1781 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001782 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1783 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001784 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001785 Result += "\t ,{\"";
1786 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001787 Result += "\", \"";
1788 std::string StrEncoding;
1789 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1790 Result += StrEncoding;
1791 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001792 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1793 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001794 }
1795
1796 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001797 }
1798
1799 // Build _objc_method_list for class's instance methods if needed
1800 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1801 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001802 true,
1803 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001804
1805 // Build _objc_method_list for class's class methods if needed
1806 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001807 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001808 false,
1809 "", IDecl->getName(), Result);
1810
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001811 // Protocols referenced in class declaration?
1812 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1813 CDecl->getNumIntfRefProtocols(),
1814 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001815 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001816
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001817
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001818 // Declaration of class/meta-class metadata
1819 /* struct _objc_class {
1820 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001821 const char *super_class_name;
1822 char *name;
1823 long version;
1824 long info;
1825 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001826 struct _objc_ivar_list *ivars;
1827 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001828 struct objc_cache *cache;
1829 struct objc_protocol_list *protocols;
1830 const char *ivar_layout;
1831 struct _objc_class_ext *ext;
1832 };
1833 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001834 static bool objc_class = false;
1835 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001836 Result += "\nstruct _objc_class {\n";
1837 Result += "\tstruct _objc_class *isa;\n";
1838 Result += "\tconst char *super_class_name;\n";
1839 Result += "\tchar *name;\n";
1840 Result += "\tlong version;\n";
1841 Result += "\tlong info;\n";
1842 Result += "\tlong instance_size;\n";
1843 Result += "\tstruct _objc_ivar_list *ivars;\n";
1844 Result += "\tstruct _objc_method_list *methods;\n";
1845 Result += "\tstruct objc_cache *cache;\n";
1846 Result += "\tstruct _objc_protocol_list *protocols;\n";
1847 Result += "\tconst char *ivar_layout;\n";
1848 Result += "\tstruct _objc_class_ext *ext;\n";
1849 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001850 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001851 }
1852
1853 // Meta-class metadata generation.
1854 ObjcInterfaceDecl *RootClass = 0;
1855 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1856 while (SuperClass) {
1857 RootClass = SuperClass;
1858 SuperClass = SuperClass->getSuperClass();
1859 }
1860 SuperClass = CDecl->getSuperClass();
1861
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001862 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1863 Result += CDecl->getName();
1864 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1865 "{\n\t(struct _objc_class *)\"";
1866 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1867 Result += "\"";
1868
1869 if (SuperClass) {
1870 Result += ", \"";
1871 Result += SuperClass->getName();
1872 Result += "\", \"";
1873 Result += CDecl->getName();
1874 Result += "\"";
1875 }
1876 else {
1877 Result += ", 0, \"";
1878 Result += CDecl->getName();
1879 Result += "\"";
1880 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001881 // TODO: 'ivars' field for root class is currently set to 0.
1882 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001883 Result += ", 0,2, sizeof(struct _objc_class), 0";
1884 if (CDecl->getNumClassMethods() > 0) {
1885 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1886 Result += CDecl->getName();
1887 Result += "\n";
1888 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001889 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001890 Result += ", 0\n";
1891 if (CDecl->getNumIntfRefProtocols() > 0) {
1892 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1893 Result += CDecl->getName();
1894 Result += ",0,0\n";
1895 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001896 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001897 Result += "\t,0,0,0,0\n";
1898 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001899
1900 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001901 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1902 Result += CDecl->getName();
1903 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1904 "{\n\t&_OBJC_METACLASS_";
1905 Result += CDecl->getName();
1906 if (SuperClass) {
1907 Result += ", \"";
1908 Result += SuperClass->getName();
1909 Result += "\", \"";
1910 Result += CDecl->getName();
1911 Result += "\"";
1912 }
1913 else {
1914 Result += ", 0, \"";
1915 Result += CDecl->getName();
1916 Result += "\"";
1917 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001918 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001919 Result += ", 0,1";
1920 if (!ObjcSynthesizedStructs.count(CDecl))
1921 Result += ",0";
1922 else {
1923 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001924 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001925 Result += CDecl->getName();
1926 Result += ")";
1927 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001928 if (NumIvars > 0) {
1929 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1930 Result += CDecl->getName();
1931 Result += "\n\t";
1932 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001933 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001934 Result += ",0";
1935 if (IDecl->getNumInstanceMethods() > 0) {
1936 Result += ", &_OBJC_INSTANCE_METHODS_";
1937 Result += CDecl->getName();
1938 Result += ", 0\n\t";
1939 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001940 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001941 Result += ",0,0";
1942 if (CDecl->getNumIntfRefProtocols() > 0) {
1943 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1944 Result += CDecl->getName();
1945 Result += ", 0,0\n";
1946 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001947 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001948 Result += ",0,0,0\n";
1949 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001950}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001951
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001952/// RewriteImplementations - This routine rewrites all method implementations
1953/// and emits meta-data.
1954
1955void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001956 int ClsDefCount = ClassImplementation.size();
1957 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001958
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001959 if (ClsDefCount == 0 && CatDefCount == 0)
1960 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001961 // Rewrite implemented methods
1962 for (int i = 0; i < ClsDefCount; i++)
1963 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001964
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001965 for (int i = 0; i < CatDefCount; i++)
1966 RewriteImplementationDecl(CategoryImplementation[i]);
1967
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001968 // This is needed for use of offsetof
1969 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001970
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001971 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001972 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001973 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001974
1975 // For each implemented category, write out all its meta data.
1976 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001977 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001978
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001979 // Write objc_symtab metadata
1980 /*
1981 struct _objc_symtab
1982 {
1983 long sel_ref_cnt;
1984 SEL *refs;
1985 short cls_def_cnt;
1986 short cat_def_cnt;
1987 void *defs[cls_def_cnt + cat_def_cnt];
1988 };
1989 */
1990
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001991 Result += "\nstruct _objc_symtab {\n";
1992 Result += "\tlong sel_ref_cnt;\n";
1993 Result += "\tSEL *refs;\n";
1994 Result += "\tshort cls_def_cnt;\n";
1995 Result += "\tshort cat_def_cnt;\n";
1996 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1997 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001998
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001999 Result += "static struct _objc_symtab "
2000 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2001 Result += "\t0, 0, " + utostr(ClsDefCount)
2002 + ", " + utostr(CatDefCount) + "\n";
2003 for (int i = 0; i < ClsDefCount; i++) {
2004 Result += "\t,&_OBJC_CLASS_";
2005 Result += ClassImplementation[i]->getName();
2006 Result += "\n";
2007 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002008
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002009 for (int i = 0; i < CatDefCount; i++) {
2010 Result += "\t,&_OBJC_CATEGORY_";
2011 Result += CategoryImplementation[i]->getClassInterface()->getName();
2012 Result += "_";
2013 Result += CategoryImplementation[i]->getName();
2014 Result += "\n";
2015 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002016
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002017 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002018
2019 // Write objc_module metadata
2020
2021 /*
2022 struct _objc_module {
2023 long version;
2024 long size;
2025 const char *name;
2026 struct _objc_symtab *symtab;
2027 }
2028 */
2029
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002030 Result += "\nstruct _objc_module {\n";
2031 Result += "\tlong version;\n";
2032 Result += "\tlong size;\n";
2033 Result += "\tconst char *name;\n";
2034 Result += "\tstruct _objc_symtab *symtab;\n";
2035 Result += "};\n\n";
2036 Result += "static struct _objc_module "
2037 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002038 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2039 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002040 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002041
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002042}
Chris Lattner311ff022007-10-16 22:36:42 +00002043