blob: 23bf240ac82e472a741efa3abd220cdc752c44ef [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 Narofff6248702007-11-15 17:06:21 +000073 const char *s = "struct objc_selector; struct objc_class; struct objc_super;\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 "extern struct objc_object *objc_msgSendSuper"
77 "(struct objc_super *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +000078 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000079 "(const char *);\n"
80 "extern void objc_exception_throw(struct objc_object *);\n"
81 "extern void objc_exception_try_enter(void *);\n"
82 "extern void objc_exception_try_exit(void *);\n"
83 "extern struct objc_object *objc_exception_extract(void *);\n"
84 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +000085 "(struct objc_class *, struct objc_object *, ...);\n"
86 "#include <Objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +000087
Steve Naroffab972d32007-11-04 22:37:50 +000088 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
89 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000090 }
Chris Lattner8a12c272007-10-11 18:38:32 +000091
Chris Lattnerf04da132007-10-24 17:06:59 +000092 // Top Level Driver code.
93 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000094 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000095 ~RewriteTest();
96
97 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000098 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000099 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000100 void RewriteTabs();
101 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000102 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000103 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000104 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000105 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000106 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000107 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000108 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000109 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000110 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +0000111 void RewriteObjcQualifiedInterfaceTypes(
112 const FunctionTypeProto *proto, FunctionDecl *FD);
113 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000114 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
115 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000116
Chris Lattnerf04da132007-10-24 17:06:59 +0000117 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000118 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000119 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000120 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000121 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000122 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000123 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000124 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
125 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
126 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000127 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000128 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
129 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000130 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000131 void SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000132 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000133 void SynthCFStringFunctionDecl();
134
Chris Lattnerf04da132007-10-24 17:06:59 +0000135 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000136 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
137 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000138
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000139 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
140 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000141
Steve Naroff0416fb92007-11-11 17:19:15 +0000142 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000143 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000144 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000145 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000146 const char *ClassName,
147 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000148
149 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
150 int NumProtocols,
151 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000152 const char *ClassName,
153 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000154 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
155 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000156 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
157 ObjcIvarDecl *ivar,
158 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000159 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000160 };
161}
162
Chris Lattner8a12c272007-10-11 18:38:32 +0000163ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165//===----------------------------------------------------------------------===//
166// Top Level Driver Code
167//===----------------------------------------------------------------------===//
168
Chris Lattner8a12c272007-10-11 18:38:32 +0000169void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000170 // Two cases: either the decl could be in the main file, or it could be in a
171 // #included file. If the former, rewrite it now. If the later, check to see
172 // if we rewrote the #include/#import.
173 SourceLocation Loc = D->getLocation();
174 Loc = SM->getLogicalLoc(Loc);
175
176 // If this is for a builtin, ignore it.
177 if (Loc.isInvalid()) return;
178
Steve Naroffebf2b562007-10-23 23:50:29 +0000179 // Look for built-in declarations that we need to refer during the rewrite.
180 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000181 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000182 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
183 // declared in <Foundation/NSString.h>
184 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
185 ConstantStringClassReference = FVD;
186 return;
187 }
Steve Naroffbef11852007-10-26 20:53:56 +0000188 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
189 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000190 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
191 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000192 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
193 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000194 } else if (ObjcForwardProtocolDecl *FP =
195 dyn_cast<ObjcForwardProtocolDecl>(D)){
196 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000197 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000198 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000199 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
200 return HandleDeclInMainFile(D);
201
Chris Lattnerf04da132007-10-24 17:06:59 +0000202 // Otherwise, see if there is a #import in the main file that should be
203 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000204 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000205}
206
Chris Lattnerf04da132007-10-24 17:06:59 +0000207/// HandleDeclInMainFile - This is called for each top-level decl defined in the
208/// main file of the input.
209void RewriteTest::HandleDeclInMainFile(Decl *D) {
210 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
211 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000212 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000213
214 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000215 if (Stmt *Body = MD->getBody()) {
216 //Body->dump();
217 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000218 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000219 CurMethodDecl = 0;
220 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000221 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000222 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
223 ClassImplementation.push_back(CI);
224 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
225 CategoryImplementation.push_back(CI);
226 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
227 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000228 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
229 if (VD->getInit())
230 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
231 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000232 // Nothing yet.
233}
234
235RewriteTest::~RewriteTest() {
236 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000237
238 // Rewrite tabs if we care.
239 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000240
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000241 // Rewrite Objective-c meta data*
242 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000243 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
246 // we are done.
247 if (const RewriteBuffer *RewriteBuf =
248 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000249 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 std::string S(RewriteBuf->begin(), RewriteBuf->end());
251 printf("%s\n", S.c_str());
252 } else {
253 printf("No changes\n");
254 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000255 // Emit metadata.
256 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000257}
258
Chris Lattnerf04da132007-10-24 17:06:59 +0000259//===----------------------------------------------------------------------===//
260// Syntactic (non-AST) Rewriting Code
261//===----------------------------------------------------------------------===//
262
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000263void RewriteTest::RewriteInclude(SourceLocation Loc) {
264 // Rip up the #include stack to the main file.
265 SourceLocation IncLoc = Loc, NextLoc = Loc;
266 do {
267 IncLoc = Loc;
268 Loc = SM->getLogicalLoc(NextLoc);
269 NextLoc = SM->getIncludeLoc(Loc);
270 } while (!NextLoc.isInvalid());
271
272 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
273 // IncLoc indicates the header that was included if it is useful.
274 IncLoc = SM->getLogicalLoc(IncLoc);
275 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
276 Loc == LastIncLoc)
277 return;
278 LastIncLoc = Loc;
279
280 unsigned IncCol = SM->getColumnNumber(Loc);
281 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
282
283 // Replace the #import with #include.
284 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
285}
286
Chris Lattnerf04da132007-10-24 17:06:59 +0000287void RewriteTest::RewriteTabs() {
288 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
289 const char *MainBufStart = MainBuf.first;
290 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000291
Chris Lattnerf04da132007-10-24 17:06:59 +0000292 // Loop over the whole file, looking for tabs.
293 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
294 if (*BufPtr != '\t')
295 continue;
296
297 // Okay, we found a tab. This tab will turn into at least one character,
298 // but it depends on which 'virtual column' it is in. Compute that now.
299 unsigned VCol = 0;
300 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
301 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
302 ++VCol;
303
304 // Okay, now that we know the virtual column, we know how many spaces to
305 // insert. We assume 8-character tab-stops.
306 unsigned Spaces = 8-(VCol & 7);
307
308 // Get the location of the tab.
309 SourceLocation TabLoc =
310 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
311
312 // Rewrite the single tab character into a sequence of spaces.
313 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
314 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000315}
316
317
Chris Lattnerf04da132007-10-24 17:06:59 +0000318void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
319 int numDecls = ClassDecl->getNumForwardDecls();
320 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
321
322 // Get the start location and compute the semi location.
323 SourceLocation startLoc = ClassDecl->getLocation();
324 const char *startBuf = SM->getCharacterData(startLoc);
325 const char *semiPtr = strchr(startBuf, ';');
326
327 // Translate to typedef's that forward reference structs with the same name
328 // as the class. As a convenience, we include the original declaration
329 // as a comment.
330 std::string typedefString;
331 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000332 typedefString.append(startBuf, semiPtr-startBuf+1);
333 typedefString += "\n";
334 for (int i = 0; i < numDecls; i++) {
335 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000336 typedefString += "#ifndef _REWRITER_typedef_";
337 typedefString += ForwardDecl->getName();
338 typedefString += "\n";
339 typedefString += "#define _REWRITER_typedef_";
340 typedefString += ForwardDecl->getName();
341 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000342 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000343 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000344 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000345 }
346
347 // Replace the @class with typedefs corresponding to the classes.
348 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
349 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000350}
351
Steve Naroff71c0a952007-11-13 23:01:27 +0000352void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000353 for (int i = 0; i < nMethods; i++) {
354 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000355 SourceLocation LocStart = Method->getLocStart();
356 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000357
Steve Naroff1d098f62007-11-14 14:34:23 +0000358 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
359 Rewrite.InsertText(LocStart, "/* ", 3);
360 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
361 } else {
362 Rewrite.InsertText(LocStart, "// ", 3);
363 }
Steve Naroff423cb562007-10-30 13:30:57 +0000364 }
365}
366
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000367void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
368{
369 for (int i = 0; i < nProperties; i++) {
370 ObjcPropertyDecl *Property = Properties[i];
371 SourceLocation Loc = Property->getLocation();
372
373 Rewrite.ReplaceText(Loc, 0, "// ", 3);
374
375 // FIXME: handle properties that are declared across multiple lines.
376 }
377}
378
Steve Naroff423cb562007-10-30 13:30:57 +0000379void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
380 SourceLocation LocStart = CatDecl->getLocStart();
381
382 // FIXME: handle category headers that are declared across multiple lines.
383 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
384
Steve Naroff71c0a952007-11-13 23:01:27 +0000385 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
386 CatDecl->getInstanceMethods());
387 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
388 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000389 // Lastly, comment out the @end.
390 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
391}
392
Steve Naroff752d6ef2007-10-30 16:42:30 +0000393void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000394 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000395
Steve Naroff752d6ef2007-10-30 16:42:30 +0000396 SourceLocation LocStart = PDecl->getLocStart();
397
398 // FIXME: handle protocol headers that are declared across multiple lines.
399 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
400
Steve Naroff71c0a952007-11-13 23:01:27 +0000401 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
402 PDecl->getInstanceMethods());
403 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
404 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000405 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000406 SourceLocation LocEnd = PDecl->getAtEndLoc();
407 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000408
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000409 // Must comment out @optional/@required
410 const char *startBuf = SM->getCharacterData(LocStart);
411 const char *endBuf = SM->getCharacterData(LocEnd);
412 for (const char *p = startBuf; p < endBuf; p++) {
413 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
414 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000415 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000416 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
417 CommentedOptional.c_str(), CommentedOptional.size());
418
419 }
420 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
421 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000422 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000423 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
424 CommentedRequired.c_str(), CommentedRequired.size());
425
426 }
427 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000428}
429
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000430void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
431 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000432 if (LocStart.isInvalid())
433 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000434 // FIXME: handle forward protocol that are declared across multiple lines.
435 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
436}
437
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000438void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
439 std::string &ResultStr) {
440 ResultStr += "\nstatic ";
441 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000442 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000443
444 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000445 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000446
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000447 if (OMD->isInstance())
448 NameStr += "_I_";
449 else
450 NameStr += "_C_";
451
452 NameStr += OMD->getClassInterface()->getName();
453 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000454
455 NamedDecl *MethodContext = OMD->getMethodContext();
456 if (ObjcCategoryImplDecl *CID =
457 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000458 NameStr += CID->getName();
459 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000460 }
461 // Append selector names, replacing ':' with '_'
462 const char *selName = OMD->getSelector().getName().c_str();
463 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000464 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000465 else {
466 std::string selString = OMD->getSelector().getName();
467 int len = selString.size();
468 for (int i = 0; i < len; i++)
469 if (selString[i] == ':')
470 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000471 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000472 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000473 // Remember this name for metadata emission
474 MethodInternalNames[OMD] = NameStr;
475 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000476
477 // Rewrite arguments
478 ResultStr += "(";
479
480 // invisible arguments
481 if (OMD->isInstance()) {
482 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
483 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000484 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
485 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000486 ResultStr += selfTy.getAsString();
487 }
488 else
489 ResultStr += Context->getObjcIdType().getAsString();
490
491 ResultStr += " self, ";
492 ResultStr += Context->getObjcSelType().getAsString();
493 ResultStr += " _cmd";
494
495 // Method arguments.
496 for (int i = 0; i < OMD->getNumParams(); i++) {
497 ParmVarDecl *PDecl = OMD->getParamDecl(i);
498 ResultStr += ", ";
499 ResultStr += PDecl->getType().getAsString();
500 ResultStr += " ";
501 ResultStr += PDecl->getName();
502 }
503 ResultStr += ")";
504
505}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000506void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
507 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
508 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000509
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000510 if (IMD)
511 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
512 else
513 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000514
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000515 int numMethods = IMD ? IMD->getNumInstanceMethods()
516 : CID->getNumInstanceMethods();
517
518 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000519 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000520 ObjcMethodDecl *OMD;
521 if (IMD)
522 OMD = IMD->getInstanceMethods()[i];
523 else
524 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000525 RewriteObjcMethodDecl(OMD, ResultStr);
526 SourceLocation LocStart = OMD->getLocStart();
527 SourceLocation LocEnd = OMD->getBody()->getLocStart();
528
529 const char *startBuf = SM->getCharacterData(LocStart);
530 const char *endBuf = SM->getCharacterData(LocEnd);
531 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
532 ResultStr.c_str(), ResultStr.size());
533 }
534
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000535 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
536 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000537 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000538 ObjcMethodDecl *OMD;
539 if (IMD)
540 OMD = IMD->getClassMethods()[i];
541 else
542 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000543 RewriteObjcMethodDecl(OMD, ResultStr);
544 SourceLocation LocStart = OMD->getLocStart();
545 SourceLocation LocEnd = OMD->getBody()->getLocStart();
546
547 const char *startBuf = SM->getCharacterData(LocStart);
548 const char *endBuf = SM->getCharacterData(LocEnd);
549 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
550 ResultStr.c_str(), ResultStr.size());
551 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000552 if (IMD)
553 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
554 else
555 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000556}
557
Steve Naroffbef11852007-10-26 20:53:56 +0000558void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000559 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000560 if (!ObjcForwardDecls.count(ClassDecl)) {
561 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000562 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000563 ResultStr += ClassDecl->getName();
564 ResultStr += "\n";
565 ResultStr += "#define _REWRITER_typedef_";
566 ResultStr += ClassDecl->getName();
567 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000568 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000569 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000570 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000571
572 // Mark this typedef as having been generated.
573 ObjcForwardDecls.insert(ClassDecl);
574 }
Steve Narofff908a872007-10-30 02:23:23 +0000575 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
576
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000577 RewriteProperties(ClassDecl->getNumPropertyDecl(),
578 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000579 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
580 ClassDecl->getInstanceMethods());
581 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
582 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000583
Steve Naroff2feac5e2007-10-30 03:43:13 +0000584 // Lastly, comment out the @end.
585 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000586}
587
Steve Naroff7e3411b2007-11-15 02:58:25 +0000588Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
589 ObjcIvarDecl *D = IV->getDecl();
590 if (IV->isFreeIvar()) {
591 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
592 IV->getLocation());
593 Rewrite.ReplaceStmt(IV, Replacement);
594 delete IV;
595 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000596 } else {
597 if (CurMethodDecl) {
598 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
599 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
600 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
601 IdentifierInfo *II = intT->getDecl()->getIdentifier();
602 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
603 II, 0);
604 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
605
606 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
607 // Don't forget the parens to enforce the proper binding.
608 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
609 Rewrite.ReplaceStmt(IV->getBase(), PE);
610 delete IV->getBase();
611 return PE;
612 }
613 }
614 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000615 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000616 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000617}
618
Chris Lattnerf04da132007-10-24 17:06:59 +0000619//===----------------------------------------------------------------------===//
620// Function Body / Expression rewriting
621//===----------------------------------------------------------------------===//
622
Steve Narofff3473a72007-11-09 15:20:18 +0000623Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000624 // Otherwise, just rewrite all children.
625 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
626 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000627 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000628 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000629 if (newStmt)
630 *CI = newStmt;
631 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000632
633 // Handle specific things.
634 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
635 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000636
637 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
638 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000639
640 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
641 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000642
643 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
644 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000645
Steve Naroff934f2762007-10-24 22:48:43 +0000646 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
647 // Before we rewrite it, put the original message expression in a comment.
648 SourceLocation startLoc = MessExpr->getLocStart();
649 SourceLocation endLoc = MessExpr->getLocEnd();
650
651 const char *startBuf = SM->getCharacterData(startLoc);
652 const char *endBuf = SM->getCharacterData(endLoc);
653
654 std::string messString;
655 messString += "// ";
656 messString.append(startBuf, endBuf-startBuf+1);
657 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000658
Steve Naroff934f2762007-10-24 22:48:43 +0000659 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
660 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
661 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000662 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000663 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000664 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000665
666 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
667 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000668
669 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
670 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000671#if 0
672 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
673 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
674 // Get the new text.
675 std::ostringstream Buf;
676 Replacement->printPretty(Buf);
677 const std::string &Str = Buf.str();
678
679 printf("CAST = %s\n", &Str[0]);
680 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
681 delete S;
682 return Replacement;
683 }
684#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000685 // Return this stmt unmodified.
686 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000687}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000688
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000689Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000690 // Get the start location and compute the semi location.
691 SourceLocation startLoc = S->getLocStart();
692 const char *startBuf = SM->getCharacterData(startLoc);
693
694 assert((*startBuf == '@') && "bogus @try location");
695
696 std::string buf;
697 // declare a new scope with two variables, _stack and _rethrow.
698 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
699 buf += "int buf[18/*32-bit i386*/];\n";
700 buf += "char *pointers[4];} _stack;\n";
701 buf += "id volatile _rethrow = 0;\n";
702 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000703 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000704
705 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
706
707 startLoc = S->getTryBody()->getLocEnd();
708 startBuf = SM->getCharacterData(startLoc);
709
710 assert((*startBuf == '}') && "bogus @try block");
711
712 SourceLocation lastCurlyLoc = startLoc;
713
714 startLoc = startLoc.getFileLocWithOffset(1);
715 buf = " /* @catch begin */ else {\n";
716 buf += " id _caught = objc_exception_extract(&_stack);\n";
717 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000718 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000719 buf += " _rethrow = objc_exception_extract(&_stack);\n";
720 buf += " else { /* @catch continue */";
721
Chris Lattner28d1fe82007-11-08 04:41:51 +0000722 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000723
724 bool sawIdTypedCatch = false;
725 Stmt *lastCatchBody = 0;
726 ObjcAtCatchStmt *catchList = S->getCatchStmts();
727 while (catchList) {
728 Stmt *catchStmt = catchList->getCatchParamStmt();
729
730 if (catchList == S->getCatchStmts())
731 buf = "if ("; // we are generating code for the first catch clause
732 else
733 buf = "else if (";
734 startLoc = catchList->getLocStart();
735 startBuf = SM->getCharacterData(startLoc);
736
737 assert((*startBuf == '@') && "bogus @catch location");
738
739 const char *lParenLoc = strchr(startBuf, '(');
740
741 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
742 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
743 if (t == Context->getObjcIdType()) {
744 buf += "1) { ";
745 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
746 buf.c_str(), buf.size());
747 sawIdTypedCatch = true;
748 } else if (const PointerType *pType = t->getAsPointerType()) {
749 ObjcInterfaceType *cls; // Should be a pointer to a class.
750
751 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
752 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000753 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000754 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000755 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000756 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
757 buf.c_str(), buf.size());
758 }
759 }
760 // Now rewrite the body...
761 lastCatchBody = catchList->getCatchBody();
762 SourceLocation rParenLoc = catchList->getRParenLoc();
763 SourceLocation bodyLoc = lastCatchBody->getLocStart();
764 const char *bodyBuf = SM->getCharacterData(bodyLoc);
765 const char *rParenBuf = SM->getCharacterData(rParenLoc);
766 assert((*rParenBuf == ')') && "bogus @catch paren location");
767 assert((*bodyBuf == '{') && "bogus @catch body location");
768
769 buf = " = _caught;";
770 // Here we replace ") {" with "= _caught;" (which initializes and
771 // declares the @catch parameter).
772 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
773 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000774 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000775 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000776 }
Steve Naroff75730982007-11-07 04:08:17 +0000777 catchList = catchList->getNextCatchStmt();
778 }
779 // Complete the catch list...
780 if (lastCatchBody) {
781 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
782 const char *bodyBuf = SM->getCharacterData(bodyLoc);
783 assert((*bodyBuf == '}') && "bogus @catch body location");
784 bodyLoc = bodyLoc.getFileLocWithOffset(1);
785 buf = " } } /* @catch end */\n";
786
Chris Lattner28d1fe82007-11-08 04:41:51 +0000787 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000788
789 // Set lastCurlyLoc
790 lastCurlyLoc = lastCatchBody->getLocEnd();
791 }
792 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
793 startLoc = finalStmt->getLocStart();
794 startBuf = SM->getCharacterData(startLoc);
795 assert((*startBuf == '@') && "bogus @finally start");
796
797 buf = "/* @finally */";
798 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
799
800 Stmt *body = finalStmt->getFinallyBody();
801 SourceLocation startLoc = body->getLocStart();
802 SourceLocation endLoc = body->getLocEnd();
803 const char *startBuf = SM->getCharacterData(startLoc);
804 const char *endBuf = SM->getCharacterData(endLoc);
805 assert((*startBuf == '{') && "bogus @finally body location");
806 assert((*endBuf == '}') && "bogus @finally body location");
807
808 startLoc = startLoc.getFileLocWithOffset(1);
809 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000810 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000811 endLoc = endLoc.getFileLocWithOffset(-1);
812 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000813 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000814
815 // Set lastCurlyLoc
816 lastCurlyLoc = body->getLocEnd();
817 }
818 // Now emit the final closing curly brace...
819 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
820 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000821 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000822 return 0;
823}
824
825Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
826 return 0;
827}
828
829Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
830 return 0;
831}
832
Steve Naroff2bd03922007-11-07 15:32:26 +0000833// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
834// the throw expression is typically a message expression that's already
835// been rewritten! (which implies the SourceLocation's are invalid).
836Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
837 // Get the start location and compute the semi location.
838 SourceLocation startLoc = S->getLocStart();
839 const char *startBuf = SM->getCharacterData(startLoc);
840
841 assert((*startBuf == '@') && "bogus @throw location");
842
843 std::string buf;
844 /* void objc_exception_throw(id) __attribute__((noreturn)); */
845 buf = "objc_exception_throw(";
846 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
847 const char *semiBuf = strchr(startBuf, ';');
848 assert((*semiBuf == ';') && "@throw: can't find ';'");
849 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
850 buf = ");";
851 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
852 return 0;
853}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000854
Chris Lattnere64b7772007-10-24 16:57:36 +0000855Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000856 // Create a new string expression.
857 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000858 std::string StrEncoding;
859 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
860 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
861 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000862 SourceLocation(), SourceLocation());
863 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000864 delete Exp;
865 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000866}
867
Steve Naroffb42f8412007-11-05 14:50:49 +0000868Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
869 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
870 // Create a call to sel_registerName("selName").
871 llvm::SmallVector<Expr*, 8> SelExprs;
872 QualType argType = Context->getPointerType(Context->CharTy);
873 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
874 Exp->getSelector().getName().size(),
875 false, argType, SourceLocation(),
876 SourceLocation()));
877 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
878 &SelExprs[0], SelExprs.size());
879 Rewrite.ReplaceStmt(Exp, SelExp);
880 delete Exp;
881 return SelExp;
882}
883
Steve Naroff934f2762007-10-24 22:48:43 +0000884CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
885 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000886 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000887 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000888
889 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000890 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000891
892 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000893 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000894 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
895
896 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000897
Steve Naroff934f2762007-10-24 22:48:43 +0000898 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
899}
900
Steve Naroffd5255f52007-11-01 13:24:47 +0000901static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
902 const char *&startRef, const char *&endRef) {
903 while (startBuf < endBuf) {
904 if (*startBuf == '<')
905 startRef = startBuf; // mark the start.
906 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000907 if (startRef && *startRef == '<') {
908 endRef = startBuf; // mark the end.
909 return true;
910 }
911 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000912 }
913 startBuf++;
914 }
915 return false;
916}
917
918bool RewriteTest::needToScanForQualifiers(QualType T) {
919 // FIXME: we don't currently represent "id <Protocol>" in the type system.
920 if (T == Context->getObjcIdType())
921 return true;
922
923 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000924 Type *pointeeType = pType->getPointeeType().getTypePtr();
925 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
926 return true; // we have "Class <Protocol> *".
927 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000928 return false;
929}
930
931void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
932 const FunctionTypeProto *proto, FunctionDecl *FD) {
933
934 if (needToScanForQualifiers(proto->getResultType())) {
935 // Since types are unique, we need to scan the buffer.
936 SourceLocation Loc = FD->getLocation();
937
938 const char *endBuf = SM->getCharacterData(Loc);
939 const char *startBuf = endBuf;
940 while (*startBuf != ';')
941 startBuf--; // scan backward (from the decl location) for return type.
942 const char *startRef = 0, *endRef = 0;
943 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
944 // Get the locations of the startRef, endRef.
945 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
946 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
947 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000948 Rewrite.InsertText(LessLoc, "/*", 2);
949 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000950 }
951 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000952 // Now check arguments.
953 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
954 if (needToScanForQualifiers(proto->getArgType(i))) {
955 // Since types are unique, we need to scan the buffer.
956 SourceLocation Loc = FD->getLocation();
957
958 const char *startBuf = SM->getCharacterData(Loc);
959 const char *endBuf = startBuf;
960 while (*endBuf != ';')
961 endBuf++; // scan forward (from the decl location) for argument types.
962 const char *startRef = 0, *endRef = 0;
963 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
964 // Get the locations of the startRef, endRef.
965 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
966 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
967 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000968 Rewrite.InsertText(LessLoc, "/*", 2);
969 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000970 }
971 }
972 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000973}
974
Steve Naroff09b266e2007-10-30 23:14:51 +0000975void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
976 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000977 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000978 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000979 return;
980 }
981 // Check for ObjC 'id' and class types that have been adorned with protocol
982 // information (id<p>, C<p>*). The protocol references need to be rewritten!
983 const FunctionType *funcType = FD->getType()->getAsFunctionType();
984 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000985 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
986 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000987}
988
989// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
990void RewriteTest::SynthMsgSendFunctionDecl() {
991 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
992 llvm::SmallVector<QualType, 16> ArgTys;
993 QualType argT = Context->getObjcIdType();
994 assert(!argT.isNull() && "Can't find 'id' type");
995 ArgTys.push_back(argT);
996 argT = Context->getObjcSelType();
997 assert(!argT.isNull() && "Can't find 'SEL' type");
998 ArgTys.push_back(argT);
999 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1000 &ArgTys[0], ArgTys.size(),
1001 true /*isVariadic*/);
1002 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1003 msgSendIdent, msgSendType,
1004 FunctionDecl::Extern, false, 0);
1005}
1006
Steve Naroff874e2322007-11-15 10:28:18 +00001007// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1008void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1009 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1010 llvm::SmallVector<QualType, 16> ArgTys;
1011 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1012 &Context->Idents.get("objc_super"), 0);
1013 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1014 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1015 ArgTys.push_back(argT);
1016 argT = Context->getObjcSelType();
1017 assert(!argT.isNull() && "Can't find 'SEL' type");
1018 ArgTys.push_back(argT);
1019 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1020 &ArgTys[0], ArgTys.size(),
1021 true /*isVariadic*/);
1022 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1023 msgSendIdent, msgSendType,
1024 FunctionDecl::Extern, false, 0);
1025}
1026
Steve Naroff09b266e2007-10-30 23:14:51 +00001027// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1028void RewriteTest::SynthGetClassFunctionDecl() {
1029 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1030 llvm::SmallVector<QualType, 16> ArgTys;
1031 ArgTys.push_back(Context->getPointerType(
1032 Context->CharTy.getQualifiedType(QualType::Const)));
1033 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1034 &ArgTys[0], ArgTys.size(),
1035 false /*isVariadic*/);
1036 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1037 getClassIdent, getClassType,
1038 FunctionDecl::Extern, false, 0);
1039}
1040
Steve Naroff96984642007-11-08 14:30:50 +00001041// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1042void RewriteTest::SynthCFStringFunctionDecl() {
1043 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1044 llvm::SmallVector<QualType, 16> ArgTys;
1045 ArgTys.push_back(Context->getPointerType(
1046 Context->CharTy.getQualifiedType(QualType::Const)));
1047 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1048 &ArgTys[0], ArgTys.size(),
1049 false /*isVariadic*/);
1050 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1051 getClassIdent, getClassType,
1052 FunctionDecl::Extern, false, 0);
1053}
1054
Steve Naroffbeaf2992007-11-03 11:27:19 +00001055Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001056#if 1
1057 // This rewrite is specific to GCC, which has builtin support for CFString.
1058 if (!CFStringFunctionDecl)
1059 SynthCFStringFunctionDecl();
1060 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1061 llvm::SmallVector<Expr*, 8> StrExpr;
1062 StrExpr.push_back(Exp->getString());
1063 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1064 &StrExpr[0], StrExpr.size());
1065 // cast to NSConstantString *
1066 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1067 Rewrite.ReplaceStmt(Exp, cast);
1068 delete Exp;
1069 return cast;
1070#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001071 assert(ConstantStringClassReference && "Can't find constant string reference");
1072 llvm::SmallVector<Expr*, 4> InitExprs;
1073
1074 // Synthesize "(Class)&_NSConstantStringClassReference"
1075 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1076 ConstantStringClassReference->getType(),
1077 SourceLocation());
1078 QualType expType = Context->getPointerType(ClsRef->getType());
1079 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1080 expType, SourceLocation());
1081 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1082 SourceLocation());
1083 InitExprs.push_back(cast); // set the 'isa'.
1084 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1085 unsigned IntSize = static_cast<unsigned>(
1086 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1087 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1088 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1089 Exp->getLocStart());
1090 InitExprs.push_back(len); // set "int numBytes".
1091
1092 // struct NSConstantString
1093 QualType CFConstantStrType = Context->getCFConstantStringType();
1094 // (struct NSConstantString) { <exprs from above> }
1095 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1096 &InitExprs[0], InitExprs.size(),
1097 SourceLocation());
1098 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1099 // struct NSConstantString *
1100 expType = Context->getPointerType(StrRep->getType());
1101 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1102 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001103 // cast to NSConstantString *
1104 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001105 Rewrite.ReplaceStmt(Exp, cast);
1106 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001107 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001108#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001109}
1110
Steve Naroff874e2322007-11-15 10:28:18 +00001111ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1112 if (CurMethodDecl) { // check if we are sending a message to 'super'
1113 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1114 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1115 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1116 if (!strcmp(PVD->getName(), "self")) {
1117 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1118 if (ObjcInterfaceType *IT =
1119 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1120 if (IT->getDecl() ==
1121 CurMethodDecl->getClassInterface()->getSuperClass())
1122 return IT->getDecl();
1123 }
1124 }
1125 }
1126 }
1127 }
1128 }
1129 }
1130 return 0;
1131}
1132
1133// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1134QualType RewriteTest::getSuperStructType() {
1135 if (!SuperStructDecl) {
1136 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1137 &Context->Idents.get("objc_super"), 0);
1138 QualType FieldTypes[2];
1139
1140 // struct objc_object *receiver;
1141 FieldTypes[0] = Context->getObjcIdType();
1142 // struct objc_class *super;
1143 FieldTypes[1] = Context->getObjcClassType();
1144 // Create fields
1145 FieldDecl *FieldDecls[2];
1146
1147 for (unsigned i = 0; i < 2; ++i)
1148 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1149
1150 SuperStructDecl->defineBody(FieldDecls, 4);
1151 }
1152 return Context->getTagDeclType(SuperStructDecl);
1153}
1154
Steve Naroff934f2762007-10-24 22:48:43 +00001155Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001156 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001157 if (!MsgSendFunctionDecl)
1158 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001159 if (!MsgSendSuperFunctionDecl)
1160 SynthMsgSendSuperFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001161 if (!GetClassFunctionDecl)
1162 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001163
Steve Naroff874e2322007-11-15 10:28:18 +00001164 // default to objc_msgSend().
1165 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1166
Steve Naroff934f2762007-10-24 22:48:43 +00001167 // Synthesize a call to objc_msgSend().
1168 llvm::SmallVector<Expr*, 8> MsgExprs;
1169 IdentifierInfo *clsName = Exp->getClassName();
1170
1171 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1172 if (clsName) { // class message.
1173 llvm::SmallVector<Expr*, 8> ClsExprs;
1174 QualType argType = Context->getPointerType(Context->CharTy);
1175 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1176 clsName->getLength(),
1177 false, argType, SourceLocation(),
1178 SourceLocation()));
1179 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1180 &ClsExprs[0], ClsExprs.size());
1181 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001182 } else { // instance message.
1183 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001184
1185 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1186 MsgSendFlavor = MsgSendSuperFunctionDecl;
1187 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1188
1189 llvm::SmallVector<Expr*, 4> InitExprs;
1190
1191 InitExprs.push_back(recExpr); // set the 'receiver'.
1192
1193 llvm::SmallVector<Expr*, 8> ClsExprs;
1194 QualType argType = Context->getPointerType(Context->CharTy);
1195 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1196 ID->getIdentifier()->getLength(),
1197 false, argType, SourceLocation(),
1198 SourceLocation()));
1199 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1200 &ClsExprs[0], ClsExprs.size());
1201 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1202 // struct objc_super
1203 QualType superType = getSuperStructType();
1204 // (struct objc_super) { <exprs from above> }
1205 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1206 &InitExprs[0], InitExprs.size(),
1207 SourceLocation());
1208 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1209 // struct objc_super *
1210 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1211 Context->getPointerType(SuperRep->getType()),
1212 SourceLocation());
1213 MsgExprs.push_back(Unop);
1214 } else {
1215 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1216 MsgExprs.push_back(recExpr);
1217 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001218 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001219 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001220 llvm::SmallVector<Expr*, 8> SelExprs;
1221 QualType argType = Context->getPointerType(Context->CharTy);
1222 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1223 Exp->getSelector().getName().size(),
1224 false, argType, SourceLocation(),
1225 SourceLocation()));
1226 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1227 &SelExprs[0], SelExprs.size());
1228 MsgExprs.push_back(SelExp);
1229
1230 // Now push any user supplied arguments.
1231 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001232 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001233 // Make all implicit casts explicit...ICE comes in handy:-)
1234 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1235 // Reuse the ICE type, it is exactly what the doctor ordered.
1236 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1237 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001238 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001239 // We've transferred the ownership to MsgExprs. Null out the argument in
1240 // the original expression, since we will delete it below.
1241 Exp->setArg(i, 0);
1242 }
Steve Naroffab972d32007-11-04 22:37:50 +00001243 // Generate the funky cast.
1244 CastExpr *cast;
1245 llvm::SmallVector<QualType, 8> ArgTypes;
1246 QualType returnType;
1247
1248 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001249 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1250 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1251 else
1252 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001253 ArgTypes.push_back(Context->getObjcSelType());
1254 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1255 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001256 for (int i = 0; i < mDecl->getNumParams(); i++) {
1257 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001258 ArgTypes.push_back(t);
1259 }
Steve Naroffab972d32007-11-04 22:37:50 +00001260 returnType = mDecl->getResultType();
1261 } else {
1262 returnType = Context->getObjcIdType();
1263 }
1264 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001265 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001266
1267 // Create a reference to the objc_msgSend() declaration.
Steve Naroff874e2322007-11-15 10:28:18 +00001268 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001269
1270 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1271 // If we don't do this cast, we get the following bizarre warning/note:
1272 // xx.m:13: warning: function called through a non-compatible type
1273 // xx.m:13: note: if this code is reached, the program will abort
1274 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1275 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001276
Steve Naroffab972d32007-11-04 22:37:50 +00001277 // Now do the "normal" pointer to function cast.
1278 QualType castType = Context->getFunctionType(returnType,
1279 &ArgTypes[0], ArgTypes.size(),
Steve Naroff335eafa2007-11-15 12:35:21 +00001280 Exp->getMethodDecl()->isVariadic());
Steve Naroffab972d32007-11-04 22:37:50 +00001281 castType = Context->getPointerType(castType);
1282 cast = new CastExpr(castType, cast, SourceLocation());
1283
1284 // Don't forget the parens to enforce the proper binding.
1285 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1286
1287 const FunctionType *FT = msgSendType->getAsFunctionType();
1288 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1289 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001290 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001291 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001292
Chris Lattnere64b7772007-10-24 16:57:36 +00001293 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001294 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001295}
1296
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001297/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1298/// an objective-c class with ivars.
1299void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1300 std::string &Result) {
1301 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1302 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001303 // Do not synthesize more than once.
1304 if (ObjcSynthesizedStructs.count(CDecl))
1305 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001306 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1307 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1308 // Do it for the root
1309 SynthesizeObjcInternalStruct(RCDecl, Result);
1310 }
1311
Steve Naroff03300712007-11-12 13:56:41 +00001312 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001313 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001314 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001315 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1316 return;
Fariborz Jahanian95673922007-11-14 22:26:25 +00001317 // FIXME: This has potential of causing problem. If
1318 // SynthesizeObjcInternalStruct is ever called recursively.
Steve Narofffea763e82007-11-14 19:25:57 +00001319 Result += "\nstruct ";
1320 Result += CDecl->getName();
1321
1322 SourceLocation LocStart = CDecl->getLocStart();
1323 SourceLocation LocEnd = CDecl->getLocEnd();
1324
1325 const char *startBuf = SM->getCharacterData(LocStart);
1326 const char *endBuf = SM->getCharacterData(LocEnd);
1327
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001328 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001329 const char *cursor = strchr(startBuf, '{');
1330 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001331 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001332
1333 // rewrite the original header *without* disturbing the '{'
1334 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1335 Result.c_str(), Result.size());
1336 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1337 Result = "\n struct ";
1338 Result += RCDecl->getName();
1339 Result += " _";
1340 Result += RCDecl->getName();
1341 Result += ";\n";
1342
1343 // insert the super class structure definition.
1344 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1345 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1346 }
1347 cursor++; // past '{'
1348
1349 // Now comment out any visibility specifiers.
1350 while (cursor < endBuf) {
1351 if (*cursor == '@') {
1352 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001353 // Skip whitespace.
1354 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1355 /*scan*/;
1356
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001357 // FIXME: presence of @public, etc. inside comment results in
1358 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001359 if (!strncmp(cursor, "public", strlen("public")) ||
1360 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001361 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001362 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001363 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001364 // FIXME: If there are cases where '<' is used in ivar declaration part
1365 // of user code, then scan the ivar list and use needToScanForQualifiers
1366 // for type checking.
1367 else if (*cursor == '<') {
1368 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1369 Rewrite.InsertText(atLoc, "/* ", 3);
1370 cursor = strchr(cursor, '>');
1371 cursor++;
1372 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1373 Rewrite.InsertText(atLoc, " */", 3);
1374 }
Steve Narofffea763e82007-11-14 19:25:57 +00001375 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001376 }
Steve Narofffea763e82007-11-14 19:25:57 +00001377 // Don't forget to add a ';'!!
1378 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1379 } else { // we don't have any instance variables - insert super struct.
1380 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1381 Result += " {\n struct ";
1382 Result += RCDecl->getName();
1383 Result += " _";
1384 Result += RCDecl->getName();
1385 Result += ";\n};\n";
1386 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1387 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001388 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001389 // Mark this struct as having been generated.
1390 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001391 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001392}
1393
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001394// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1395/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001396void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001397 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001398 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001399 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001400 const char *ClassName,
1401 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001402 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001403 if (NumMethods > 0 && !objc_impl_method) {
1404 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001405 SEL _cmd;
1406 char *method_types;
1407 void *_imp;
1408 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001409 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001410 Result += "\nstruct _objc_method {\n";
1411 Result += "\tSEL _cmd;\n";
1412 Result += "\tchar *method_types;\n";
1413 Result += "\tvoid *_imp;\n";
1414 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001415
1416 /* struct _objc_method_list {
1417 struct _objc_method_list *next_method;
1418 int method_count;
1419 struct _objc_method method_list[];
1420 }
1421 */
1422 Result += "\nstruct _objc_method_list {\n";
1423 Result += "\tstruct _objc_method_list *next_method;\n";
1424 Result += "\tint method_count;\n";
1425 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001426 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001427 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001428 // Build _objc_method_list for class's methods if needed
1429 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001430 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001431 Result += prefix;
1432 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1433 Result += "_METHODS_";
1434 Result += ClassName;
1435 Result += " __attribute__ ((section (\"__OBJC, __";
1436 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001437 Result += "_meth\")))= ";
1438 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1439
1440 Result += "\t,{{(SEL)\"";
1441 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001442 std::string MethodTypeString;
1443 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1444 Result += "\", \"";
1445 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001446 Result += "\", ";
1447 Result += MethodInternalNames[Methods[0]];
1448 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001449 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001450 Result += "\t ,{(SEL)\"";
1451 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001452 std::string MethodTypeString;
1453 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1454 Result += "\", \"";
1455 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001456 Result += "\", ";
1457 Result += MethodInternalNames[Methods[i]];
1458 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001459 }
1460 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001461 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001462}
1463
1464/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1465void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1466 int NumProtocols,
1467 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001468 const char *ClassName,
1469 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001470 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001471 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001472 for (int i = 0; i < NumProtocols; i++) {
1473 ObjcProtocolDecl *PDecl = Protocols[i];
1474 // Output struct protocol_methods holder of method selector and type.
1475 if (!objc_protocol_methods &&
1476 (PDecl->getNumInstanceMethods() > 0
1477 || PDecl->getNumClassMethods() > 0)) {
1478 /* struct protocol_methods {
1479 SEL _cmd;
1480 char *method_types;
1481 }
1482 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001483 Result += "\nstruct protocol_methods {\n";
1484 Result += "\tSEL _cmd;\n";
1485 Result += "\tchar *method_types;\n";
1486 Result += "};\n";
1487
1488 /* struct _objc_protocol_method_list {
1489 int protocol_method_count;
1490 struct protocol_methods protocols[];
1491 }
1492 */
1493 Result += "\nstruct _objc_protocol_method_list {\n";
1494 Result += "\tint protocol_method_count;\n";
1495 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001496 objc_protocol_methods = true;
1497 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001498
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001499 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001500 int NumMethods = PDecl->getNumInstanceMethods();
1501 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001502 Result += "\nstatic struct _objc_protocol_method_list "
1503 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1504 Result += PDecl->getName();
1505 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1506 "{\n\t" + utostr(NumMethods) + "\n";
1507
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001508 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001509 Result += "\t,{{(SEL)\"";
1510 Result += Methods[0]->getSelector().getName().c_str();
1511 Result += "\", \"\"}\n";
1512
1513 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001514 Result += "\t ,{(SEL)\"";
1515 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001516 std::string MethodTypeString;
1517 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1518 Result += "\", \"";
1519 Result += MethodTypeString;
1520 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001521 }
1522 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001523 }
1524
1525 // Output class methods declared in this protocol.
1526 NumMethods = PDecl->getNumClassMethods();
1527 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001528 Result += "\nstatic struct _objc_protocol_method_list "
1529 "_OBJC_PROTOCOL_CLASS_METHODS_";
1530 Result += PDecl->getName();
1531 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1532 "{\n\t";
1533 Result += utostr(NumMethods);
1534 Result += "\n";
1535
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001536 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001537 Result += "\t,{{(SEL)\"";
1538 Result += Methods[0]->getSelector().getName().c_str();
1539 Result += "\", \"\"}\n";
1540
1541 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001542 Result += "\t ,{(SEL)\"";
1543 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001544 std::string MethodTypeString;
1545 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1546 Result += "\", \"";
1547 Result += MethodTypeString;
1548 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001549 }
1550 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001551 }
1552 // Output:
1553 /* struct _objc_protocol {
1554 // Objective-C 1.0 extensions
1555 struct _objc_protocol_extension *isa;
1556 char *protocol_name;
1557 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001558 struct _objc_protocol_method_list *instance_methods;
1559 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001560 };
1561 */
1562 static bool objc_protocol = false;
1563 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001564 Result += "\nstruct _objc_protocol {\n";
1565 Result += "\tstruct _objc_protocol_extension *isa;\n";
1566 Result += "\tchar *protocol_name;\n";
1567 Result += "\tstruct _objc_protocol **protocol_list;\n";
1568 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1569 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1570 Result += "};\n";
1571
1572 /* struct _objc_protocol_list {
1573 struct _objc_protocol_list *next;
1574 int protocol_count;
1575 struct _objc_protocol *class_protocols[];
1576 }
1577 */
1578 Result += "\nstruct _objc_protocol_list {\n";
1579 Result += "\tstruct _objc_protocol_list *next;\n";
1580 Result += "\tint protocol_count;\n";
1581 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1582 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001583 objc_protocol = true;
1584 }
1585
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001586 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1587 Result += PDecl->getName();
1588 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1589 "{\n\t0, \"";
1590 Result += PDecl->getName();
1591 Result += "\", 0, ";
1592 if (PDecl->getInstanceMethods() > 0) {
1593 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1594 Result += PDecl->getName();
1595 Result += ", ";
1596 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001597 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001598 Result += "0, ";
1599 if (PDecl->getClassMethods() > 0) {
1600 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1601 Result += PDecl->getName();
1602 Result += "\n";
1603 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001604 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001605 Result += "0\n";
1606 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001607 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001608 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001609 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1610 Result += prefix;
1611 Result += "_PROTOCOLS_";
1612 Result += ClassName;
1613 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1614 "{\n\t0, ";
1615 Result += utostr(NumProtocols);
1616 Result += "\n";
1617
1618 Result += "\t,{&_OBJC_PROTOCOL_";
1619 Result += Protocols[0]->getName();
1620 Result += " \n";
1621
1622 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001623 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001624 Result += "\t ,&_OBJC_PROTOCOL_";
1625 Result += PDecl->getName();
1626 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001627 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001628 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001629 }
1630}
1631
1632/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1633/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001634void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1635 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001636 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1637 // Find category declaration for this implementation.
1638 ObjcCategoryDecl *CDecl;
1639 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1640 CDecl = CDecl->getNextClassCategory())
1641 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1642 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001643
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001644 char *FullCategoryName = (char*)alloca(
1645 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1646 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1647
1648 // Build _objc_method_list for class's instance methods if needed
1649 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1650 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001651 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001652 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001653
1654 // Build _objc_method_list for class's class methods if needed
1655 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1656 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001657 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001658 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001659
1660 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001661 // Null CDecl is case of a category implementation with no category interface
1662 if (CDecl)
1663 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1664 CDecl->getNumReferencedProtocols(),
1665 "CATEGORY",
1666 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001667
1668 /* struct _objc_category {
1669 char *category_name;
1670 char *class_name;
1671 struct _objc_method_list *instance_methods;
1672 struct _objc_method_list *class_methods;
1673 struct _objc_protocol_list *protocols;
1674 // Objective-C 1.0 extensions
1675 uint32_t size; // sizeof (struct _objc_category)
1676 struct _objc_property_list *instance_properties; // category's own
1677 // @property decl.
1678 };
1679 */
1680
1681 static bool objc_category = false;
1682 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001683 Result += "\nstruct _objc_category {\n";
1684 Result += "\tchar *category_name;\n";
1685 Result += "\tchar *class_name;\n";
1686 Result += "\tstruct _objc_method_list *instance_methods;\n";
1687 Result += "\tstruct _objc_method_list *class_methods;\n";
1688 Result += "\tstruct _objc_protocol_list *protocols;\n";
1689 Result += "\tunsigned int size;\n";
1690 Result += "\tstruct _objc_property_list *instance_properties;\n";
1691 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001692 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001693 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001694 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1695 Result += FullCategoryName;
1696 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1697 Result += IDecl->getName();
1698 Result += "\"\n\t, \"";
1699 Result += ClassDecl->getName();
1700 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001701
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001702 if (IDecl->getNumInstanceMethods() > 0) {
1703 Result += "\t, (struct _objc_method_list *)"
1704 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1705 Result += FullCategoryName;
1706 Result += "\n";
1707 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001708 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001709 Result += "\t, 0\n";
1710 if (IDecl->getNumClassMethods() > 0) {
1711 Result += "\t, (struct _objc_method_list *)"
1712 "&_OBJC_CATEGORY_CLASS_METHODS_";
1713 Result += FullCategoryName;
1714 Result += "\n";
1715 }
1716 else
1717 Result += "\t, 0\n";
1718
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001719 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001720 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1721 Result += FullCategoryName;
1722 Result += "\n";
1723 }
1724 else
1725 Result += "\t, 0\n";
1726 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001727}
1728
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001729/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1730/// ivar offset.
1731void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1732 ObjcIvarDecl *ivar,
1733 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001734 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001735 Result += IDecl->getName();
1736 Result += ", ";
1737 Result += ivar->getName();
1738 Result += ")";
1739}
1740
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001741//===----------------------------------------------------------------------===//
1742// Meta Data Emission
1743//===----------------------------------------------------------------------===//
1744
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001745void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1746 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001747 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1748
1749 // Build _objc_ivar_list metadata for classes ivars if needed
1750 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1751 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001752 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001753
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001754 SynthesizeObjcInternalStruct(CDecl, Result);
1755
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001756 if (NumIvars > 0) {
1757 static bool objc_ivar = false;
1758 if (!objc_ivar) {
1759 /* struct _objc_ivar {
1760 char *ivar_name;
1761 char *ivar_type;
1762 int ivar_offset;
1763 };
1764 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001765 Result += "\nstruct _objc_ivar {\n";
1766 Result += "\tchar *ivar_name;\n";
1767 Result += "\tchar *ivar_type;\n";
1768 Result += "\tint ivar_offset;\n";
1769 Result += "};\n";
1770
1771 /* struct _objc_ivar_list {
1772 int ivar_count;
1773 struct _objc_ivar ivar_list[];
1774 };
1775 */
1776 Result += "\nstruct _objc_ivar_list {\n";
1777 Result += "\tint ivar_count;\n";
1778 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001779 objc_ivar = true;
1780 }
1781
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001782 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1783 Result += IDecl->getName();
1784 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1785 "{\n\t";
1786 Result += utostr(NumIvars);
1787 Result += "\n";
1788
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001789 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1790 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001791 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001792 Result += "\t,{{\"";
1793 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001794 Result += "\", \"";
1795 std::string StrEncoding;
1796 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1797 Result += StrEncoding;
1798 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001799 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1800 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001801 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001802 Result += "\t ,{\"";
1803 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001804 Result += "\", \"";
1805 std::string StrEncoding;
1806 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1807 Result += StrEncoding;
1808 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001809 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1810 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001811 }
1812
1813 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001814 }
1815
1816 // Build _objc_method_list for class's instance methods if needed
1817 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1818 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001819 true,
1820 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001821
1822 // Build _objc_method_list for class's class methods if needed
1823 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001824 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001825 false,
1826 "", IDecl->getName(), Result);
1827
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001828 // Protocols referenced in class declaration?
1829 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1830 CDecl->getNumIntfRefProtocols(),
1831 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001832 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001833
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001834
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001835 // Declaration of class/meta-class metadata
1836 /* struct _objc_class {
1837 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001838 const char *super_class_name;
1839 char *name;
1840 long version;
1841 long info;
1842 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001843 struct _objc_ivar_list *ivars;
1844 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001845 struct objc_cache *cache;
1846 struct objc_protocol_list *protocols;
1847 const char *ivar_layout;
1848 struct _objc_class_ext *ext;
1849 };
1850 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001851 static bool objc_class = false;
1852 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001853 Result += "\nstruct _objc_class {\n";
1854 Result += "\tstruct _objc_class *isa;\n";
1855 Result += "\tconst char *super_class_name;\n";
1856 Result += "\tchar *name;\n";
1857 Result += "\tlong version;\n";
1858 Result += "\tlong info;\n";
1859 Result += "\tlong instance_size;\n";
1860 Result += "\tstruct _objc_ivar_list *ivars;\n";
1861 Result += "\tstruct _objc_method_list *methods;\n";
1862 Result += "\tstruct objc_cache *cache;\n";
1863 Result += "\tstruct _objc_protocol_list *protocols;\n";
1864 Result += "\tconst char *ivar_layout;\n";
1865 Result += "\tstruct _objc_class_ext *ext;\n";
1866 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001867 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001868 }
1869
1870 // Meta-class metadata generation.
1871 ObjcInterfaceDecl *RootClass = 0;
1872 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1873 while (SuperClass) {
1874 RootClass = SuperClass;
1875 SuperClass = SuperClass->getSuperClass();
1876 }
1877 SuperClass = CDecl->getSuperClass();
1878
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001879 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1880 Result += CDecl->getName();
1881 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1882 "{\n\t(struct _objc_class *)\"";
1883 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1884 Result += "\"";
1885
1886 if (SuperClass) {
1887 Result += ", \"";
1888 Result += SuperClass->getName();
1889 Result += "\", \"";
1890 Result += CDecl->getName();
1891 Result += "\"";
1892 }
1893 else {
1894 Result += ", 0, \"";
1895 Result += CDecl->getName();
1896 Result += "\"";
1897 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001898 // TODO: 'ivars' field for root class is currently set to 0.
1899 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001900 Result += ", 0,2, sizeof(struct _objc_class), 0";
1901 if (CDecl->getNumClassMethods() > 0) {
1902 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1903 Result += CDecl->getName();
1904 Result += "\n";
1905 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001906 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001907 Result += ", 0\n";
1908 if (CDecl->getNumIntfRefProtocols() > 0) {
1909 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1910 Result += CDecl->getName();
1911 Result += ",0,0\n";
1912 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001913 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001914 Result += "\t,0,0,0,0\n";
1915 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001916
1917 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001918 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1919 Result += CDecl->getName();
1920 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1921 "{\n\t&_OBJC_METACLASS_";
1922 Result += CDecl->getName();
1923 if (SuperClass) {
1924 Result += ", \"";
1925 Result += SuperClass->getName();
1926 Result += "\", \"";
1927 Result += CDecl->getName();
1928 Result += "\"";
1929 }
1930 else {
1931 Result += ", 0, \"";
1932 Result += CDecl->getName();
1933 Result += "\"";
1934 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001935 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001936 Result += ", 0,1";
1937 if (!ObjcSynthesizedStructs.count(CDecl))
1938 Result += ",0";
1939 else {
1940 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001941 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001942 Result += CDecl->getName();
1943 Result += ")";
1944 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001945 if (NumIvars > 0) {
1946 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1947 Result += CDecl->getName();
1948 Result += "\n\t";
1949 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001950 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001951 Result += ",0";
1952 if (IDecl->getNumInstanceMethods() > 0) {
1953 Result += ", &_OBJC_INSTANCE_METHODS_";
1954 Result += CDecl->getName();
1955 Result += ", 0\n\t";
1956 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001957 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001958 Result += ",0,0";
1959 if (CDecl->getNumIntfRefProtocols() > 0) {
1960 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1961 Result += CDecl->getName();
1962 Result += ", 0,0\n";
1963 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001964 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001965 Result += ",0,0,0\n";
1966 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001967}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001968
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001969/// RewriteImplementations - This routine rewrites all method implementations
1970/// and emits meta-data.
1971
1972void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001973 int ClsDefCount = ClassImplementation.size();
1974 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001975
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001976 if (ClsDefCount == 0 && CatDefCount == 0)
1977 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001978 // Rewrite implemented methods
1979 for (int i = 0; i < ClsDefCount; i++)
1980 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001981
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001982 for (int i = 0; i < CatDefCount; i++)
1983 RewriteImplementationDecl(CategoryImplementation[i]);
1984
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001985 // This is needed for use of offsetof
1986 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001987
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001988 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001989 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001990 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001991
1992 // For each implemented category, write out all its meta data.
1993 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001994 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001995
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001996 // Write objc_symtab metadata
1997 /*
1998 struct _objc_symtab
1999 {
2000 long sel_ref_cnt;
2001 SEL *refs;
2002 short cls_def_cnt;
2003 short cat_def_cnt;
2004 void *defs[cls_def_cnt + cat_def_cnt];
2005 };
2006 */
2007
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002008 Result += "\nstruct _objc_symtab {\n";
2009 Result += "\tlong sel_ref_cnt;\n";
2010 Result += "\tSEL *refs;\n";
2011 Result += "\tshort cls_def_cnt;\n";
2012 Result += "\tshort cat_def_cnt;\n";
2013 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2014 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002015
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002016 Result += "static struct _objc_symtab "
2017 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2018 Result += "\t0, 0, " + utostr(ClsDefCount)
2019 + ", " + utostr(CatDefCount) + "\n";
2020 for (int i = 0; i < ClsDefCount; i++) {
2021 Result += "\t,&_OBJC_CLASS_";
2022 Result += ClassImplementation[i]->getName();
2023 Result += "\n";
2024 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002025
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002026 for (int i = 0; i < CatDefCount; i++) {
2027 Result += "\t,&_OBJC_CATEGORY_";
2028 Result += CategoryImplementation[i]->getClassInterface()->getName();
2029 Result += "_";
2030 Result += CategoryImplementation[i]->getName();
2031 Result += "\n";
2032 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002033
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002034 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002035
2036 // Write objc_module metadata
2037
2038 /*
2039 struct _objc_module {
2040 long version;
2041 long size;
2042 const char *name;
2043 struct _objc_symtab *symtab;
2044 }
2045 */
2046
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002047 Result += "\nstruct _objc_module {\n";
2048 Result += "\tlong version;\n";
2049 Result += "\tlong size;\n";
2050 Result += "\tconst char *name;\n";
2051 Result += "\tstruct _objc_symtab *symtab;\n";
2052 Result += "};\n\n";
2053 Result += "static struct _objc_module "
2054 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002055 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2056 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002057 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002058
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002059}
Chris Lattner311ff022007-10-16 22:36:42 +00002060