blob: e79d830e01bfdd846a1f2e0af9c974402db0a8f0 [file] [log] [blame]
Chris Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff1ccf4632007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000023using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000025
Chris Lattnerb429ae42007-10-11 00:43:27 +000026namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner74db1682007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Steve Naroffe9780582007-10-23 23:50:29 +000037
38 FunctionDecl *MsgSendFunctionDecl;
39 FunctionDecl *GetClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000040 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000041
Steve Naroff0add5d22007-11-03 11:27:19 +000042 // ObjC string constant support.
43 FileVarDecl *ConstantStringClassReference;
44 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000045
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000046 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000047 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000048 void Initialize(ASTContext &context, unsigned mainFileID) {
49 Context = &context;
50 SM = &Context->SourceMgr;
Chris Lattner569faa62007-10-11 18:38:32 +000051 MainFileID = mainFileID;
Steve Naroffe9780582007-10-23 23:50:29 +000052 MsgSendFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000053 GetClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000054 SelGetUidFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000055 ConstantStringClassReference = 0;
56 NSStringRecord = 0;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000057 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Narofffcab7932007-11-05 14:55:35 +000058 // declaring objc_selector outside the parameter list removes a silly
59 // scope related warning...
60 const char *s = "struct objc_selector;\n"
61 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +000062 "(struct objc_object *, struct objc_selector *, ...);\n"
63 "extern struct objc_object *objc_getClass"
64 "(const char *);\n";
65 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
66 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +000067 }
Chris Lattner569faa62007-10-11 18:38:32 +000068
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000069 // Top Level Driver code.
70 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000071 void HandleDeclInMainFile(Decl *D);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000072 ~RewriteTest();
73
74 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +000075 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +000076 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000077 void RewriteTabs();
78 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +000079 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff667f1682007-10-30 13:30:57 +000080 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +000081 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff667f1682007-10-30 13:30:57 +000082 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Steve Naroff02a82aa2007-10-30 23:14:51 +000083 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffc8a92d12007-11-01 13:24:47 +000084 void RewriteObjcQualifiedInterfaceTypes(
85 const FunctionTypeProto *proto, FunctionDecl *FD);
86 bool needToScanForQualifiers(QualType T);
Chris Lattner6fe8b272007-10-16 22:36:42 +000087
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000088 // Expression Rewriting.
Chris Lattner0021f452007-10-24 16:57:36 +000089 Stmt *RewriteFunctionBody(Stmt *S);
90 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff296b74f2007-11-05 14:50:49 +000091 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +000092 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +000093 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +000094 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
95 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
96 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +000097 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
98 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +000099 void SynthMsgSendFunctionDecl();
100 void SynthGetClassFunctionDecl();
101
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000102 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000103 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
104 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000105
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000106 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
107 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000108
109 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
110 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000111 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000112 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000113 const char *ClassName,
114 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000115
116 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
117 int NumProtocols,
118 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000119 const char *ClassName,
120 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000121 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
122 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000123 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
124 ObjcIvarDecl *ivar,
125 std::string &Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000126 void WriteObjcMetaData(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000127 };
128}
129
Chris Lattner569faa62007-10-11 18:38:32 +0000130ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000131
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000132//===----------------------------------------------------------------------===//
133// Top Level Driver Code
134//===----------------------------------------------------------------------===//
135
Chris Lattner569faa62007-10-11 18:38:32 +0000136void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000137 // Two cases: either the decl could be in the main file, or it could be in a
138 // #included file. If the former, rewrite it now. If the later, check to see
139 // if we rewrote the #include/#import.
140 SourceLocation Loc = D->getLocation();
141 Loc = SM->getLogicalLoc(Loc);
142
143 // If this is for a builtin, ignore it.
144 if (Loc.isInvalid()) return;
145
Steve Naroffe9780582007-10-23 23:50:29 +0000146 // Look for built-in declarations that we need to refer during the rewrite.
147 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000148 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000149 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
150 // declared in <Foundation/NSString.h>
151 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
152 ConstantStringClassReference = FVD;
153 return;
154 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000155 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
156 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000157 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
158 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000159 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
160 RewriteProtocolDecl(PD);
Steve Naroffe9780582007-10-23 23:50:29 +0000161 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000162 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000163 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
164 return HandleDeclInMainFile(D);
165
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000166 // Otherwise, see if there is a #import in the main file that should be
167 // rewritten.
Chris Lattner74db1682007-10-16 21:07:07 +0000168 RewriteInclude(Loc);
169}
170
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000171/// HandleDeclInMainFile - This is called for each top-level decl defined in the
172/// main file of the input.
173void RewriteTest::HandleDeclInMainFile(Decl *D) {
174 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
175 if (Stmt *Body = FD->getBody())
176 FD->setBody(RewriteFunctionBody(Body));
177
178 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
179 ClassImplementation.push_back(CI);
180 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
181 CategoryImplementation.push_back(CI);
182 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
183 RewriteForwardClassDecl(CD);
184 // Nothing yet.
185}
186
187RewriteTest::~RewriteTest() {
188 // Get the top-level buffer that this corresponds to.
189 RewriteTabs();
190
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000191 // Rewrite Objective-c meta data*
192 std::string ResultStr;
193 WriteObjcMetaData(ResultStr);
194 // For now just print the string out.
195 printf("%s", ResultStr.c_str());
196
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000197 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
198 // we are done.
199 if (const RewriteBuffer *RewriteBuf =
200 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000201 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000202 std::string S(RewriteBuf->begin(), RewriteBuf->end());
203 printf("%s\n", S.c_str());
204 } else {
205 printf("No changes\n");
206 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000207
208}
209
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000210//===----------------------------------------------------------------------===//
211// Syntactic (non-AST) Rewriting Code
212//===----------------------------------------------------------------------===//
213
Chris Lattner74db1682007-10-16 21:07:07 +0000214void RewriteTest::RewriteInclude(SourceLocation Loc) {
215 // Rip up the #include stack to the main file.
216 SourceLocation IncLoc = Loc, NextLoc = Loc;
217 do {
218 IncLoc = Loc;
219 Loc = SM->getLogicalLoc(NextLoc);
220 NextLoc = SM->getIncludeLoc(Loc);
221 } while (!NextLoc.isInvalid());
222
223 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
224 // IncLoc indicates the header that was included if it is useful.
225 IncLoc = SM->getLogicalLoc(IncLoc);
226 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
227 Loc == LastIncLoc)
228 return;
229 LastIncLoc = Loc;
230
231 unsigned IncCol = SM->getColumnNumber(Loc);
232 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
233
234 // Replace the #import with #include.
235 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
236}
237
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000238void RewriteTest::RewriteTabs() {
239 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
240 const char *MainBufStart = MainBuf.first;
241 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000242
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000243 // Loop over the whole file, looking for tabs.
244 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
245 if (*BufPtr != '\t')
246 continue;
247
248 // Okay, we found a tab. This tab will turn into at least one character,
249 // but it depends on which 'virtual column' it is in. Compute that now.
250 unsigned VCol = 0;
251 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
252 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
253 ++VCol;
254
255 // Okay, now that we know the virtual column, we know how many spaces to
256 // insert. We assume 8-character tab-stops.
257 unsigned Spaces = 8-(VCol & 7);
258
259 // Get the location of the tab.
260 SourceLocation TabLoc =
261 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
262
263 // Rewrite the single tab character into a sequence of spaces.
264 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
265 }
Chris Lattner569faa62007-10-11 18:38:32 +0000266}
267
268
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000269void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
270 int numDecls = ClassDecl->getNumForwardDecls();
271 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
272
273 // Get the start location and compute the semi location.
274 SourceLocation startLoc = ClassDecl->getLocation();
275 const char *startBuf = SM->getCharacterData(startLoc);
276 const char *semiPtr = strchr(startBuf, ';');
277
278 // Translate to typedef's that forward reference structs with the same name
279 // as the class. As a convenience, we include the original declaration
280 // as a comment.
281 std::string typedefString;
282 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000283 typedefString.append(startBuf, semiPtr-startBuf+1);
284 typedefString += "\n";
285 for (int i = 0; i < numDecls; i++) {
286 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff809b4f02007-10-31 22:11:35 +0000287 if (ObjcForwardDecls.count(ForwardDecl))
288 continue;
Steve Naroff4242b972007-11-05 14:36:37 +0000289 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000290 typedefString += ForwardDecl->getName();
291 typedefString += ";\n";
Steve Naroff809b4f02007-10-31 22:11:35 +0000292
293 // Mark this typedef as having been generated.
294 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000295 assert(false && "typedef already output");
Steve Naroff71226032007-10-24 22:48:43 +0000296 }
297
298 // Replace the @class with typedefs corresponding to the classes.
299 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
300 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000301}
302
Steve Naroff667f1682007-10-30 13:30:57 +0000303void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
304 for (int i = 0; i < nMethods; i++) {
305 ObjcMethodDecl *Method = Methods[i];
306 SourceLocation Loc = Method->getLocStart();
307
308 Rewrite.ReplaceText(Loc, 0, "// ", 3);
309
310 // FIXME: handle methods that are declared across multiple lines.
311 }
312}
313
314void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
315 SourceLocation LocStart = CatDecl->getLocStart();
316
317 // FIXME: handle category headers that are declared across multiple lines.
318 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
319
320 RewriteMethods(CatDecl->getNumInstanceMethods(),
321 CatDecl->getInstanceMethods());
322 RewriteMethods(CatDecl->getNumClassMethods(),
323 CatDecl->getClassMethods());
324 // Lastly, comment out the @end.
325 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
326}
327
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000328void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
329 SourceLocation LocStart = PDecl->getLocStart();
330
331 // FIXME: handle protocol headers that are declared across multiple lines.
332 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
333
334 RewriteMethods(PDecl->getNumInstanceMethods(),
335 PDecl->getInstanceMethods());
336 RewriteMethods(PDecl->getNumClassMethods(),
337 PDecl->getClassMethods());
338 // Lastly, comment out the @end.
339 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
340}
341
Steve Naroff3774dd92007-10-26 20:53:56 +0000342void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000343
344 SourceLocation LocStart = ClassDecl->getLocStart();
345 SourceLocation LocEnd = ClassDecl->getLocEnd();
346
347 const char *startBuf = SM->getCharacterData(LocStart);
348 const char *endBuf = SM->getCharacterData(LocEnd);
349
Steve Naroff1ccf4632007-10-30 03:43:13 +0000350 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Naroffef20ed32007-10-30 02:23:23 +0000351
352 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000353 if (!ObjcForwardDecls.count(ClassDecl)) {
354 // we haven't seen a forward decl - generate a typedef.
Steve Naroff4242b972007-11-05 14:36:37 +0000355 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000356 ResultStr += ClassDecl->getName();
357 ResultStr += ";";
358
359 // Mark this typedef as having been generated.
360 ObjcForwardDecls.insert(ClassDecl);
361 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000362 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
363
Steve Naroff1ccf4632007-10-30 03:43:13 +0000364 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Naroffef20ed32007-10-30 02:23:23 +0000365 ResultStr.c_str(), ResultStr.size());
366
Steve Naroff667f1682007-10-30 13:30:57 +0000367 RewriteMethods(ClassDecl->getNumInstanceMethods(),
368 ClassDecl->getInstanceMethods());
369 RewriteMethods(ClassDecl->getNumClassMethods(),
370 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000371
Steve Naroff1ccf4632007-10-30 03:43:13 +0000372 // Lastly, comment out the @end.
373 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000374}
375
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000376//===----------------------------------------------------------------------===//
377// Function Body / Expression rewriting
378//===----------------------------------------------------------------------===//
379
Chris Lattner0021f452007-10-24 16:57:36 +0000380Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000381 // Otherwise, just rewrite all children.
382 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
383 CI != E; ++CI)
Chris Lattnere33506b2007-10-17 21:28:00 +0000384 if (*CI)
Chris Lattner0021f452007-10-24 16:57:36 +0000385 *CI = RewriteFunctionBody(*CI);
Steve Naroffe9780582007-10-23 23:50:29 +0000386
387 // Handle specific things.
388 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
389 return RewriteAtEncode(AtEncode);
Steve Naroff296b74f2007-11-05 14:50:49 +0000390
391 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
392 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000393
394 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
395 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000396
Steve Naroff71226032007-10-24 22:48:43 +0000397 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
398 // Before we rewrite it, put the original message expression in a comment.
399 SourceLocation startLoc = MessExpr->getLocStart();
400 SourceLocation endLoc = MessExpr->getLocEnd();
401
402 const char *startBuf = SM->getCharacterData(startLoc);
403 const char *endBuf = SM->getCharacterData(endLoc);
404
405 std::string messString;
406 messString += "// ";
407 messString.append(startBuf, endBuf-startBuf+1);
408 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000409
Steve Naroff71226032007-10-24 22:48:43 +0000410 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
411 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
412 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000413 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000414 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000415 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000416
417 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
418 return RewriteObjcTryStmt(StmtTry);
419
420 if (ObjcAtCatchStmt *StmtCatch = dyn_cast<ObjcAtCatchStmt>(S))
421 return RewriteObjcCatchStmt(StmtCatch);
422
423 if (ObjcAtFinallyStmt *StmtFinally = dyn_cast<ObjcAtFinallyStmt>(S))
424 return RewriteObjcFinallyStmt(StmtFinally);
425
Chris Lattner0021f452007-10-24 16:57:36 +0000426 // Return this stmt unmodified.
427 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000428}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000429
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000430Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
431 return 0;
432}
433
434Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
435 return 0;
436}
437
438Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
439 return 0;
440}
441
442
Chris Lattner0021f452007-10-24 16:57:36 +0000443Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000444 // Create a new string expression.
445 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000446 std::string StrEncoding;
447 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
448 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
449 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000450 SourceLocation(), SourceLocation());
451 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattner0021f452007-10-24 16:57:36 +0000452 delete Exp;
453 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000454}
455
Steve Naroff296b74f2007-11-05 14:50:49 +0000456Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
457 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
458 // Create a call to sel_registerName("selName").
459 llvm::SmallVector<Expr*, 8> SelExprs;
460 QualType argType = Context->getPointerType(Context->CharTy);
461 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
462 Exp->getSelector().getName().size(),
463 false, argType, SourceLocation(),
464 SourceLocation()));
465 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
466 &SelExprs[0], SelExprs.size());
467 Rewrite.ReplaceStmt(Exp, SelExp);
468 delete Exp;
469 return SelExp;
470}
471
Steve Naroff71226032007-10-24 22:48:43 +0000472CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
473 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000474 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000475 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000476
477 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000478 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000479
480 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000481 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000482 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
483
484 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000485
Steve Naroff71226032007-10-24 22:48:43 +0000486 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
487}
488
Steve Naroffc8a92d12007-11-01 13:24:47 +0000489static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
490 const char *&startRef, const char *&endRef) {
491 while (startBuf < endBuf) {
492 if (*startBuf == '<')
493 startRef = startBuf; // mark the start.
494 if (*startBuf == '>') {
495 assert((startRef && *startRef == '<') && "rewrite scanning error");
496 endRef = startBuf; // mark the end.
497 return true;
498 }
499 startBuf++;
500 }
501 return false;
502}
503
504bool RewriteTest::needToScanForQualifiers(QualType T) {
505 // FIXME: we don't currently represent "id <Protocol>" in the type system.
506 if (T == Context->getObjcIdType())
507 return true;
508
509 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000510 Type *pointeeType = pType->getPointeeType().getTypePtr();
511 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
512 return true; // we have "Class <Protocol> *".
513 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000514 return false;
515}
516
517void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
518 const FunctionTypeProto *proto, FunctionDecl *FD) {
519
520 if (needToScanForQualifiers(proto->getResultType())) {
521 // Since types are unique, we need to scan the buffer.
522 SourceLocation Loc = FD->getLocation();
523
524 const char *endBuf = SM->getCharacterData(Loc);
525 const char *startBuf = endBuf;
526 while (*startBuf != ';')
527 startBuf--; // scan backward (from the decl location) for return type.
528 const char *startRef = 0, *endRef = 0;
529 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
530 // Get the locations of the startRef, endRef.
531 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
532 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
533 // Comment out the protocol references.
534 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
535 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000536 }
537 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000538 // Now check arguments.
539 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
540 if (needToScanForQualifiers(proto->getArgType(i))) {
541 // Since types are unique, we need to scan the buffer.
542 SourceLocation Loc = FD->getLocation();
543
544 const char *startBuf = SM->getCharacterData(Loc);
545 const char *endBuf = startBuf;
546 while (*endBuf != ';')
547 endBuf++; // scan forward (from the decl location) for argument types.
548 const char *startRef = 0, *endRef = 0;
549 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
550 // Get the locations of the startRef, endRef.
551 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
552 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
553 // Comment out the protocol references.
554 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
555 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
556 }
557 }
558 }
Steve Naroff05d6ff52007-10-31 04:38:33 +0000559}
560
Steve Naroff02a82aa2007-10-30 23:14:51 +0000561void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
562 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +0000563 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000564 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +0000565 return;
566 }
567 // Check for ObjC 'id' and class types that have been adorned with protocol
568 // information (id<p>, C<p>*). The protocol references need to be rewritten!
569 const FunctionType *funcType = FD->getType()->getAsFunctionType();
570 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +0000571 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
572 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000573}
574
575// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
576void RewriteTest::SynthMsgSendFunctionDecl() {
577 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
578 llvm::SmallVector<QualType, 16> ArgTys;
579 QualType argT = Context->getObjcIdType();
580 assert(!argT.isNull() && "Can't find 'id' type");
581 ArgTys.push_back(argT);
582 argT = Context->getObjcSelType();
583 assert(!argT.isNull() && "Can't find 'SEL' type");
584 ArgTys.push_back(argT);
585 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
586 &ArgTys[0], ArgTys.size(),
587 true /*isVariadic*/);
588 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
589 msgSendIdent, msgSendType,
590 FunctionDecl::Extern, false, 0);
591}
592
593// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
594void RewriteTest::SynthGetClassFunctionDecl() {
595 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
596 llvm::SmallVector<QualType, 16> ArgTys;
597 ArgTys.push_back(Context->getPointerType(
598 Context->CharTy.getQualifiedType(QualType::Const)));
599 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
600 &ArgTys[0], ArgTys.size(),
601 false /*isVariadic*/);
602 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
603 getClassIdent, getClassType,
604 FunctionDecl::Extern, false, 0);
605}
606
Steve Naroff0add5d22007-11-03 11:27:19 +0000607Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
608 assert(ConstantStringClassReference && "Can't find constant string reference");
609 llvm::SmallVector<Expr*, 4> InitExprs;
610
611 // Synthesize "(Class)&_NSConstantStringClassReference"
612 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
613 ConstantStringClassReference->getType(),
614 SourceLocation());
615 QualType expType = Context->getPointerType(ClsRef->getType());
616 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
617 expType, SourceLocation());
618 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
619 SourceLocation());
620 InitExprs.push_back(cast); // set the 'isa'.
621 InitExprs.push_back(Exp->getString()); // set "char *bytes".
622 unsigned IntSize = static_cast<unsigned>(
623 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
624 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
625 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
626 Exp->getLocStart());
627 InitExprs.push_back(len); // set "int numBytes".
628
629 // struct NSConstantString
630 QualType CFConstantStrType = Context->getCFConstantStringType();
631 // (struct NSConstantString) { <exprs from above> }
632 InitListExpr *ILE = new InitListExpr(SourceLocation(),
633 &InitExprs[0], InitExprs.size(),
634 SourceLocation());
635 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
636 // struct NSConstantString *
637 expType = Context->getPointerType(StrRep->getType());
638 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
639 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +0000640 // cast to NSConstantString *
641 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +0000642 Rewrite.ReplaceStmt(Exp, cast);
643 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +0000644 return cast;
Steve Naroff0add5d22007-11-03 11:27:19 +0000645}
646
Steve Naroff71226032007-10-24 22:48:43 +0000647Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000648 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +0000649 if (!MsgSendFunctionDecl)
650 SynthMsgSendFunctionDecl();
651 if (!GetClassFunctionDecl)
652 SynthGetClassFunctionDecl();
Steve Naroff71226032007-10-24 22:48:43 +0000653
654 // Synthesize a call to objc_msgSend().
655 llvm::SmallVector<Expr*, 8> MsgExprs;
656 IdentifierInfo *clsName = Exp->getClassName();
657
658 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
659 if (clsName) { // class message.
660 llvm::SmallVector<Expr*, 8> ClsExprs;
661 QualType argType = Context->getPointerType(Context->CharTy);
662 ClsExprs.push_back(new StringLiteral(clsName->getName(),
663 clsName->getLength(),
664 false, argType, SourceLocation(),
665 SourceLocation()));
666 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
667 &ClsExprs[0], ClsExprs.size());
668 MsgExprs.push_back(Cls);
669 } else // instance message.
670 MsgExprs.push_back(Exp->getReceiver());
671
Steve Naroff0add5d22007-11-03 11:27:19 +0000672 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +0000673 llvm::SmallVector<Expr*, 8> SelExprs;
674 QualType argType = Context->getPointerType(Context->CharTy);
675 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
676 Exp->getSelector().getName().size(),
677 false, argType, SourceLocation(),
678 SourceLocation()));
679 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
680 &SelExprs[0], SelExprs.size());
681 MsgExprs.push_back(SelExp);
682
683 // Now push any user supplied arguments.
684 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
685 MsgExprs.push_back(Exp->getArg(i));
686 // We've transferred the ownership to MsgExprs. Null out the argument in
687 // the original expression, since we will delete it below.
688 Exp->setArg(i, 0);
689 }
Steve Naroff0744c472007-11-04 22:37:50 +0000690 // Generate the funky cast.
691 CastExpr *cast;
692 llvm::SmallVector<QualType, 8> ArgTypes;
693 QualType returnType;
694
695 // Push 'id' and 'SEL', the 2 implicit arguments.
696 ArgTypes.push_back(Context->getObjcIdType());
697 ArgTypes.push_back(Context->getObjcSelType());
698 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
699 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +0000700 for (int i = 0; i < mDecl->getNumParams(); i++) {
701 QualType t = mDecl->getParamDecl(i)->getType();
702 if (t == Context->getObjcClassType())
703 t = Context->getObjcIdType(); // Convert "Class"->"id"
704 ArgTypes.push_back(t);
705 }
Steve Naroff0744c472007-11-04 22:37:50 +0000706 returnType = mDecl->getResultType();
707 } else {
708 returnType = Context->getObjcIdType();
709 }
710 // Get the type, we will need to reference it in a couple spots.
711 QualType msgSendType = MsgSendFunctionDecl->getType();
712
713 // Create a reference to the objc_msgSend() declaration.
714 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
715
716 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
717 // If we don't do this cast, we get the following bizarre warning/note:
718 // xx.m:13: warning: function called through a non-compatible type
719 // xx.m:13: note: if this code is reached, the program will abort
720 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
721 SourceLocation());
722
723 // Now do the "normal" pointer to function cast.
724 QualType castType = Context->getFunctionType(returnType,
725 &ArgTypes[0], ArgTypes.size(),
726 false/*FIXME:variadic*/);
727 castType = Context->getPointerType(castType);
728 cast = new CastExpr(castType, cast, SourceLocation());
729
730 // Don't forget the parens to enforce the proper binding.
731 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
732
733 const FunctionType *FT = msgSendType->getAsFunctionType();
734 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
735 FT->getResultType(), SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +0000736 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +0000737 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +0000738
Chris Lattner0021f452007-10-24 16:57:36 +0000739 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +0000740 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +0000741}
742
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000743/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
744/// an objective-c class with ivars.
745void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
746 std::string &Result) {
747 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
748 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +0000749 // Do not synthesize more than once.
750 if (ObjcSynthesizedStructs.count(CDecl))
751 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000752 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
753 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
754 // Do it for the root
755 SynthesizeObjcInternalStruct(RCDecl, Result);
756 }
757
758 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000759 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanian2fd0daa2007-10-31 23:53:01 +0000760 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000761 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
762 return;
763
Steve Naroffb1147382007-11-01 17:12:31 +0000764 Result += "\nstruct ";
765 Result += CDecl->getName();
766 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
767 Result += " {\n struct ";
768 Result += RCDecl->getName();
769 Result += " _";
770 Result += RCDecl->getName();
771 Result += ";\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000772 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +0000773 else
774 Result += " {";
Steve Naroff809b4f02007-10-31 22:11:35 +0000775
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +0000776 if (NumIvars > 0) {
777 SourceLocation LocStart = CDecl->getLocStart();
778 SourceLocation LocEnd = CDecl->getLocEnd();
779
780 const char *startBuf = SM->getCharacterData(LocStart);
781 const char *endBuf = SM->getCharacterData(LocEnd);
782 startBuf = strchr(startBuf, '{');
783 assert((startBuf && endBuf)
784 && "SynthesizeObjcInternalStruct - malformed @interface");
785 startBuf++; // past '{'
786 while (startBuf < endBuf) {
787 if (*startBuf == '@') {
788 startBuf = strchr(startBuf, 'p');
789 // FIXME: presence of @public, etc. inside comment results in
790 // this transformation as well, which is still correct c-code.
791 if (!strncmp(startBuf, "public", strlen("public"))) {
792 startBuf += strlen("public");
793 Result += "/* @public */";
794 }
795 else if (!strncmp(startBuf, "private", strlen("private"))) {
796 startBuf += strlen("private");
797 Result += "/* @private */";
798 }
799 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
800 startBuf += strlen("protected");
801 Result += "/* @protected */";
802 }
803 }
804 Result += *startBuf++;
805 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000806 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +0000807
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000808 Result += "};\n";
809 // Mark this struct as having been generated.
810 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000811 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000812}
813
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000814// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
815/// class methods.
816void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
817 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000818 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000819 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000820 const char *ClassName,
821 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000822 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000823 if (NumMethods > 0 && !objc_impl_method) {
824 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000825 SEL _cmd;
826 char *method_types;
827 void *_imp;
828 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000829 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000830 Result += "\nstruct _objc_method {\n";
831 Result += "\tSEL _cmd;\n";
832 Result += "\tchar *method_types;\n";
833 Result += "\tvoid *_imp;\n";
834 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000835
836 /* struct _objc_method_list {
837 struct _objc_method_list *next_method;
838 int method_count;
839 struct _objc_method method_list[];
840 }
841 */
842 Result += "\nstruct _objc_method_list {\n";
843 Result += "\tstruct _objc_method_list *next_method;\n";
844 Result += "\tint method_count;\n";
845 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000846 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +0000847 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000848 // Build _objc_method_list for class's methods if needed
849 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000850 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000851 Result += prefix;
852 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
853 Result += "_METHODS_";
854 Result += ClassName;
855 Result += " __attribute__ ((section (\"__OBJC, __";
856 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000857 Result += "_meth\")))= ";
858 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
859
860 Result += "\t,{{(SEL)\"";
861 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000862 std::string MethodTypeString;
863 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
864 Result += "\", \"";
865 Result += MethodTypeString;
866 Result += "\", 0}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000867 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000868 // TODO: Need method address as 3rd initializer.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000869 Result += "\t ,{(SEL)\"";
870 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000871 std::string MethodTypeString;
872 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
873 Result += "\", \"";
874 Result += MethodTypeString;
875 Result += "\", 0}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000876 }
877 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000878 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000879}
880
881/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
882void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
883 int NumProtocols,
884 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000885 const char *ClassName,
886 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000887 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +0000888 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000889 for (int i = 0; i < NumProtocols; i++) {
890 ObjcProtocolDecl *PDecl = Protocols[i];
891 // Output struct protocol_methods holder of method selector and type.
892 if (!objc_protocol_methods &&
893 (PDecl->getNumInstanceMethods() > 0
894 || PDecl->getNumClassMethods() > 0)) {
895 /* struct protocol_methods {
896 SEL _cmd;
897 char *method_types;
898 }
899 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000900 Result += "\nstruct protocol_methods {\n";
901 Result += "\tSEL _cmd;\n";
902 Result += "\tchar *method_types;\n";
903 Result += "};\n";
904
905 /* struct _objc_protocol_method_list {
906 int protocol_method_count;
907 struct protocol_methods protocols[];
908 }
909 */
910 Result += "\nstruct _objc_protocol_method_list {\n";
911 Result += "\tint protocol_method_count;\n";
912 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000913 objc_protocol_methods = true;
914 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000915
Fariborz Jahanian04455192007-10-22 21:41:37 +0000916 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +0000917 int NumMethods = PDecl->getNumInstanceMethods();
918 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000919 Result += "\nstatic struct _objc_protocol_method_list "
920 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
921 Result += PDecl->getName();
922 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
923 "{\n\t" + utostr(NumMethods) + "\n";
924
Fariborz Jahanian04455192007-10-22 21:41:37 +0000925 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000926 Result += "\t,{{(SEL)\"";
927 Result += Methods[0]->getSelector().getName().c_str();
928 Result += "\", \"\"}\n";
929
930 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000931 Result += "\t ,{(SEL)\"";
932 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000933 std::string MethodTypeString;
934 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
935 Result += "\", \"";
936 Result += MethodTypeString;
937 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000938 }
939 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000940 }
941
942 // Output class methods declared in this protocol.
943 NumMethods = PDecl->getNumClassMethods();
944 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000945 Result += "\nstatic struct _objc_protocol_method_list "
946 "_OBJC_PROTOCOL_CLASS_METHODS_";
947 Result += PDecl->getName();
948 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
949 "{\n\t";
950 Result += utostr(NumMethods);
951 Result += "\n";
952
Fariborz Jahanian04455192007-10-22 21:41:37 +0000953 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000954 Result += "\t,{{(SEL)\"";
955 Result += Methods[0]->getSelector().getName().c_str();
956 Result += "\", \"\"}\n";
957
958 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000959 Result += "\t ,{(SEL)\"";
960 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000961 std::string MethodTypeString;
962 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
963 Result += "\", \"";
964 Result += MethodTypeString;
965 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000966 }
967 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000968 }
969 // Output:
970 /* struct _objc_protocol {
971 // Objective-C 1.0 extensions
972 struct _objc_protocol_extension *isa;
973 char *protocol_name;
974 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000975 struct _objc_protocol_method_list *instance_methods;
976 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +0000977 };
978 */
979 static bool objc_protocol = false;
980 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000981 Result += "\nstruct _objc_protocol {\n";
982 Result += "\tstruct _objc_protocol_extension *isa;\n";
983 Result += "\tchar *protocol_name;\n";
984 Result += "\tstruct _objc_protocol **protocol_list;\n";
985 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
986 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
987 Result += "};\n";
988
989 /* struct _objc_protocol_list {
990 struct _objc_protocol_list *next;
991 int protocol_count;
992 struct _objc_protocol *class_protocols[];
993 }
994 */
995 Result += "\nstruct _objc_protocol_list {\n";
996 Result += "\tstruct _objc_protocol_list *next;\n";
997 Result += "\tint protocol_count;\n";
998 Result += "\tstruct _objc_protocol *class_protocols[];\n";
999 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001000 objc_protocol = true;
1001 }
1002
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001003 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1004 Result += PDecl->getName();
1005 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1006 "{\n\t0, \"";
1007 Result += PDecl->getName();
1008 Result += "\", 0, ";
1009 if (PDecl->getInstanceMethods() > 0) {
1010 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1011 Result += PDecl->getName();
1012 Result += ", ";
1013 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001014 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001015 Result += "0, ";
1016 if (PDecl->getClassMethods() > 0) {
1017 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1018 Result += PDecl->getName();
1019 Result += "\n";
1020 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001021 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001022 Result += "0\n";
1023 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001024 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001025 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001026 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1027 Result += prefix;
1028 Result += "_PROTOCOLS_";
1029 Result += ClassName;
1030 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1031 "{\n\t0, ";
1032 Result += utostr(NumProtocols);
1033 Result += "\n";
1034
1035 Result += "\t,{&_OBJC_PROTOCOL_";
1036 Result += Protocols[0]->getName();
1037 Result += " \n";
1038
1039 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001040 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001041 Result += "\t ,&_OBJC_PROTOCOL_";
1042 Result += PDecl->getName();
1043 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001044 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001045 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001046 }
1047}
1048
1049/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1050/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001051void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1052 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001053 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1054 // Find category declaration for this implementation.
1055 ObjcCategoryDecl *CDecl;
1056 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1057 CDecl = CDecl->getNextClassCategory())
1058 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1059 break;
1060 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1061
1062 char *FullCategoryName = (char*)alloca(
1063 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1064 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1065
1066 // Build _objc_method_list for class's instance methods if needed
1067 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1068 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001069 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001070 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001071
1072 // Build _objc_method_list for class's class methods if needed
1073 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1074 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001075 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001076 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001077
1078 // Protocols referenced in class declaration?
1079 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1080 CDecl->getNumReferencedProtocols(),
1081 "CATEGORY",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001082 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001083
1084 /* struct _objc_category {
1085 char *category_name;
1086 char *class_name;
1087 struct _objc_method_list *instance_methods;
1088 struct _objc_method_list *class_methods;
1089 struct _objc_protocol_list *protocols;
1090 // Objective-C 1.0 extensions
1091 uint32_t size; // sizeof (struct _objc_category)
1092 struct _objc_property_list *instance_properties; // category's own
1093 // @property decl.
1094 };
1095 */
1096
1097 static bool objc_category = false;
1098 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001099 Result += "\nstruct _objc_category {\n";
1100 Result += "\tchar *category_name;\n";
1101 Result += "\tchar *class_name;\n";
1102 Result += "\tstruct _objc_method_list *instance_methods;\n";
1103 Result += "\tstruct _objc_method_list *class_methods;\n";
1104 Result += "\tstruct _objc_protocol_list *protocols;\n";
1105 Result += "\tunsigned int size;\n";
1106 Result += "\tstruct _objc_property_list *instance_properties;\n";
1107 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001108 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001109 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001110 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1111 Result += FullCategoryName;
1112 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1113 Result += IDecl->getName();
1114 Result += "\"\n\t, \"";
1115 Result += ClassDecl->getName();
1116 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001117
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001118 if (IDecl->getNumInstanceMethods() > 0) {
1119 Result += "\t, (struct _objc_method_list *)"
1120 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1121 Result += FullCategoryName;
1122 Result += "\n";
1123 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001124 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001125 Result += "\t, 0\n";
1126 if (IDecl->getNumClassMethods() > 0) {
1127 Result += "\t, (struct _objc_method_list *)"
1128 "&_OBJC_CATEGORY_CLASS_METHODS_";
1129 Result += FullCategoryName;
1130 Result += "\n";
1131 }
1132 else
1133 Result += "\t, 0\n";
1134
1135 if (CDecl->getNumReferencedProtocols() > 0) {
1136 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1137 Result += FullCategoryName;
1138 Result += "\n";
1139 }
1140 else
1141 Result += "\t, 0\n";
1142 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001143}
1144
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001145/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1146/// ivar offset.
1147void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1148 ObjcIvarDecl *ivar,
1149 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001150 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001151 Result += IDecl->getName();
1152 Result += ", ";
1153 Result += ivar->getName();
1154 Result += ")";
1155}
1156
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001157//===----------------------------------------------------------------------===//
1158// Meta Data Emission
1159//===----------------------------------------------------------------------===//
1160
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001161void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1162 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001163 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1164
1165 // Build _objc_ivar_list metadata for classes ivars if needed
1166 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1167 ? IDecl->getImplDeclNumIvars()
1168 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1169
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001170 SynthesizeObjcInternalStruct(CDecl, Result);
1171
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001172 if (NumIvars > 0) {
1173 static bool objc_ivar = false;
1174 if (!objc_ivar) {
1175 /* struct _objc_ivar {
1176 char *ivar_name;
1177 char *ivar_type;
1178 int ivar_offset;
1179 };
1180 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001181 Result += "\nstruct _objc_ivar {\n";
1182 Result += "\tchar *ivar_name;\n";
1183 Result += "\tchar *ivar_type;\n";
1184 Result += "\tint ivar_offset;\n";
1185 Result += "};\n";
1186
1187 /* struct _objc_ivar_list {
1188 int ivar_count;
1189 struct _objc_ivar ivar_list[];
1190 };
1191 */
1192 Result += "\nstruct _objc_ivar_list {\n";
1193 Result += "\tint ivar_count;\n";
1194 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001195 objc_ivar = true;
1196 }
1197
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001198 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1199 Result += IDecl->getName();
1200 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1201 "{\n\t";
1202 Result += utostr(NumIvars);
1203 Result += "\n";
1204
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001205 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1206 ? IDecl->getImplDeclIVars()
1207 : CDecl->getIntfDeclIvars();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001208 Result += "\t,{{\"";
1209 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001210 Result += "\", \"";
1211 std::string StrEncoding;
1212 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1213 Result += StrEncoding;
1214 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001215 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1216 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001217 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001218 Result += "\t ,{\"";
1219 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001220 Result += "\", \"";
1221 std::string StrEncoding;
1222 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1223 Result += StrEncoding;
1224 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001225 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1226 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001227 }
1228
1229 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001230 }
1231
1232 // Build _objc_method_list for class's instance methods if needed
1233 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1234 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001235 true,
1236 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001237
1238 // Build _objc_method_list for class's class methods if needed
1239 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001240 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001241 false,
1242 "", IDecl->getName(), Result);
1243
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001244 // Protocols referenced in class declaration?
1245 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1246 CDecl->getNumIntfRefProtocols(),
1247 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001248 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001249
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001250
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001251 // Declaration of class/meta-class metadata
1252 /* struct _objc_class {
1253 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001254 const char *super_class_name;
1255 char *name;
1256 long version;
1257 long info;
1258 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001259 struct _objc_ivar_list *ivars;
1260 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001261 struct objc_cache *cache;
1262 struct objc_protocol_list *protocols;
1263 const char *ivar_layout;
1264 struct _objc_class_ext *ext;
1265 };
1266 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001267 static bool objc_class = false;
1268 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001269 Result += "\nstruct _objc_class {\n";
1270 Result += "\tstruct _objc_class *isa;\n";
1271 Result += "\tconst char *super_class_name;\n";
1272 Result += "\tchar *name;\n";
1273 Result += "\tlong version;\n";
1274 Result += "\tlong info;\n";
1275 Result += "\tlong instance_size;\n";
1276 Result += "\tstruct _objc_ivar_list *ivars;\n";
1277 Result += "\tstruct _objc_method_list *methods;\n";
1278 Result += "\tstruct objc_cache *cache;\n";
1279 Result += "\tstruct _objc_protocol_list *protocols;\n";
1280 Result += "\tconst char *ivar_layout;\n";
1281 Result += "\tstruct _objc_class_ext *ext;\n";
1282 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001283 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001284 }
1285
1286 // Meta-class metadata generation.
1287 ObjcInterfaceDecl *RootClass = 0;
1288 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1289 while (SuperClass) {
1290 RootClass = SuperClass;
1291 SuperClass = SuperClass->getSuperClass();
1292 }
1293 SuperClass = CDecl->getSuperClass();
1294
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001295 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1296 Result += CDecl->getName();
1297 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1298 "{\n\t(struct _objc_class *)\"";
1299 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1300 Result += "\"";
1301
1302 if (SuperClass) {
1303 Result += ", \"";
1304 Result += SuperClass->getName();
1305 Result += "\", \"";
1306 Result += CDecl->getName();
1307 Result += "\"";
1308 }
1309 else {
1310 Result += ", 0, \"";
1311 Result += CDecl->getName();
1312 Result += "\"";
1313 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001314 // TODO: 'ivars' field for root class is currently set to 0.
1315 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001316 Result += ", 0,2, sizeof(struct _objc_class), 0";
1317 if (CDecl->getNumClassMethods() > 0) {
1318 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1319 Result += CDecl->getName();
1320 Result += "\n";
1321 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001322 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001323 Result += ", 0\n";
1324 if (CDecl->getNumIntfRefProtocols() > 0) {
1325 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1326 Result += CDecl->getName();
1327 Result += ",0,0\n";
1328 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001329 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001330 Result += "\t,0,0,0,0\n";
1331 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001332
1333 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001334 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1335 Result += CDecl->getName();
1336 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1337 "{\n\t&_OBJC_METACLASS_";
1338 Result += CDecl->getName();
1339 if (SuperClass) {
1340 Result += ", \"";
1341 Result += SuperClass->getName();
1342 Result += "\", \"";
1343 Result += CDecl->getName();
1344 Result += "\"";
1345 }
1346 else {
1347 Result += ", 0, \"";
1348 Result += CDecl->getName();
1349 Result += "\"";
1350 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001351 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001352 Result += ", 0,1";
1353 if (!ObjcSynthesizedStructs.count(CDecl))
1354 Result += ",0";
1355 else {
1356 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001357 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001358 Result += CDecl->getName();
1359 Result += ")";
1360 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001361 if (NumIvars > 0) {
1362 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1363 Result += CDecl->getName();
1364 Result += "\n\t";
1365 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001366 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001367 Result += ",0";
1368 if (IDecl->getNumInstanceMethods() > 0) {
1369 Result += ", &_OBJC_INSTANCE_METHODS_";
1370 Result += CDecl->getName();
1371 Result += ", 0\n\t";
1372 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001373 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001374 Result += ",0,0";
1375 if (CDecl->getNumIntfRefProtocols() > 0) {
1376 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1377 Result += CDecl->getName();
1378 Result += ", 0,0\n";
1379 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001380 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001381 Result += ",0,0,0\n";
1382 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001383}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001384
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001385void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001386 int ClsDefCount = ClassImplementation.size();
1387 int CatDefCount = CategoryImplementation.size();
1388 if (ClsDefCount == 0 && CatDefCount == 0)
1389 return;
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001390
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001391 // TODO: This is temporary until we decide how to access objc types in a
1392 // c program
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001393 Result += "#include <Objc/objc.h>\n";
1394 // This is needed for use of offsetof
1395 Result += "#include <stddef.h>\n";
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001396
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001397 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001398 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001399 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001400
1401 // For each implemented category, write out all its meta data.
1402 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001403 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001404
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001405 // Write objc_symtab metadata
1406 /*
1407 struct _objc_symtab
1408 {
1409 long sel_ref_cnt;
1410 SEL *refs;
1411 short cls_def_cnt;
1412 short cat_def_cnt;
1413 void *defs[cls_def_cnt + cat_def_cnt];
1414 };
1415 */
1416
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001417 Result += "\nstruct _objc_symtab {\n";
1418 Result += "\tlong sel_ref_cnt;\n";
1419 Result += "\tSEL *refs;\n";
1420 Result += "\tshort cls_def_cnt;\n";
1421 Result += "\tshort cat_def_cnt;\n";
1422 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1423 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001424
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001425 Result += "static struct _objc_symtab "
1426 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1427 Result += "\t0, 0, " + utostr(ClsDefCount)
1428 + ", " + utostr(CatDefCount) + "\n";
1429 for (int i = 0; i < ClsDefCount; i++) {
1430 Result += "\t,&_OBJC_CLASS_";
1431 Result += ClassImplementation[i]->getName();
1432 Result += "\n";
1433 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001434
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001435 for (int i = 0; i < CatDefCount; i++) {
1436 Result += "\t,&_OBJC_CATEGORY_";
1437 Result += CategoryImplementation[i]->getClassInterface()->getName();
1438 Result += "_";
1439 Result += CategoryImplementation[i]->getName();
1440 Result += "\n";
1441 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001442
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001443 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001444
1445 // Write objc_module metadata
1446
1447 /*
1448 struct _objc_module {
1449 long version;
1450 long size;
1451 const char *name;
1452 struct _objc_symtab *symtab;
1453 }
1454 */
1455
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001456 Result += "\nstruct _objc_module {\n";
1457 Result += "\tlong version;\n";
1458 Result += "\tlong size;\n";
1459 Result += "\tconst char *name;\n";
1460 Result += "\tstruct _objc_symtab *symtab;\n";
1461 Result += "};\n\n";
1462 Result += "static struct _objc_module "
1463 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001464 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1465 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001466 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001467}
Chris Lattner6fe8b272007-10-16 22:36:42 +00001468