blob: ac1b6d3d01c247245bc149ce6dfc05d642221aff [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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Steve Naroffebf2b562007-10-23 23:50:29 +000037
38 FunctionDecl *MsgSendFunctionDecl;
39 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000040 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000041 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000042
Steve Naroffbeaf2992007-11-03 11:27:19 +000043 // ObjC string constant support.
44 FileVarDecl *ConstantStringClassReference;
45 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000046
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000047 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000048 public:
Chris Lattner01c57482007-10-17 22:35:30 +000049 void Initialize(ASTContext &context, unsigned mainFileID) {
50 Context = &context;
51 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000052 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000053 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000054 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000055 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000056 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000057 ConstantStringClassReference = 0;
58 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000059 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000060 // declaring objc_selector outside the parameter list removes a silly
61 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000062 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000063 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000064 "(struct objc_object *, struct objc_selector *, ...);\n"
65 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +000066 "(const char *);\n"
67 "extern void objc_exception_throw(struct objc_object *);\n"
68 "extern void objc_exception_try_enter(void *);\n"
69 "extern void objc_exception_try_exit(void *);\n"
70 "extern struct objc_object *objc_exception_extract(void *);\n"
71 "extern int objc_exception_match"
72 "(struct objc_class *, struct objc_object *, ...);\n";
73
Steve Naroffab972d32007-11-04 22:37:50 +000074 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
75 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000076 }
Chris Lattner8a12c272007-10-11 18:38:32 +000077
Chris Lattnerf04da132007-10-24 17:06:59 +000078 // Top Level Driver code.
79 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000080 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000081 ~RewriteTest();
82
83 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000084 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000085 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000086 void RewriteTabs();
87 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000088 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +000089 void RewriteImplementationDecl(ObjcImplementationDecl *Dcl);
90 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +000091 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000092 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000093 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000094 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000095 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000096 void RewriteObjcQualifiedInterfaceTypes(
97 const FunctionTypeProto *proto, FunctionDecl *FD);
98 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000099
Chris Lattnerf04da132007-10-24 17:06:59 +0000100 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000101 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000102 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000103 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000104 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000105 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000106 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
107 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
108 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000109 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000110 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
111 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000112 void SynthMsgSendFunctionDecl();
113 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000114 void SynthCFStringFunctionDecl();
115
Chris Lattnerf04da132007-10-24 17:06:59 +0000116 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000117 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
118 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000119
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000120 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
121 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000122
Steve Naroff0416fb92007-11-11 17:19:15 +0000123 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000124 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000125 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000126 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000127 const char *ClassName,
128 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000129
130 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
131 int NumProtocols,
132 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000133 const char *ClassName,
134 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000135 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
136 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000137 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
138 ObjcIvarDecl *ivar,
139 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000140 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000141 };
142}
143
Chris Lattner8a12c272007-10-11 18:38:32 +0000144ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000145
Chris Lattnerf04da132007-10-24 17:06:59 +0000146//===----------------------------------------------------------------------===//
147// Top Level Driver Code
148//===----------------------------------------------------------------------===//
149
Chris Lattner8a12c272007-10-11 18:38:32 +0000150void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000151 // Two cases: either the decl could be in the main file, or it could be in a
152 // #included file. If the former, rewrite it now. If the later, check to see
153 // if we rewrote the #include/#import.
154 SourceLocation Loc = D->getLocation();
155 Loc = SM->getLogicalLoc(Loc);
156
157 // If this is for a builtin, ignore it.
158 if (Loc.isInvalid()) return;
159
Steve Naroffebf2b562007-10-23 23:50:29 +0000160 // Look for built-in declarations that we need to refer during the rewrite.
161 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000162 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000163 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
164 // declared in <Foundation/NSString.h>
165 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
166 ConstantStringClassReference = FVD;
167 return;
168 }
Steve Naroffbef11852007-10-26 20:53:56 +0000169 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
170 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000171 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
172 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000173 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
174 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000175 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000176 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000177 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
178 return HandleDeclInMainFile(D);
179
Chris Lattnerf04da132007-10-24 17:06:59 +0000180 // Otherwise, see if there is a #import in the main file that should be
181 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000182 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000183}
184
Chris Lattnerf04da132007-10-24 17:06:59 +0000185/// HandleDeclInMainFile - This is called for each top-level decl defined in the
186/// main file of the input.
187void RewriteTest::HandleDeclInMainFile(Decl *D) {
188 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
189 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000190 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Chris Lattnerf04da132007-10-24 17:06:59 +0000191
192 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
193 ClassImplementation.push_back(CI);
194 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
195 CategoryImplementation.push_back(CI);
196 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
197 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000198 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
199 if (VD->getInit())
200 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
201 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000202 // Nothing yet.
203}
204
205RewriteTest::~RewriteTest() {
206 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000207
208 // Rewrite tabs if we care.
209 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000210
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000211 // Rewrite Objective-c meta data*
212 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000213 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000214
Chris Lattnerf04da132007-10-24 17:06:59 +0000215 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
216 // we are done.
217 if (const RewriteBuffer *RewriteBuf =
218 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000219 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000220 std::string S(RewriteBuf->begin(), RewriteBuf->end());
221 printf("%s\n", S.c_str());
222 } else {
223 printf("No changes\n");
224 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000225 // Emit metadata.
226 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000227}
228
Chris Lattnerf04da132007-10-24 17:06:59 +0000229//===----------------------------------------------------------------------===//
230// Syntactic (non-AST) Rewriting Code
231//===----------------------------------------------------------------------===//
232
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000233void RewriteTest::RewriteInclude(SourceLocation Loc) {
234 // Rip up the #include stack to the main file.
235 SourceLocation IncLoc = Loc, NextLoc = Loc;
236 do {
237 IncLoc = Loc;
238 Loc = SM->getLogicalLoc(NextLoc);
239 NextLoc = SM->getIncludeLoc(Loc);
240 } while (!NextLoc.isInvalid());
241
242 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
243 // IncLoc indicates the header that was included if it is useful.
244 IncLoc = SM->getLogicalLoc(IncLoc);
245 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
246 Loc == LastIncLoc)
247 return;
248 LastIncLoc = Loc;
249
250 unsigned IncCol = SM->getColumnNumber(Loc);
251 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
252
253 // Replace the #import with #include.
254 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
255}
256
Chris Lattnerf04da132007-10-24 17:06:59 +0000257void RewriteTest::RewriteTabs() {
258 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
259 const char *MainBufStart = MainBuf.first;
260 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000261
Chris Lattnerf04da132007-10-24 17:06:59 +0000262 // Loop over the whole file, looking for tabs.
263 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
264 if (*BufPtr != '\t')
265 continue;
266
267 // Okay, we found a tab. This tab will turn into at least one character,
268 // but it depends on which 'virtual column' it is in. Compute that now.
269 unsigned VCol = 0;
270 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
271 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
272 ++VCol;
273
274 // Okay, now that we know the virtual column, we know how many spaces to
275 // insert. We assume 8-character tab-stops.
276 unsigned Spaces = 8-(VCol & 7);
277
278 // Get the location of the tab.
279 SourceLocation TabLoc =
280 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
281
282 // Rewrite the single tab character into a sequence of spaces.
283 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
284 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000285}
286
287
Chris Lattnerf04da132007-10-24 17:06:59 +0000288void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
289 int numDecls = ClassDecl->getNumForwardDecls();
290 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
291
292 // Get the start location and compute the semi location.
293 SourceLocation startLoc = ClassDecl->getLocation();
294 const char *startBuf = SM->getCharacterData(startLoc);
295 const char *semiPtr = strchr(startBuf, ';');
296
297 // Translate to typedef's that forward reference structs with the same name
298 // as the class. As a convenience, we include the original declaration
299 // as a comment.
300 std::string typedefString;
301 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000302 typedefString.append(startBuf, semiPtr-startBuf+1);
303 typedefString += "\n";
304 for (int i = 0; i < numDecls; i++) {
305 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000306 if (ObjcForwardDecls.count(ForwardDecl))
307 continue;
Steve Naroff32174822007-11-09 12:50:28 +0000308 typedefString += "#ifndef _REWRITER_typedef_";
309 typedefString += ForwardDecl->getName();
310 typedefString += "\n";
311 typedefString += "#define _REWRITER_typedef_";
312 typedefString += ForwardDecl->getName();
313 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000314 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000315 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000316 typedefString += ";\n#endif\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000317 // Mark this typedef as having been generated.
318 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000319 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000320 }
321
322 // Replace the @class with typedefs corresponding to the classes.
323 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
324 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000325}
326
Steve Naroff423cb562007-10-30 13:30:57 +0000327void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
328 for (int i = 0; i < nMethods; i++) {
329 ObjcMethodDecl *Method = Methods[i];
330 SourceLocation Loc = Method->getLocStart();
331
Chris Lattner28d1fe82007-11-08 04:41:51 +0000332 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000333
334 // FIXME: handle methods that are declared across multiple lines.
335 }
336}
337
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000338void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
339{
340 for (int i = 0; i < nProperties; i++) {
341 ObjcPropertyDecl *Property = Properties[i];
342 SourceLocation Loc = Property->getLocation();
343
344 Rewrite.ReplaceText(Loc, 0, "// ", 3);
345
346 // FIXME: handle properties that are declared across multiple lines.
347 }
348}
349
Steve Naroff423cb562007-10-30 13:30:57 +0000350void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
351 SourceLocation LocStart = CatDecl->getLocStart();
352
353 // FIXME: handle category headers that are declared across multiple lines.
354 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
355
356 RewriteMethods(CatDecl->getNumInstanceMethods(),
357 CatDecl->getInstanceMethods());
358 RewriteMethods(CatDecl->getNumClassMethods(),
359 CatDecl->getClassMethods());
360 // Lastly, comment out the @end.
361 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
362}
363
Steve Naroff752d6ef2007-10-30 16:42:30 +0000364void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
365 SourceLocation LocStart = PDecl->getLocStart();
366
367 // FIXME: handle protocol headers that are declared across multiple lines.
368 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
369
370 RewriteMethods(PDecl->getNumInstanceMethods(),
371 PDecl->getInstanceMethods());
372 RewriteMethods(PDecl->getNumClassMethods(),
373 PDecl->getClassMethods());
374 // Lastly, comment out the @end.
375 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
376}
377
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000378void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
379 std::string &ResultStr) {
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000380 static bool includeObjc = false;
381 if (!includeObjc) {
382 ResultStr += "#include <Objc/objc.h>\n";
383 includeObjc = true;
384 }
385
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000386 ResultStr += "\nstatic ";
387 ResultStr += OMD->getResultType().getAsString();
388 ResultStr += "\n_";
389
390 // Unique method name
391 if (OMD->isInstance())
392 ResultStr += "I_";
393 else
394 ResultStr += "C_";
395
396 ResultStr += OMD->getClassInterface()->getName();
397 ResultStr += "_";
398
399 NamedDecl *MethodContext = OMD->getMethodContext();
400 if (ObjcCategoryImplDecl *CID =
401 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
402 ResultStr += CID->getName();
403 ResultStr += "_";
404 }
405 // Append selector names, replacing ':' with '_'
406 const char *selName = OMD->getSelector().getName().c_str();
407 if (!strchr(selName, ':'))
408 ResultStr += OMD->getSelector().getName();
409 else {
410 std::string selString = OMD->getSelector().getName();
411 int len = selString.size();
412 for (int i = 0; i < len; i++)
413 if (selString[i] == ':')
414 selString[i] = '_';
415 ResultStr += selString;
416 }
417
418 // Rewrite arguments
419 ResultStr += "(";
420
421 // invisible arguments
422 if (OMD->isInstance()) {
423 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
424 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000425 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000426 ResultStr += selfTy.getAsString();
427 }
428 else
429 ResultStr += Context->getObjcIdType().getAsString();
430
431 ResultStr += " self, ";
432 ResultStr += Context->getObjcSelType().getAsString();
433 ResultStr += " _cmd";
434
435 // Method arguments.
436 for (int i = 0; i < OMD->getNumParams(); i++) {
437 ParmVarDecl *PDecl = OMD->getParamDecl(i);
438 ResultStr += ", ";
439 ResultStr += PDecl->getType().getAsString();
440 ResultStr += " ";
441 ResultStr += PDecl->getName();
442 }
443 ResultStr += ")";
444
445}
446void RewriteTest::RewriteImplementationDecl(ObjcImplementationDecl *OID) {
447
448 Rewrite.InsertText(OID->getLocStart(), "// ", 3);
449
450 for (int i = 0; i < OID->getNumInstanceMethods(); i++) {
451 std::string ResultStr;
452 ObjcMethodDecl *OMD = OID->getInstanceMethods()[i];
453 RewriteObjcMethodDecl(OMD, ResultStr);
454 SourceLocation LocStart = OMD->getLocStart();
455 SourceLocation LocEnd = OMD->getBody()->getLocStart();
456
457 const char *startBuf = SM->getCharacterData(LocStart);
458 const char *endBuf = SM->getCharacterData(LocEnd);
459 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
460 ResultStr.c_str(), ResultStr.size());
461 }
462
463 for (int i = 0; i < OID->getNumClassMethods(); i++) {
464 std::string ResultStr;
465 ObjcMethodDecl *OMD = OID->getClassMethods()[i];
466 RewriteObjcMethodDecl(OMD, ResultStr);
467 SourceLocation LocStart = OMD->getLocStart();
468 SourceLocation LocEnd = OMD->getBody()->getLocStart();
469
470 const char *startBuf = SM->getCharacterData(LocStart);
471 const char *endBuf = SM->getCharacterData(LocEnd);
472 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
473 ResultStr.c_str(), ResultStr.size());
474 }
475 Rewrite.InsertText(OID->getLocEnd(), "// ", 3);
476}
477
Steve Naroffbef11852007-10-26 20:53:56 +0000478void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000479
480 SourceLocation LocStart = ClassDecl->getLocStart();
481 SourceLocation LocEnd = ClassDecl->getLocEnd();
482
483 const char *startBuf = SM->getCharacterData(LocStart);
484 const char *endBuf = SM->getCharacterData(LocEnd);
485
Steve Naroff2feac5e2007-10-30 03:43:13 +0000486 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000487
488 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000489 if (!ObjcForwardDecls.count(ClassDecl)) {
490 // we haven't seen a forward decl - generate a typedef.
Steve Naroff32174822007-11-09 12:50:28 +0000491 ResultStr += "#ifndef _REWRITER_typedef_";
492 ResultStr += ClassDecl->getName();
493 ResultStr += "\n";
494 ResultStr += "#define _REWRITER_typedef_";
495 ResultStr += ClassDecl->getName();
496 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000497 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000498 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000499 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000500
501 // Mark this typedef as having been generated.
502 ObjcForwardDecls.insert(ClassDecl);
503 }
Steve Narofff908a872007-10-30 02:23:23 +0000504 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
505
Steve Naroff2feac5e2007-10-30 03:43:13 +0000506 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000507 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000508 RewriteProperties(ClassDecl->getNumPropertyDecl(),
509 ClassDecl->getPropertyDecl());
Steve Naroff423cb562007-10-30 13:30:57 +0000510 RewriteMethods(ClassDecl->getNumInstanceMethods(),
511 ClassDecl->getInstanceMethods());
512 RewriteMethods(ClassDecl->getNumClassMethods(),
513 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000514
Steve Naroff2feac5e2007-10-30 03:43:13 +0000515 // Lastly, comment out the @end.
516 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000517}
518
Chris Lattnerf04da132007-10-24 17:06:59 +0000519//===----------------------------------------------------------------------===//
520// Function Body / Expression rewriting
521//===----------------------------------------------------------------------===//
522
Steve Narofff3473a72007-11-09 15:20:18 +0000523Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000524 // Otherwise, just rewrite all children.
525 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
526 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000527 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000528 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000529 if (newStmt)
530 *CI = newStmt;
531 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000532
533 // Handle specific things.
534 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
535 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000536
537 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
538 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000539
540 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
541 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000542
Steve Naroff934f2762007-10-24 22:48:43 +0000543 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
544 // Before we rewrite it, put the original message expression in a comment.
545 SourceLocation startLoc = MessExpr->getLocStart();
546 SourceLocation endLoc = MessExpr->getLocEnd();
547
548 const char *startBuf = SM->getCharacterData(startLoc);
549 const char *endBuf = SM->getCharacterData(endLoc);
550
551 std::string messString;
552 messString += "// ";
553 messString.append(startBuf, endBuf-startBuf+1);
554 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000555
Steve Naroff934f2762007-10-24 22:48:43 +0000556 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
557 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
558 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000559 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000560 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000561 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000562
563 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
564 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000565
566 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
567 return RewriteObjcThrowStmt(StmtThrow);
568
Chris Lattnere64b7772007-10-24 16:57:36 +0000569 // Return this stmt unmodified.
570 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000571}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000572
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000573Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000574 // Get the start location and compute the semi location.
575 SourceLocation startLoc = S->getLocStart();
576 const char *startBuf = SM->getCharacterData(startLoc);
577
578 assert((*startBuf == '@') && "bogus @try location");
579
580 std::string buf;
581 // declare a new scope with two variables, _stack and _rethrow.
582 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
583 buf += "int buf[18/*32-bit i386*/];\n";
584 buf += "char *pointers[4];} _stack;\n";
585 buf += "id volatile _rethrow = 0;\n";
586 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000587 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000588
589 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
590
591 startLoc = S->getTryBody()->getLocEnd();
592 startBuf = SM->getCharacterData(startLoc);
593
594 assert((*startBuf == '}') && "bogus @try block");
595
596 SourceLocation lastCurlyLoc = startLoc;
597
598 startLoc = startLoc.getFileLocWithOffset(1);
599 buf = " /* @catch begin */ else {\n";
600 buf += " id _caught = objc_exception_extract(&_stack);\n";
601 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000602 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000603 buf += " _rethrow = objc_exception_extract(&_stack);\n";
604 buf += " else { /* @catch continue */";
605
Chris Lattner28d1fe82007-11-08 04:41:51 +0000606 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000607
608 bool sawIdTypedCatch = false;
609 Stmt *lastCatchBody = 0;
610 ObjcAtCatchStmt *catchList = S->getCatchStmts();
611 while (catchList) {
612 Stmt *catchStmt = catchList->getCatchParamStmt();
613
614 if (catchList == S->getCatchStmts())
615 buf = "if ("; // we are generating code for the first catch clause
616 else
617 buf = "else if (";
618 startLoc = catchList->getLocStart();
619 startBuf = SM->getCharacterData(startLoc);
620
621 assert((*startBuf == '@') && "bogus @catch location");
622
623 const char *lParenLoc = strchr(startBuf, '(');
624
625 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
626 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
627 if (t == Context->getObjcIdType()) {
628 buf += "1) { ";
629 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
630 buf.c_str(), buf.size());
631 sawIdTypedCatch = true;
632 } else if (const PointerType *pType = t->getAsPointerType()) {
633 ObjcInterfaceType *cls; // Should be a pointer to a class.
634
635 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
636 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000637 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000638 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000639 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000640 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
641 buf.c_str(), buf.size());
642 }
643 }
644 // Now rewrite the body...
645 lastCatchBody = catchList->getCatchBody();
646 SourceLocation rParenLoc = catchList->getRParenLoc();
647 SourceLocation bodyLoc = lastCatchBody->getLocStart();
648 const char *bodyBuf = SM->getCharacterData(bodyLoc);
649 const char *rParenBuf = SM->getCharacterData(rParenLoc);
650 assert((*rParenBuf == ')') && "bogus @catch paren location");
651 assert((*bodyBuf == '{') && "bogus @catch body location");
652
653 buf = " = _caught;";
654 // Here we replace ") {" with "= _caught;" (which initializes and
655 // declares the @catch parameter).
656 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
657 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000658 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000659 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000660 }
Steve Naroff75730982007-11-07 04:08:17 +0000661 catchList = catchList->getNextCatchStmt();
662 }
663 // Complete the catch list...
664 if (lastCatchBody) {
665 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
666 const char *bodyBuf = SM->getCharacterData(bodyLoc);
667 assert((*bodyBuf == '}') && "bogus @catch body location");
668 bodyLoc = bodyLoc.getFileLocWithOffset(1);
669 buf = " } } /* @catch end */\n";
670
Chris Lattner28d1fe82007-11-08 04:41:51 +0000671 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000672
673 // Set lastCurlyLoc
674 lastCurlyLoc = lastCatchBody->getLocEnd();
675 }
676 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
677 startLoc = finalStmt->getLocStart();
678 startBuf = SM->getCharacterData(startLoc);
679 assert((*startBuf == '@') && "bogus @finally start");
680
681 buf = "/* @finally */";
682 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
683
684 Stmt *body = finalStmt->getFinallyBody();
685 SourceLocation startLoc = body->getLocStart();
686 SourceLocation endLoc = body->getLocEnd();
687 const char *startBuf = SM->getCharacterData(startLoc);
688 const char *endBuf = SM->getCharacterData(endLoc);
689 assert((*startBuf == '{') && "bogus @finally body location");
690 assert((*endBuf == '}') && "bogus @finally body location");
691
692 startLoc = startLoc.getFileLocWithOffset(1);
693 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000694 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000695 endLoc = endLoc.getFileLocWithOffset(-1);
696 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000697 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000698
699 // Set lastCurlyLoc
700 lastCurlyLoc = body->getLocEnd();
701 }
702 // Now emit the final closing curly brace...
703 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
704 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000705 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000706 return 0;
707}
708
709Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
710 return 0;
711}
712
713Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
714 return 0;
715}
716
Steve Naroff2bd03922007-11-07 15:32:26 +0000717// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
718// the throw expression is typically a message expression that's already
719// been rewritten! (which implies the SourceLocation's are invalid).
720Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
721 // Get the start location and compute the semi location.
722 SourceLocation startLoc = S->getLocStart();
723 const char *startBuf = SM->getCharacterData(startLoc);
724
725 assert((*startBuf == '@') && "bogus @throw location");
726
727 std::string buf;
728 /* void objc_exception_throw(id) __attribute__((noreturn)); */
729 buf = "objc_exception_throw(";
730 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
731 const char *semiBuf = strchr(startBuf, ';');
732 assert((*semiBuf == ';') && "@throw: can't find ';'");
733 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
734 buf = ");";
735 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
736 return 0;
737}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000738
Chris Lattnere64b7772007-10-24 16:57:36 +0000739Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000740 // Create a new string expression.
741 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000742 std::string StrEncoding;
743 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
744 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
745 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000746 SourceLocation(), SourceLocation());
747 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000748 delete Exp;
749 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000750}
751
Steve Naroffb42f8412007-11-05 14:50:49 +0000752Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
753 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
754 // Create a call to sel_registerName("selName").
755 llvm::SmallVector<Expr*, 8> SelExprs;
756 QualType argType = Context->getPointerType(Context->CharTy);
757 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
758 Exp->getSelector().getName().size(),
759 false, argType, SourceLocation(),
760 SourceLocation()));
761 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
762 &SelExprs[0], SelExprs.size());
763 Rewrite.ReplaceStmt(Exp, SelExp);
764 delete Exp;
765 return SelExp;
766}
767
Steve Naroff934f2762007-10-24 22:48:43 +0000768CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
769 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000770 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000771 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000772
773 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000774 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000775
776 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000777 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000778 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
779
780 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000781
Steve Naroff934f2762007-10-24 22:48:43 +0000782 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
783}
784
Steve Naroffd5255f52007-11-01 13:24:47 +0000785static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
786 const char *&startRef, const char *&endRef) {
787 while (startBuf < endBuf) {
788 if (*startBuf == '<')
789 startRef = startBuf; // mark the start.
790 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000791 if (startRef && *startRef == '<') {
792 endRef = startBuf; // mark the end.
793 return true;
794 }
795 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000796 }
797 startBuf++;
798 }
799 return false;
800}
801
802bool RewriteTest::needToScanForQualifiers(QualType T) {
803 // FIXME: we don't currently represent "id <Protocol>" in the type system.
804 if (T == Context->getObjcIdType())
805 return true;
806
807 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000808 Type *pointeeType = pType->getPointeeType().getTypePtr();
809 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
810 return true; // we have "Class <Protocol> *".
811 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000812 return false;
813}
814
815void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
816 const FunctionTypeProto *proto, FunctionDecl *FD) {
817
818 if (needToScanForQualifiers(proto->getResultType())) {
819 // Since types are unique, we need to scan the buffer.
820 SourceLocation Loc = FD->getLocation();
821
822 const char *endBuf = SM->getCharacterData(Loc);
823 const char *startBuf = endBuf;
824 while (*startBuf != ';')
825 startBuf--; // scan backward (from the decl location) for return type.
826 const char *startRef = 0, *endRef = 0;
827 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
828 // Get the locations of the startRef, endRef.
829 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
830 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
831 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000832 Rewrite.InsertText(LessLoc, "/*", 2);
833 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000834 }
835 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000836 // Now check arguments.
837 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
838 if (needToScanForQualifiers(proto->getArgType(i))) {
839 // Since types are unique, we need to scan the buffer.
840 SourceLocation Loc = FD->getLocation();
841
842 const char *startBuf = SM->getCharacterData(Loc);
843 const char *endBuf = startBuf;
844 while (*endBuf != ';')
845 endBuf++; // scan forward (from the decl location) for argument types.
846 const char *startRef = 0, *endRef = 0;
847 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
848 // Get the locations of the startRef, endRef.
849 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
850 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
851 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000852 Rewrite.InsertText(LessLoc, "/*", 2);
853 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000854 }
855 }
856 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000857}
858
Steve Naroff09b266e2007-10-30 23:14:51 +0000859void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
860 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000861 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000862 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000863 return;
864 }
865 // Check for ObjC 'id' and class types that have been adorned with protocol
866 // information (id<p>, C<p>*). The protocol references need to be rewritten!
867 const FunctionType *funcType = FD->getType()->getAsFunctionType();
868 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000869 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
870 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000871}
872
873// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
874void RewriteTest::SynthMsgSendFunctionDecl() {
875 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
876 llvm::SmallVector<QualType, 16> ArgTys;
877 QualType argT = Context->getObjcIdType();
878 assert(!argT.isNull() && "Can't find 'id' type");
879 ArgTys.push_back(argT);
880 argT = Context->getObjcSelType();
881 assert(!argT.isNull() && "Can't find 'SEL' type");
882 ArgTys.push_back(argT);
883 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
884 &ArgTys[0], ArgTys.size(),
885 true /*isVariadic*/);
886 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
887 msgSendIdent, msgSendType,
888 FunctionDecl::Extern, false, 0);
889}
890
891// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
892void RewriteTest::SynthGetClassFunctionDecl() {
893 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
894 llvm::SmallVector<QualType, 16> ArgTys;
895 ArgTys.push_back(Context->getPointerType(
896 Context->CharTy.getQualifiedType(QualType::Const)));
897 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
898 &ArgTys[0], ArgTys.size(),
899 false /*isVariadic*/);
900 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
901 getClassIdent, getClassType,
902 FunctionDecl::Extern, false, 0);
903}
904
Steve Naroff96984642007-11-08 14:30:50 +0000905// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
906void RewriteTest::SynthCFStringFunctionDecl() {
907 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
908 llvm::SmallVector<QualType, 16> ArgTys;
909 ArgTys.push_back(Context->getPointerType(
910 Context->CharTy.getQualifiedType(QualType::Const)));
911 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
912 &ArgTys[0], ArgTys.size(),
913 false /*isVariadic*/);
914 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
915 getClassIdent, getClassType,
916 FunctionDecl::Extern, false, 0);
917}
918
Steve Naroffbeaf2992007-11-03 11:27:19 +0000919Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000920#if 1
921 // This rewrite is specific to GCC, which has builtin support for CFString.
922 if (!CFStringFunctionDecl)
923 SynthCFStringFunctionDecl();
924 // Create a call to __builtin___CFStringMakeConstantString("cstr").
925 llvm::SmallVector<Expr*, 8> StrExpr;
926 StrExpr.push_back(Exp->getString());
927 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
928 &StrExpr[0], StrExpr.size());
929 // cast to NSConstantString *
930 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
931 Rewrite.ReplaceStmt(Exp, cast);
932 delete Exp;
933 return cast;
934#else
Steve Naroffbeaf2992007-11-03 11:27:19 +0000935 assert(ConstantStringClassReference && "Can't find constant string reference");
936 llvm::SmallVector<Expr*, 4> InitExprs;
937
938 // Synthesize "(Class)&_NSConstantStringClassReference"
939 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
940 ConstantStringClassReference->getType(),
941 SourceLocation());
942 QualType expType = Context->getPointerType(ClsRef->getType());
943 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
944 expType, SourceLocation());
945 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
946 SourceLocation());
947 InitExprs.push_back(cast); // set the 'isa'.
948 InitExprs.push_back(Exp->getString()); // set "char *bytes".
949 unsigned IntSize = static_cast<unsigned>(
950 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
951 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
952 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
953 Exp->getLocStart());
954 InitExprs.push_back(len); // set "int numBytes".
955
956 // struct NSConstantString
957 QualType CFConstantStrType = Context->getCFConstantStringType();
958 // (struct NSConstantString) { <exprs from above> }
959 InitListExpr *ILE = new InitListExpr(SourceLocation(),
960 &InitExprs[0], InitExprs.size(),
961 SourceLocation());
962 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
963 // struct NSConstantString *
964 expType = Context->getPointerType(StrRep->getType());
965 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
966 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000967 // cast to NSConstantString *
968 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000969 Rewrite.ReplaceStmt(Exp, cast);
970 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000971 return cast;
Steve Naroff96984642007-11-08 14:30:50 +0000972#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +0000973}
974
Steve Naroff934f2762007-10-24 22:48:43 +0000975Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000976 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000977 if (!MsgSendFunctionDecl)
978 SynthMsgSendFunctionDecl();
979 if (!GetClassFunctionDecl)
980 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000981
982 // Synthesize a call to objc_msgSend().
983 llvm::SmallVector<Expr*, 8> MsgExprs;
984 IdentifierInfo *clsName = Exp->getClassName();
985
986 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
987 if (clsName) { // class message.
988 llvm::SmallVector<Expr*, 8> ClsExprs;
989 QualType argType = Context->getPointerType(Context->CharTy);
990 ClsExprs.push_back(new StringLiteral(clsName->getName(),
991 clsName->getLength(),
992 false, argType, SourceLocation(),
993 SourceLocation()));
994 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
995 &ClsExprs[0], ClsExprs.size());
996 MsgExprs.push_back(Cls);
997 } else // instance message.
998 MsgExprs.push_back(Exp->getReceiver());
999
Steve Naroffbeaf2992007-11-03 11:27:19 +00001000 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001001 llvm::SmallVector<Expr*, 8> SelExprs;
1002 QualType argType = Context->getPointerType(Context->CharTy);
1003 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1004 Exp->getSelector().getName().size(),
1005 false, argType, SourceLocation(),
1006 SourceLocation()));
1007 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1008 &SelExprs[0], SelExprs.size());
1009 MsgExprs.push_back(SelExp);
1010
1011 // Now push any user supplied arguments.
1012 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1013 MsgExprs.push_back(Exp->getArg(i));
1014 // We've transferred the ownership to MsgExprs. Null out the argument in
1015 // the original expression, since we will delete it below.
1016 Exp->setArg(i, 0);
1017 }
Steve Naroffab972d32007-11-04 22:37:50 +00001018 // Generate the funky cast.
1019 CastExpr *cast;
1020 llvm::SmallVector<QualType, 8> ArgTypes;
1021 QualType returnType;
1022
1023 // Push 'id' and 'SEL', the 2 implicit arguments.
1024 ArgTypes.push_back(Context->getObjcIdType());
1025 ArgTypes.push_back(Context->getObjcSelType());
1026 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1027 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001028 for (int i = 0; i < mDecl->getNumParams(); i++) {
1029 QualType t = mDecl->getParamDecl(i)->getType();
1030 if (t == Context->getObjcClassType())
1031 t = Context->getObjcIdType(); // Convert "Class"->"id"
1032 ArgTypes.push_back(t);
1033 }
Steve Naroffab972d32007-11-04 22:37:50 +00001034 returnType = mDecl->getResultType();
1035 } else {
1036 returnType = Context->getObjcIdType();
1037 }
1038 // Get the type, we will need to reference it in a couple spots.
1039 QualType msgSendType = MsgSendFunctionDecl->getType();
1040
1041 // Create a reference to the objc_msgSend() declaration.
1042 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1043
1044 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1045 // If we don't do this cast, we get the following bizarre warning/note:
1046 // xx.m:13: warning: function called through a non-compatible type
1047 // xx.m:13: note: if this code is reached, the program will abort
1048 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1049 SourceLocation());
1050
1051 // Now do the "normal" pointer to function cast.
1052 QualType castType = Context->getFunctionType(returnType,
1053 &ArgTypes[0], ArgTypes.size(),
1054 false/*FIXME:variadic*/);
1055 castType = Context->getPointerType(castType);
1056 cast = new CastExpr(castType, cast, SourceLocation());
1057
1058 // Don't forget the parens to enforce the proper binding.
1059 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1060
1061 const FunctionType *FT = msgSendType->getAsFunctionType();
1062 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1063 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001064 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001065 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001066
Chris Lattnere64b7772007-10-24 16:57:36 +00001067 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001068 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001069}
1070
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001071/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1072/// an objective-c class with ivars.
1073void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1074 std::string &Result) {
1075 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1076 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001077 // Do not synthesize more than once.
1078 if (ObjcSynthesizedStructs.count(CDecl))
1079 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001080 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1081 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1082 // Do it for the root
1083 SynthesizeObjcInternalStruct(RCDecl, Result);
1084 }
1085
Steve Naroff03300712007-11-12 13:56:41 +00001086 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001087 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001088 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001089 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1090 return;
1091
Steve Naroff04960052007-11-01 17:12:31 +00001092 Result += "\nstruct ";
1093 Result += CDecl->getName();
1094 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1095 Result += " {\n struct ";
1096 Result += RCDecl->getName();
1097 Result += " _";
1098 Result += RCDecl->getName();
1099 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001100 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001101 else
1102 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +00001103
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001104 if (NumIvars > 0) {
1105 SourceLocation LocStart = CDecl->getLocStart();
1106 SourceLocation LocEnd = CDecl->getLocEnd();
1107
1108 const char *startBuf = SM->getCharacterData(LocStart);
1109 const char *endBuf = SM->getCharacterData(LocEnd);
1110 startBuf = strchr(startBuf, '{');
1111 assert((startBuf && endBuf)
1112 && "SynthesizeObjcInternalStruct - malformed @interface");
1113 startBuf++; // past '{'
1114 while (startBuf < endBuf) {
1115 if (*startBuf == '@') {
1116 startBuf = strchr(startBuf, 'p');
1117 // FIXME: presence of @public, etc. inside comment results in
1118 // this transformation as well, which is still correct c-code.
1119 if (!strncmp(startBuf, "public", strlen("public"))) {
1120 startBuf += strlen("public");
1121 Result += "/* @public */";
1122 }
1123 else if (!strncmp(startBuf, "private", strlen("private"))) {
1124 startBuf += strlen("private");
1125 Result += "/* @private */";
1126 }
1127 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1128 startBuf += strlen("protected");
1129 Result += "/* @protected */";
1130 }
1131 }
1132 Result += *startBuf++;
1133 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001134 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001135
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001136 Result += "};\n";
1137 // Mark this struct as having been generated.
1138 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001139 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001140}
1141
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001142// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1143/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001144void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001145 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001146 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001147 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001148 const char *ClassName,
1149 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001150 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001151 if (NumMethods > 0 && !objc_impl_method) {
1152 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001153 SEL _cmd;
1154 char *method_types;
1155 void *_imp;
1156 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001157 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001158 Result += "\nstruct _objc_method {\n";
1159 Result += "\tSEL _cmd;\n";
1160 Result += "\tchar *method_types;\n";
1161 Result += "\tvoid *_imp;\n";
1162 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001163
1164 /* struct _objc_method_list {
1165 struct _objc_method_list *next_method;
1166 int method_count;
1167 struct _objc_method method_list[];
1168 }
1169 */
1170 Result += "\nstruct _objc_method_list {\n";
1171 Result += "\tstruct _objc_method_list *next_method;\n";
1172 Result += "\tint method_count;\n";
1173 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001174 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001175 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001176 // Build _objc_method_list for class's methods if needed
1177 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001178 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001179 Result += prefix;
1180 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1181 Result += "_METHODS_";
1182 Result += ClassName;
1183 Result += " __attribute__ ((section (\"__OBJC, __";
1184 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001185 Result += "_meth\")))= ";
1186 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1187
1188 Result += "\t,{{(SEL)\"";
1189 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001190 std::string MethodTypeString;
1191 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1192 Result += "\", \"";
1193 Result += MethodTypeString;
1194 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001195 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001196 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001197 Result += "\t ,{(SEL)\"";
1198 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001199 std::string MethodTypeString;
1200 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1201 Result += "\", \"";
1202 Result += MethodTypeString;
1203 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001204 }
1205 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001206 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001207}
1208
1209/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1210void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1211 int NumProtocols,
1212 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001213 const char *ClassName,
1214 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001215 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001216 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001217 for (int i = 0; i < NumProtocols; i++) {
1218 ObjcProtocolDecl *PDecl = Protocols[i];
1219 // Output struct protocol_methods holder of method selector and type.
1220 if (!objc_protocol_methods &&
1221 (PDecl->getNumInstanceMethods() > 0
1222 || PDecl->getNumClassMethods() > 0)) {
1223 /* struct protocol_methods {
1224 SEL _cmd;
1225 char *method_types;
1226 }
1227 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001228 Result += "\nstruct protocol_methods {\n";
1229 Result += "\tSEL _cmd;\n";
1230 Result += "\tchar *method_types;\n";
1231 Result += "};\n";
1232
1233 /* struct _objc_protocol_method_list {
1234 int protocol_method_count;
1235 struct protocol_methods protocols[];
1236 }
1237 */
1238 Result += "\nstruct _objc_protocol_method_list {\n";
1239 Result += "\tint protocol_method_count;\n";
1240 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001241 objc_protocol_methods = true;
1242 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001243
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001244 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001245 int NumMethods = PDecl->getNumInstanceMethods();
1246 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001247 Result += "\nstatic struct _objc_protocol_method_list "
1248 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1249 Result += PDecl->getName();
1250 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1251 "{\n\t" + utostr(NumMethods) + "\n";
1252
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001253 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001254 Result += "\t,{{(SEL)\"";
1255 Result += Methods[0]->getSelector().getName().c_str();
1256 Result += "\", \"\"}\n";
1257
1258 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001259 Result += "\t ,{(SEL)\"";
1260 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001261 std::string MethodTypeString;
1262 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1263 Result += "\", \"";
1264 Result += MethodTypeString;
1265 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001266 }
1267 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001268 }
1269
1270 // Output class methods declared in this protocol.
1271 NumMethods = PDecl->getNumClassMethods();
1272 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001273 Result += "\nstatic struct _objc_protocol_method_list "
1274 "_OBJC_PROTOCOL_CLASS_METHODS_";
1275 Result += PDecl->getName();
1276 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1277 "{\n\t";
1278 Result += utostr(NumMethods);
1279 Result += "\n";
1280
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001281 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001282 Result += "\t,{{(SEL)\"";
1283 Result += Methods[0]->getSelector().getName().c_str();
1284 Result += "\", \"\"}\n";
1285
1286 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001287 Result += "\t ,{(SEL)\"";
1288 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001289 std::string MethodTypeString;
1290 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1291 Result += "\", \"";
1292 Result += MethodTypeString;
1293 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001294 }
1295 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001296 }
1297 // Output:
1298 /* struct _objc_protocol {
1299 // Objective-C 1.0 extensions
1300 struct _objc_protocol_extension *isa;
1301 char *protocol_name;
1302 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001303 struct _objc_protocol_method_list *instance_methods;
1304 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001305 };
1306 */
1307 static bool objc_protocol = false;
1308 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001309 Result += "\nstruct _objc_protocol {\n";
1310 Result += "\tstruct _objc_protocol_extension *isa;\n";
1311 Result += "\tchar *protocol_name;\n";
1312 Result += "\tstruct _objc_protocol **protocol_list;\n";
1313 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1314 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1315 Result += "};\n";
1316
1317 /* struct _objc_protocol_list {
1318 struct _objc_protocol_list *next;
1319 int protocol_count;
1320 struct _objc_protocol *class_protocols[];
1321 }
1322 */
1323 Result += "\nstruct _objc_protocol_list {\n";
1324 Result += "\tstruct _objc_protocol_list *next;\n";
1325 Result += "\tint protocol_count;\n";
1326 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1327 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001328 objc_protocol = true;
1329 }
1330
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001331 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1332 Result += PDecl->getName();
1333 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1334 "{\n\t0, \"";
1335 Result += PDecl->getName();
1336 Result += "\", 0, ";
1337 if (PDecl->getInstanceMethods() > 0) {
1338 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1339 Result += PDecl->getName();
1340 Result += ", ";
1341 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001342 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001343 Result += "0, ";
1344 if (PDecl->getClassMethods() > 0) {
1345 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1346 Result += PDecl->getName();
1347 Result += "\n";
1348 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001349 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001350 Result += "0\n";
1351 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001352 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001353 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001354 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1355 Result += prefix;
1356 Result += "_PROTOCOLS_";
1357 Result += ClassName;
1358 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1359 "{\n\t0, ";
1360 Result += utostr(NumProtocols);
1361 Result += "\n";
1362
1363 Result += "\t,{&_OBJC_PROTOCOL_";
1364 Result += Protocols[0]->getName();
1365 Result += " \n";
1366
1367 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001368 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001369 Result += "\t ,&_OBJC_PROTOCOL_";
1370 Result += PDecl->getName();
1371 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001372 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001373 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001374 }
1375}
1376
1377/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1378/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001379void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1380 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001381 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1382 // Find category declaration for this implementation.
1383 ObjcCategoryDecl *CDecl;
1384 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1385 CDecl = CDecl->getNextClassCategory())
1386 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1387 break;
1388 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1389
1390 char *FullCategoryName = (char*)alloca(
1391 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1392 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1393
1394 // Build _objc_method_list for class's instance methods if needed
1395 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1396 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001397 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001398 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001399
1400 // Build _objc_method_list for class's class methods if needed
1401 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1402 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001403 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001404 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001405
1406 // Protocols referenced in class declaration?
1407 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1408 CDecl->getNumReferencedProtocols(),
1409 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001410 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001411
1412 /* struct _objc_category {
1413 char *category_name;
1414 char *class_name;
1415 struct _objc_method_list *instance_methods;
1416 struct _objc_method_list *class_methods;
1417 struct _objc_protocol_list *protocols;
1418 // Objective-C 1.0 extensions
1419 uint32_t size; // sizeof (struct _objc_category)
1420 struct _objc_property_list *instance_properties; // category's own
1421 // @property decl.
1422 };
1423 */
1424
1425 static bool objc_category = false;
1426 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001427 Result += "\nstruct _objc_category {\n";
1428 Result += "\tchar *category_name;\n";
1429 Result += "\tchar *class_name;\n";
1430 Result += "\tstruct _objc_method_list *instance_methods;\n";
1431 Result += "\tstruct _objc_method_list *class_methods;\n";
1432 Result += "\tstruct _objc_protocol_list *protocols;\n";
1433 Result += "\tunsigned int size;\n";
1434 Result += "\tstruct _objc_property_list *instance_properties;\n";
1435 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001436 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001437 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001438 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1439 Result += FullCategoryName;
1440 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1441 Result += IDecl->getName();
1442 Result += "\"\n\t, \"";
1443 Result += ClassDecl->getName();
1444 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001445
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001446 if (IDecl->getNumInstanceMethods() > 0) {
1447 Result += "\t, (struct _objc_method_list *)"
1448 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1449 Result += FullCategoryName;
1450 Result += "\n";
1451 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001452 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001453 Result += "\t, 0\n";
1454 if (IDecl->getNumClassMethods() > 0) {
1455 Result += "\t, (struct _objc_method_list *)"
1456 "&_OBJC_CATEGORY_CLASS_METHODS_";
1457 Result += FullCategoryName;
1458 Result += "\n";
1459 }
1460 else
1461 Result += "\t, 0\n";
1462
1463 if (CDecl->getNumReferencedProtocols() > 0) {
1464 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1465 Result += FullCategoryName;
1466 Result += "\n";
1467 }
1468 else
1469 Result += "\t, 0\n";
1470 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001471}
1472
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001473/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1474/// ivar offset.
1475void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1476 ObjcIvarDecl *ivar,
1477 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001478 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001479 Result += IDecl->getName();
1480 Result += ", ";
1481 Result += ivar->getName();
1482 Result += ")";
1483}
1484
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001485//===----------------------------------------------------------------------===//
1486// Meta Data Emission
1487//===----------------------------------------------------------------------===//
1488
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001489void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1490 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001491 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1492
1493 // Build _objc_ivar_list metadata for classes ivars if needed
1494 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1495 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001496 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001497
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001498 SynthesizeObjcInternalStruct(CDecl, Result);
1499
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001500 if (NumIvars > 0) {
1501 static bool objc_ivar = false;
1502 if (!objc_ivar) {
1503 /* struct _objc_ivar {
1504 char *ivar_name;
1505 char *ivar_type;
1506 int ivar_offset;
1507 };
1508 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001509 Result += "\nstruct _objc_ivar {\n";
1510 Result += "\tchar *ivar_name;\n";
1511 Result += "\tchar *ivar_type;\n";
1512 Result += "\tint ivar_offset;\n";
1513 Result += "};\n";
1514
1515 /* struct _objc_ivar_list {
1516 int ivar_count;
1517 struct _objc_ivar ivar_list[];
1518 };
1519 */
1520 Result += "\nstruct _objc_ivar_list {\n";
1521 Result += "\tint ivar_count;\n";
1522 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001523 objc_ivar = true;
1524 }
1525
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001526 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1527 Result += IDecl->getName();
1528 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1529 "{\n\t";
1530 Result += utostr(NumIvars);
1531 Result += "\n";
1532
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001533 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1534 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001535 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001536 Result += "\t,{{\"";
1537 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001538 Result += "\", \"";
1539 std::string StrEncoding;
1540 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1541 Result += StrEncoding;
1542 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001543 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1544 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001545 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001546 Result += "\t ,{\"";
1547 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001548 Result += "\", \"";
1549 std::string StrEncoding;
1550 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1551 Result += StrEncoding;
1552 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001553 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1554 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001555 }
1556
1557 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001558 }
1559
1560 // Build _objc_method_list for class's instance methods if needed
1561 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1562 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001563 true,
1564 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001565
1566 // Build _objc_method_list for class's class methods if needed
1567 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001568 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001569 false,
1570 "", IDecl->getName(), Result);
1571
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001572 // Protocols referenced in class declaration?
1573 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1574 CDecl->getNumIntfRefProtocols(),
1575 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001576 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001577
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001578
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001579 // Declaration of class/meta-class metadata
1580 /* struct _objc_class {
1581 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001582 const char *super_class_name;
1583 char *name;
1584 long version;
1585 long info;
1586 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001587 struct _objc_ivar_list *ivars;
1588 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001589 struct objc_cache *cache;
1590 struct objc_protocol_list *protocols;
1591 const char *ivar_layout;
1592 struct _objc_class_ext *ext;
1593 };
1594 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001595 static bool objc_class = false;
1596 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001597 Result += "\nstruct _objc_class {\n";
1598 Result += "\tstruct _objc_class *isa;\n";
1599 Result += "\tconst char *super_class_name;\n";
1600 Result += "\tchar *name;\n";
1601 Result += "\tlong version;\n";
1602 Result += "\tlong info;\n";
1603 Result += "\tlong instance_size;\n";
1604 Result += "\tstruct _objc_ivar_list *ivars;\n";
1605 Result += "\tstruct _objc_method_list *methods;\n";
1606 Result += "\tstruct objc_cache *cache;\n";
1607 Result += "\tstruct _objc_protocol_list *protocols;\n";
1608 Result += "\tconst char *ivar_layout;\n";
1609 Result += "\tstruct _objc_class_ext *ext;\n";
1610 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001611 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001612 }
1613
1614 // Meta-class metadata generation.
1615 ObjcInterfaceDecl *RootClass = 0;
1616 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1617 while (SuperClass) {
1618 RootClass = SuperClass;
1619 SuperClass = SuperClass->getSuperClass();
1620 }
1621 SuperClass = CDecl->getSuperClass();
1622
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001623 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1624 Result += CDecl->getName();
1625 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1626 "{\n\t(struct _objc_class *)\"";
1627 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1628 Result += "\"";
1629
1630 if (SuperClass) {
1631 Result += ", \"";
1632 Result += SuperClass->getName();
1633 Result += "\", \"";
1634 Result += CDecl->getName();
1635 Result += "\"";
1636 }
1637 else {
1638 Result += ", 0, \"";
1639 Result += CDecl->getName();
1640 Result += "\"";
1641 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001642 // TODO: 'ivars' field for root class is currently set to 0.
1643 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001644 Result += ", 0,2, sizeof(struct _objc_class), 0";
1645 if (CDecl->getNumClassMethods() > 0) {
1646 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1647 Result += CDecl->getName();
1648 Result += "\n";
1649 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001650 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001651 Result += ", 0\n";
1652 if (CDecl->getNumIntfRefProtocols() > 0) {
1653 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1654 Result += CDecl->getName();
1655 Result += ",0,0\n";
1656 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001657 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001658 Result += "\t,0,0,0,0\n";
1659 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001660
1661 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001662 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1663 Result += CDecl->getName();
1664 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1665 "{\n\t&_OBJC_METACLASS_";
1666 Result += CDecl->getName();
1667 if (SuperClass) {
1668 Result += ", \"";
1669 Result += SuperClass->getName();
1670 Result += "\", \"";
1671 Result += CDecl->getName();
1672 Result += "\"";
1673 }
1674 else {
1675 Result += ", 0, \"";
1676 Result += CDecl->getName();
1677 Result += "\"";
1678 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001679 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001680 Result += ", 0,1";
1681 if (!ObjcSynthesizedStructs.count(CDecl))
1682 Result += ",0";
1683 else {
1684 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001685 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001686 Result += CDecl->getName();
1687 Result += ")";
1688 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001689 if (NumIvars > 0) {
1690 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1691 Result += CDecl->getName();
1692 Result += "\n\t";
1693 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001694 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001695 Result += ",0";
1696 if (IDecl->getNumInstanceMethods() > 0) {
1697 Result += ", &_OBJC_INSTANCE_METHODS_";
1698 Result += CDecl->getName();
1699 Result += ", 0\n\t";
1700 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001701 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001702 Result += ",0,0";
1703 if (CDecl->getNumIntfRefProtocols() > 0) {
1704 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1705 Result += CDecl->getName();
1706 Result += ", 0,0\n";
1707 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001708 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001709 Result += ",0,0,0\n";
1710 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001711}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001712
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001713/// RewriteImplementations - This routine rewrites all method implementations
1714/// and emits meta-data.
1715
1716void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001717 int ClsDefCount = ClassImplementation.size();
1718 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001719
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001720 if (ClsDefCount == 0 && CatDefCount == 0)
1721 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001722 // Rewrite implemented methods
1723 for (int i = 0; i < ClsDefCount; i++)
1724 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001725
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001726 // TODO: This is temporary until we decide how to access objc types in a
1727 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001728 Result += "#include <Objc/objc.h>\n";
1729 // This is needed for use of offsetof
1730 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001731
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001732 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001733 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001734 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001735
1736 // For each implemented category, write out all its meta data.
1737 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001738 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001739
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001740 // Write objc_symtab metadata
1741 /*
1742 struct _objc_symtab
1743 {
1744 long sel_ref_cnt;
1745 SEL *refs;
1746 short cls_def_cnt;
1747 short cat_def_cnt;
1748 void *defs[cls_def_cnt + cat_def_cnt];
1749 };
1750 */
1751
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001752 Result += "\nstruct _objc_symtab {\n";
1753 Result += "\tlong sel_ref_cnt;\n";
1754 Result += "\tSEL *refs;\n";
1755 Result += "\tshort cls_def_cnt;\n";
1756 Result += "\tshort cat_def_cnt;\n";
1757 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1758 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001759
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001760 Result += "static struct _objc_symtab "
1761 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1762 Result += "\t0, 0, " + utostr(ClsDefCount)
1763 + ", " + utostr(CatDefCount) + "\n";
1764 for (int i = 0; i < ClsDefCount; i++) {
1765 Result += "\t,&_OBJC_CLASS_";
1766 Result += ClassImplementation[i]->getName();
1767 Result += "\n";
1768 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001769
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001770 for (int i = 0; i < CatDefCount; i++) {
1771 Result += "\t,&_OBJC_CATEGORY_";
1772 Result += CategoryImplementation[i]->getClassInterface()->getName();
1773 Result += "_";
1774 Result += CategoryImplementation[i]->getName();
1775 Result += "\n";
1776 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001777
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001778 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001779
1780 // Write objc_module metadata
1781
1782 /*
1783 struct _objc_module {
1784 long version;
1785 long size;
1786 const char *name;
1787 struct _objc_symtab *symtab;
1788 }
1789 */
1790
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001791 Result += "\nstruct _objc_module {\n";
1792 Result += "\tlong version;\n";
1793 Result += "\tlong size;\n";
1794 Result += "\tconst char *name;\n";
1795 Result += "\tstruct _objc_symtab *symtab;\n";
1796 Result += "};\n\n";
1797 Result += "static struct _objc_module "
1798 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001799 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1800 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001801 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001802
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001803}
Chris Lattner311ff022007-10-16 22:36:42 +00001804