blob: d3455af69a1b643e69c05ff5693046179684f598 [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 Naroff0744c472007-11-04 22:37:50 +000058 const char *s = "extern struct objc_object *objc_msgSend"
59 "(struct objc_object *, struct objc_selector *, ...);\n"
60 "extern struct objc_object *objc_getClass"
61 "(const char *);\n";
62 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
63 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +000064 }
Chris Lattner569faa62007-10-11 18:38:32 +000065
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000066 // Top Level Driver code.
67 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000068 void HandleDeclInMainFile(Decl *D);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000069 ~RewriteTest();
70
71 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +000072 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +000073 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000074 void RewriteTabs();
75 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +000076 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff667f1682007-10-30 13:30:57 +000077 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +000078 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff667f1682007-10-30 13:30:57 +000079 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Steve Naroff02a82aa2007-10-30 23:14:51 +000080 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffc8a92d12007-11-01 13:24:47 +000081 void RewriteObjcQualifiedInterfaceTypes(
82 const FunctionTypeProto *proto, FunctionDecl *FD);
83 bool needToScanForQualifiers(QualType T);
Chris Lattner6fe8b272007-10-16 22:36:42 +000084
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000085 // Expression Rewriting.
Chris Lattner0021f452007-10-24 16:57:36 +000086 Stmt *RewriteFunctionBody(Stmt *S);
87 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
88 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +000089 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Steve Naroff71226032007-10-24 22:48:43 +000090 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
91 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +000092 void SynthMsgSendFunctionDecl();
93 void SynthGetClassFunctionDecl();
94
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000095 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +000096 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
97 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +000098
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +000099 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
100 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000101
102 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
103 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000104 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000105 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000106 const char *ClassName,
107 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000108
109 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
110 int NumProtocols,
111 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000112 const char *ClassName,
113 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000114 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
115 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000116 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
117 ObjcIvarDecl *ivar,
118 std::string &Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000119 void WriteObjcMetaData(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000120 };
121}
122
Chris Lattner569faa62007-10-11 18:38:32 +0000123ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000124
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000125//===----------------------------------------------------------------------===//
126// Top Level Driver Code
127//===----------------------------------------------------------------------===//
128
Chris Lattner569faa62007-10-11 18:38:32 +0000129void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000130 // Two cases: either the decl could be in the main file, or it could be in a
131 // #included file. If the former, rewrite it now. If the later, check to see
132 // if we rewrote the #include/#import.
133 SourceLocation Loc = D->getLocation();
134 Loc = SM->getLogicalLoc(Loc);
135
136 // If this is for a builtin, ignore it.
137 if (Loc.isInvalid()) return;
138
Steve Naroffe9780582007-10-23 23:50:29 +0000139 // Look for built-in declarations that we need to refer during the rewrite.
140 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000141 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000142 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
143 // declared in <Foundation/NSString.h>
144 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
145 ConstantStringClassReference = FVD;
146 return;
147 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000148 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
149 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000150 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
151 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000152 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
153 RewriteProtocolDecl(PD);
Steve Naroffe9780582007-10-23 23:50:29 +0000154 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000155 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000156 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
157 return HandleDeclInMainFile(D);
158
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000159 // Otherwise, see if there is a #import in the main file that should be
160 // rewritten.
Chris Lattner74db1682007-10-16 21:07:07 +0000161 RewriteInclude(Loc);
162}
163
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000164/// HandleDeclInMainFile - This is called for each top-level decl defined in the
165/// main file of the input.
166void RewriteTest::HandleDeclInMainFile(Decl *D) {
167 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
168 if (Stmt *Body = FD->getBody())
169 FD->setBody(RewriteFunctionBody(Body));
170
171 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
172 ClassImplementation.push_back(CI);
173 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
174 CategoryImplementation.push_back(CI);
175 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
176 RewriteForwardClassDecl(CD);
177 // Nothing yet.
178}
179
180RewriteTest::~RewriteTest() {
181 // Get the top-level buffer that this corresponds to.
182 RewriteTabs();
183
184 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
185 // we are done.
186 if (const RewriteBuffer *RewriteBuf =
187 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000188 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000189 std::string S(RewriteBuf->begin(), RewriteBuf->end());
190 printf("%s\n", S.c_str());
191 } else {
192 printf("No changes\n");
193 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000194
195}
196
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000197//===----------------------------------------------------------------------===//
198// Syntactic (non-AST) Rewriting Code
199//===----------------------------------------------------------------------===//
200
Chris Lattner74db1682007-10-16 21:07:07 +0000201void RewriteTest::RewriteInclude(SourceLocation Loc) {
202 // Rip up the #include stack to the main file.
203 SourceLocation IncLoc = Loc, NextLoc = Loc;
204 do {
205 IncLoc = Loc;
206 Loc = SM->getLogicalLoc(NextLoc);
207 NextLoc = SM->getIncludeLoc(Loc);
208 } while (!NextLoc.isInvalid());
209
210 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
211 // IncLoc indicates the header that was included if it is useful.
212 IncLoc = SM->getLogicalLoc(IncLoc);
213 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
214 Loc == LastIncLoc)
215 return;
216 LastIncLoc = Loc;
217
218 unsigned IncCol = SM->getColumnNumber(Loc);
219 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
220
221 // Replace the #import with #include.
222 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
223}
224
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000225void RewriteTest::RewriteTabs() {
226 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
227 const char *MainBufStart = MainBuf.first;
228 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000229
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000230 // Loop over the whole file, looking for tabs.
231 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
232 if (*BufPtr != '\t')
233 continue;
234
235 // Okay, we found a tab. This tab will turn into at least one character,
236 // but it depends on which 'virtual column' it is in. Compute that now.
237 unsigned VCol = 0;
238 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
239 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
240 ++VCol;
241
242 // Okay, now that we know the virtual column, we know how many spaces to
243 // insert. We assume 8-character tab-stops.
244 unsigned Spaces = 8-(VCol & 7);
245
246 // Get the location of the tab.
247 SourceLocation TabLoc =
248 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
249
250 // Rewrite the single tab character into a sequence of spaces.
251 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
252 }
Chris Lattner569faa62007-10-11 18:38:32 +0000253}
254
255
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000256void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
257 int numDecls = ClassDecl->getNumForwardDecls();
258 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
259
260 // Get the start location and compute the semi location.
261 SourceLocation startLoc = ClassDecl->getLocation();
262 const char *startBuf = SM->getCharacterData(startLoc);
263 const char *semiPtr = strchr(startBuf, ';');
264
265 // Translate to typedef's that forward reference structs with the same name
266 // as the class. As a convenience, we include the original declaration
267 // as a comment.
268 std::string typedefString;
269 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000270 typedefString.append(startBuf, semiPtr-startBuf+1);
271 typedefString += "\n";
272 for (int i = 0; i < numDecls; i++) {
273 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff809b4f02007-10-31 22:11:35 +0000274 if (ObjcForwardDecls.count(ForwardDecl))
275 continue;
Steve Naroff71226032007-10-24 22:48:43 +0000276 typedefString += "typedef struct ";
277 typedefString += ForwardDecl->getName();
278 typedefString += " ";
279 typedefString += ForwardDecl->getName();
280 typedefString += ";\n";
Steve Naroff809b4f02007-10-31 22:11:35 +0000281
282 // Mark this typedef as having been generated.
283 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000284 assert(false && "typedef already output");
Steve Naroff71226032007-10-24 22:48:43 +0000285 }
286
287 // Replace the @class with typedefs corresponding to the classes.
288 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
289 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000290}
291
Steve Naroff667f1682007-10-30 13:30:57 +0000292void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
293 for (int i = 0; i < nMethods; i++) {
294 ObjcMethodDecl *Method = Methods[i];
295 SourceLocation Loc = Method->getLocStart();
296
297 Rewrite.ReplaceText(Loc, 0, "// ", 3);
298
299 // FIXME: handle methods that are declared across multiple lines.
300 }
301}
302
303void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
304 SourceLocation LocStart = CatDecl->getLocStart();
305
306 // FIXME: handle category headers that are declared across multiple lines.
307 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
308
309 RewriteMethods(CatDecl->getNumInstanceMethods(),
310 CatDecl->getInstanceMethods());
311 RewriteMethods(CatDecl->getNumClassMethods(),
312 CatDecl->getClassMethods());
313 // Lastly, comment out the @end.
314 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
315}
316
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000317void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
318 SourceLocation LocStart = PDecl->getLocStart();
319
320 // FIXME: handle protocol headers that are declared across multiple lines.
321 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
322
323 RewriteMethods(PDecl->getNumInstanceMethods(),
324 PDecl->getInstanceMethods());
325 RewriteMethods(PDecl->getNumClassMethods(),
326 PDecl->getClassMethods());
327 // Lastly, comment out the @end.
328 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
329}
330
Steve Naroff3774dd92007-10-26 20:53:56 +0000331void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000332
333 SourceLocation LocStart = ClassDecl->getLocStart();
334 SourceLocation LocEnd = ClassDecl->getLocEnd();
335
336 const char *startBuf = SM->getCharacterData(LocStart);
337 const char *endBuf = SM->getCharacterData(LocEnd);
338
Steve Naroff1ccf4632007-10-30 03:43:13 +0000339 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Naroffef20ed32007-10-30 02:23:23 +0000340
341 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000342 if (!ObjcForwardDecls.count(ClassDecl)) {
343 // we haven't seen a forward decl - generate a typedef.
344 ResultStr += "typedef struct ";
345 ResultStr += ClassDecl->getName();
346 ResultStr += " ";
347 ResultStr += ClassDecl->getName();
348 ResultStr += ";";
349
350 // Mark this typedef as having been generated.
351 ObjcForwardDecls.insert(ClassDecl);
352 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000353 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
354
Steve Naroff1ccf4632007-10-30 03:43:13 +0000355 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Naroffef20ed32007-10-30 02:23:23 +0000356 ResultStr.c_str(), ResultStr.size());
357
Steve Naroff667f1682007-10-30 13:30:57 +0000358 RewriteMethods(ClassDecl->getNumInstanceMethods(),
359 ClassDecl->getInstanceMethods());
360 RewriteMethods(ClassDecl->getNumClassMethods(),
361 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000362
Steve Naroff1ccf4632007-10-30 03:43:13 +0000363 // Lastly, comment out the @end.
364 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000365}
366
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000367//===----------------------------------------------------------------------===//
368// Function Body / Expression rewriting
369//===----------------------------------------------------------------------===//
370
Chris Lattner0021f452007-10-24 16:57:36 +0000371Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000372 // Otherwise, just rewrite all children.
373 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
374 CI != E; ++CI)
Chris Lattnere33506b2007-10-17 21:28:00 +0000375 if (*CI)
Chris Lattner0021f452007-10-24 16:57:36 +0000376 *CI = RewriteFunctionBody(*CI);
Steve Naroffe9780582007-10-23 23:50:29 +0000377
378 // Handle specific things.
379 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
380 return RewriteAtEncode(AtEncode);
Steve Naroff0add5d22007-11-03 11:27:19 +0000381
382 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
383 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000384
Steve Naroff71226032007-10-24 22:48:43 +0000385 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
386 // Before we rewrite it, put the original message expression in a comment.
387 SourceLocation startLoc = MessExpr->getLocStart();
388 SourceLocation endLoc = MessExpr->getLocEnd();
389
390 const char *startBuf = SM->getCharacterData(startLoc);
391 const char *endBuf = SM->getCharacterData(endLoc);
392
393 std::string messString;
394 messString += "// ";
395 messString.append(startBuf, endBuf-startBuf+1);
396 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000397
Steve Naroff71226032007-10-24 22:48:43 +0000398 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
399 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
400 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000401 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000402 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000403 }
Chris Lattner0021f452007-10-24 16:57:36 +0000404 // Return this stmt unmodified.
405 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000406}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000407
Chris Lattner0021f452007-10-24 16:57:36 +0000408Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000409 // Create a new string expression.
410 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000411 std::string StrEncoding;
412 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
413 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
414 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000415 SourceLocation(), SourceLocation());
416 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattner0021f452007-10-24 16:57:36 +0000417 delete Exp;
418 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000419}
420
Steve Naroff71226032007-10-24 22:48:43 +0000421CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
422 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000423 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000424 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000425
426 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000427 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000428
429 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000430 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000431 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
432
433 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000434
Steve Naroff71226032007-10-24 22:48:43 +0000435 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
436}
437
Steve Naroffc8a92d12007-11-01 13:24:47 +0000438static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
439 const char *&startRef, const char *&endRef) {
440 while (startBuf < endBuf) {
441 if (*startBuf == '<')
442 startRef = startBuf; // mark the start.
443 if (*startBuf == '>') {
444 assert((startRef && *startRef == '<') && "rewrite scanning error");
445 endRef = startBuf; // mark the end.
446 return true;
447 }
448 startBuf++;
449 }
450 return false;
451}
452
453bool RewriteTest::needToScanForQualifiers(QualType T) {
454 // FIXME: we don't currently represent "id <Protocol>" in the type system.
455 if (T == Context->getObjcIdType())
456 return true;
457
458 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000459 Type *pointeeType = pType->getPointeeType().getTypePtr();
460 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
461 return true; // we have "Class <Protocol> *".
462 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000463 return false;
464}
465
466void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
467 const FunctionTypeProto *proto, FunctionDecl *FD) {
468
469 if (needToScanForQualifiers(proto->getResultType())) {
470 // Since types are unique, we need to scan the buffer.
471 SourceLocation Loc = FD->getLocation();
472
473 const char *endBuf = SM->getCharacterData(Loc);
474 const char *startBuf = endBuf;
475 while (*startBuf != ';')
476 startBuf--; // scan backward (from the decl location) for return type.
477 const char *startRef = 0, *endRef = 0;
478 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
479 // Get the locations of the startRef, endRef.
480 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
481 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
482 // Comment out the protocol references.
483 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
484 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000485 }
486 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000487 // Now check arguments.
488 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
489 if (needToScanForQualifiers(proto->getArgType(i))) {
490 // Since types are unique, we need to scan the buffer.
491 SourceLocation Loc = FD->getLocation();
492
493 const char *startBuf = SM->getCharacterData(Loc);
494 const char *endBuf = startBuf;
495 while (*endBuf != ';')
496 endBuf++; // scan forward (from the decl location) for argument types.
497 const char *startRef = 0, *endRef = 0;
498 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
499 // Get the locations of the startRef, endRef.
500 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
501 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
502 // Comment out the protocol references.
503 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
504 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
505 }
506 }
507 }
Steve Naroff05d6ff52007-10-31 04:38:33 +0000508}
509
Steve Naroff02a82aa2007-10-30 23:14:51 +0000510void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
511 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +0000512 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000513 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +0000514 return;
515 }
516 // Check for ObjC 'id' and class types that have been adorned with protocol
517 // information (id<p>, C<p>*). The protocol references need to be rewritten!
518 const FunctionType *funcType = FD->getType()->getAsFunctionType();
519 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +0000520 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
521 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000522}
523
524// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
525void RewriteTest::SynthMsgSendFunctionDecl() {
526 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
527 llvm::SmallVector<QualType, 16> ArgTys;
528 QualType argT = Context->getObjcIdType();
529 assert(!argT.isNull() && "Can't find 'id' type");
530 ArgTys.push_back(argT);
531 argT = Context->getObjcSelType();
532 assert(!argT.isNull() && "Can't find 'SEL' type");
533 ArgTys.push_back(argT);
534 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
535 &ArgTys[0], ArgTys.size(),
536 true /*isVariadic*/);
537 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
538 msgSendIdent, msgSendType,
539 FunctionDecl::Extern, false, 0);
540}
541
542// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
543void RewriteTest::SynthGetClassFunctionDecl() {
544 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
545 llvm::SmallVector<QualType, 16> ArgTys;
546 ArgTys.push_back(Context->getPointerType(
547 Context->CharTy.getQualifiedType(QualType::Const)));
548 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
549 &ArgTys[0], ArgTys.size(),
550 false /*isVariadic*/);
551 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
552 getClassIdent, getClassType,
553 FunctionDecl::Extern, false, 0);
554}
555
Steve Naroff0add5d22007-11-03 11:27:19 +0000556Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
557 assert(ConstantStringClassReference && "Can't find constant string reference");
558 llvm::SmallVector<Expr*, 4> InitExprs;
559
560 // Synthesize "(Class)&_NSConstantStringClassReference"
561 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
562 ConstantStringClassReference->getType(),
563 SourceLocation());
564 QualType expType = Context->getPointerType(ClsRef->getType());
565 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
566 expType, SourceLocation());
567 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
568 SourceLocation());
569 InitExprs.push_back(cast); // set the 'isa'.
570 InitExprs.push_back(Exp->getString()); // set "char *bytes".
571 unsigned IntSize = static_cast<unsigned>(
572 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
573 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
574 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
575 Exp->getLocStart());
576 InitExprs.push_back(len); // set "int numBytes".
577
578 // struct NSConstantString
579 QualType CFConstantStrType = Context->getCFConstantStringType();
580 // (struct NSConstantString) { <exprs from above> }
581 InitListExpr *ILE = new InitListExpr(SourceLocation(),
582 &InitExprs[0], InitExprs.size(),
583 SourceLocation());
584 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
585 // struct NSConstantString *
586 expType = Context->getPointerType(StrRep->getType());
587 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
588 SourceLocation());
589 // struct NSString *
590 if (!NSStringRecord)
591 NSStringRecord = new RecordDecl(Decl::Struct, SourceLocation(),
592 &Context->Idents.get("NSString"), 0);
593 expType = Context->getPointerType(Context->getTagDeclType(NSStringRecord));
594 cast = new CastExpr(expType, Unop, SourceLocation());
595 Rewrite.ReplaceStmt(Exp, cast);
596 delete Exp;
597 return StrRep;
598}
599
Steve Naroff71226032007-10-24 22:48:43 +0000600Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000601 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +0000602 if (!MsgSendFunctionDecl)
603 SynthMsgSendFunctionDecl();
604 if (!GetClassFunctionDecl)
605 SynthGetClassFunctionDecl();
Steve Naroff71226032007-10-24 22:48:43 +0000606
607 // Synthesize a call to objc_msgSend().
608 llvm::SmallVector<Expr*, 8> MsgExprs;
609 IdentifierInfo *clsName = Exp->getClassName();
610
611 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
612 if (clsName) { // class message.
613 llvm::SmallVector<Expr*, 8> ClsExprs;
614 QualType argType = Context->getPointerType(Context->CharTy);
615 ClsExprs.push_back(new StringLiteral(clsName->getName(),
616 clsName->getLength(),
617 false, argType, SourceLocation(),
618 SourceLocation()));
619 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
620 &ClsExprs[0], ClsExprs.size());
621 MsgExprs.push_back(Cls);
622 } else // instance message.
623 MsgExprs.push_back(Exp->getReceiver());
624
Steve Naroff0add5d22007-11-03 11:27:19 +0000625 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +0000626 llvm::SmallVector<Expr*, 8> SelExprs;
627 QualType argType = Context->getPointerType(Context->CharTy);
628 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
629 Exp->getSelector().getName().size(),
630 false, argType, SourceLocation(),
631 SourceLocation()));
632 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
633 &SelExprs[0], SelExprs.size());
634 MsgExprs.push_back(SelExp);
635
636 // Now push any user supplied arguments.
637 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
638 MsgExprs.push_back(Exp->getArg(i));
639 // We've transferred the ownership to MsgExprs. Null out the argument in
640 // the original expression, since we will delete it below.
641 Exp->setArg(i, 0);
642 }
Steve Naroff0744c472007-11-04 22:37:50 +0000643 // Generate the funky cast.
644 CastExpr *cast;
645 llvm::SmallVector<QualType, 8> ArgTypes;
646 QualType returnType;
647
648 // Push 'id' and 'SEL', the 2 implicit arguments.
649 ArgTypes.push_back(Context->getObjcIdType());
650 ArgTypes.push_back(Context->getObjcSelType());
651 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
652 // Push any user argument types.
653 for (int i = 0; i < mDecl->getNumParams(); i++)
654 ArgTypes.push_back(mDecl->getParamDecl(i)->getType());
655 returnType = mDecl->getResultType();
656 } else {
657 returnType = Context->getObjcIdType();
658 }
659 // Get the type, we will need to reference it in a couple spots.
660 QualType msgSendType = MsgSendFunctionDecl->getType();
661
662 // Create a reference to the objc_msgSend() declaration.
663 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
664
665 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
666 // If we don't do this cast, we get the following bizarre warning/note:
667 // xx.m:13: warning: function called through a non-compatible type
668 // xx.m:13: note: if this code is reached, the program will abort
669 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
670 SourceLocation());
671
672 // Now do the "normal" pointer to function cast.
673 QualType castType = Context->getFunctionType(returnType,
674 &ArgTypes[0], ArgTypes.size(),
675 false/*FIXME:variadic*/);
676 castType = Context->getPointerType(castType);
677 cast = new CastExpr(castType, cast, SourceLocation());
678
679 // Don't forget the parens to enforce the proper binding.
680 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
681
682 const FunctionType *FT = msgSendType->getAsFunctionType();
683 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
684 FT->getResultType(), SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +0000685 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +0000686 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +0000687
Chris Lattner0021f452007-10-24 16:57:36 +0000688 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +0000689 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +0000690}
691
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000692/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
693/// an objective-c class with ivars.
694void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
695 std::string &Result) {
696 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
697 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +0000698 // Do not synthesize more than once.
699 if (ObjcSynthesizedStructs.count(CDecl))
700 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000701 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
702 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
703 // Do it for the root
704 SynthesizeObjcInternalStruct(RCDecl, Result);
705 }
706
707 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000708 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanian2fd0daa2007-10-31 23:53:01 +0000709 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000710 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
711 return;
712
Steve Naroffb1147382007-11-01 17:12:31 +0000713 Result += "\nstruct ";
714 Result += CDecl->getName();
715 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
716 Result += " {\n struct ";
717 Result += RCDecl->getName();
718 Result += " _";
719 Result += RCDecl->getName();
720 Result += ";\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000721 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +0000722 else
723 Result += " {";
Steve Naroff809b4f02007-10-31 22:11:35 +0000724
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +0000725 if (NumIvars > 0) {
726 SourceLocation LocStart = CDecl->getLocStart();
727 SourceLocation LocEnd = CDecl->getLocEnd();
728
729 const char *startBuf = SM->getCharacterData(LocStart);
730 const char *endBuf = SM->getCharacterData(LocEnd);
731 startBuf = strchr(startBuf, '{');
732 assert((startBuf && endBuf)
733 && "SynthesizeObjcInternalStruct - malformed @interface");
734 startBuf++; // past '{'
735 while (startBuf < endBuf) {
736 if (*startBuf == '@') {
737 startBuf = strchr(startBuf, 'p');
738 // FIXME: presence of @public, etc. inside comment results in
739 // this transformation as well, which is still correct c-code.
740 if (!strncmp(startBuf, "public", strlen("public"))) {
741 startBuf += strlen("public");
742 Result += "/* @public */";
743 }
744 else if (!strncmp(startBuf, "private", strlen("private"))) {
745 startBuf += strlen("private");
746 Result += "/* @private */";
747 }
748 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
749 startBuf += strlen("protected");
750 Result += "/* @protected */";
751 }
752 }
753 Result += *startBuf++;
754 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000755 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +0000756
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000757 Result += "};\n";
758 // Mark this struct as having been generated.
759 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000760 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000761}
762
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000763// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
764/// class methods.
765void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
766 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000767 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000768 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000769 const char *ClassName,
770 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000771 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000772 if (NumMethods > 0 && !objc_impl_method) {
773 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000774 SEL _cmd;
775 char *method_types;
776 void *_imp;
777 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000778 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000779 Result += "\nstruct _objc_method {\n";
780 Result += "\tSEL _cmd;\n";
781 Result += "\tchar *method_types;\n";
782 Result += "\tvoid *_imp;\n";
783 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000784
785 /* struct _objc_method_list {
786 struct _objc_method_list *next_method;
787 int method_count;
788 struct _objc_method method_list[];
789 }
790 */
791 Result += "\nstruct _objc_method_list {\n";
792 Result += "\tstruct _objc_method_list *next_method;\n";
793 Result += "\tint method_count;\n";
794 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000795 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +0000796 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000797 // Build _objc_method_list for class's methods if needed
798 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000799 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000800 Result += prefix;
801 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
802 Result += "_METHODS_";
803 Result += ClassName;
804 Result += " __attribute__ ((section (\"__OBJC, __";
805 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000806 Result += "_meth\")))= ";
807 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
808
809 Result += "\t,{{(SEL)\"";
810 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000811 std::string MethodTypeString;
812 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
813 Result += "\", \"";
814 Result += MethodTypeString;
815 Result += "\", 0}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000816 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000817 // TODO: Need method address as 3rd initializer.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000818 Result += "\t ,{(SEL)\"";
819 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000820 std::string MethodTypeString;
821 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
822 Result += "\", \"";
823 Result += MethodTypeString;
824 Result += "\", 0}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000825 }
826 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000827 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000828}
829
830/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
831void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
832 int NumProtocols,
833 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000834 const char *ClassName,
835 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000836 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +0000837 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000838 for (int i = 0; i < NumProtocols; i++) {
839 ObjcProtocolDecl *PDecl = Protocols[i];
840 // Output struct protocol_methods holder of method selector and type.
841 if (!objc_protocol_methods &&
842 (PDecl->getNumInstanceMethods() > 0
843 || PDecl->getNumClassMethods() > 0)) {
844 /* struct protocol_methods {
845 SEL _cmd;
846 char *method_types;
847 }
848 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000849 Result += "\nstruct protocol_methods {\n";
850 Result += "\tSEL _cmd;\n";
851 Result += "\tchar *method_types;\n";
852 Result += "};\n";
853
854 /* struct _objc_protocol_method_list {
855 int protocol_method_count;
856 struct protocol_methods protocols[];
857 }
858 */
859 Result += "\nstruct _objc_protocol_method_list {\n";
860 Result += "\tint protocol_method_count;\n";
861 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000862 objc_protocol_methods = true;
863 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000864
Fariborz Jahanian04455192007-10-22 21:41:37 +0000865 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +0000866 int NumMethods = PDecl->getNumInstanceMethods();
867 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000868 Result += "\nstatic struct _objc_protocol_method_list "
869 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
870 Result += PDecl->getName();
871 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
872 "{\n\t" + utostr(NumMethods) + "\n";
873
Fariborz Jahanian04455192007-10-22 21:41:37 +0000874 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000875 Result += "\t,{{(SEL)\"";
876 Result += Methods[0]->getSelector().getName().c_str();
877 Result += "\", \"\"}\n";
878
879 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000880 Result += "\t ,{(SEL)\"";
881 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000882 std::string MethodTypeString;
883 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
884 Result += "\", \"";
885 Result += MethodTypeString;
886 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000887 }
888 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000889 }
890
891 // Output class methods declared in this protocol.
892 NumMethods = PDecl->getNumClassMethods();
893 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000894 Result += "\nstatic struct _objc_protocol_method_list "
895 "_OBJC_PROTOCOL_CLASS_METHODS_";
896 Result += PDecl->getName();
897 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
898 "{\n\t";
899 Result += utostr(NumMethods);
900 Result += "\n";
901
Fariborz Jahanian04455192007-10-22 21:41:37 +0000902 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000903 Result += "\t,{{(SEL)\"";
904 Result += Methods[0]->getSelector().getName().c_str();
905 Result += "\", \"\"}\n";
906
907 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000908 Result += "\t ,{(SEL)\"";
909 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +0000910 std::string MethodTypeString;
911 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
912 Result += "\", \"";
913 Result += MethodTypeString;
914 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000915 }
916 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000917 }
918 // Output:
919 /* struct _objc_protocol {
920 // Objective-C 1.0 extensions
921 struct _objc_protocol_extension *isa;
922 char *protocol_name;
923 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000924 struct _objc_protocol_method_list *instance_methods;
925 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +0000926 };
927 */
928 static bool objc_protocol = false;
929 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000930 Result += "\nstruct _objc_protocol {\n";
931 Result += "\tstruct _objc_protocol_extension *isa;\n";
932 Result += "\tchar *protocol_name;\n";
933 Result += "\tstruct _objc_protocol **protocol_list;\n";
934 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
935 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
936 Result += "};\n";
937
938 /* struct _objc_protocol_list {
939 struct _objc_protocol_list *next;
940 int protocol_count;
941 struct _objc_protocol *class_protocols[];
942 }
943 */
944 Result += "\nstruct _objc_protocol_list {\n";
945 Result += "\tstruct _objc_protocol_list *next;\n";
946 Result += "\tint protocol_count;\n";
947 Result += "\tstruct _objc_protocol *class_protocols[];\n";
948 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000949 objc_protocol = true;
950 }
951
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000952 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
953 Result += PDecl->getName();
954 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
955 "{\n\t0, \"";
956 Result += PDecl->getName();
957 Result += "\", 0, ";
958 if (PDecl->getInstanceMethods() > 0) {
959 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
960 Result += PDecl->getName();
961 Result += ", ";
962 }
Fariborz Jahanian04455192007-10-22 21:41:37 +0000963 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000964 Result += "0, ";
965 if (PDecl->getClassMethods() > 0) {
966 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
967 Result += PDecl->getName();
968 Result += "\n";
969 }
Fariborz Jahanian04455192007-10-22 21:41:37 +0000970 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000971 Result += "0\n";
972 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000973 }
Fariborz Jahanian04455192007-10-22 21:41:37 +0000974 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000975 Result += "\nstatic struct _objc_protocol_list _OBJC_";
976 Result += prefix;
977 Result += "_PROTOCOLS_";
978 Result += ClassName;
979 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
980 "{\n\t0, ";
981 Result += utostr(NumProtocols);
982 Result += "\n";
983
984 Result += "\t,{&_OBJC_PROTOCOL_";
985 Result += Protocols[0]->getName();
986 Result += " \n";
987
988 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +0000989 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000990 Result += "\t ,&_OBJC_PROTOCOL_";
991 Result += PDecl->getName();
992 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +0000993 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000994 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000995 }
996}
997
998/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
999/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001000void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1001 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001002 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1003 // Find category declaration for this implementation.
1004 ObjcCategoryDecl *CDecl;
1005 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1006 CDecl = CDecl->getNextClassCategory())
1007 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1008 break;
1009 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1010
1011 char *FullCategoryName = (char*)alloca(
1012 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1013 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1014
1015 // Build _objc_method_list for class's instance methods if needed
1016 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1017 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001018 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001019 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001020
1021 // Build _objc_method_list for class's class methods if needed
1022 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1023 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001024 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001025 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001026
1027 // Protocols referenced in class declaration?
1028 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1029 CDecl->getNumReferencedProtocols(),
1030 "CATEGORY",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001031 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001032
1033 /* struct _objc_category {
1034 char *category_name;
1035 char *class_name;
1036 struct _objc_method_list *instance_methods;
1037 struct _objc_method_list *class_methods;
1038 struct _objc_protocol_list *protocols;
1039 // Objective-C 1.0 extensions
1040 uint32_t size; // sizeof (struct _objc_category)
1041 struct _objc_property_list *instance_properties; // category's own
1042 // @property decl.
1043 };
1044 */
1045
1046 static bool objc_category = false;
1047 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001048 Result += "\nstruct _objc_category {\n";
1049 Result += "\tchar *category_name;\n";
1050 Result += "\tchar *class_name;\n";
1051 Result += "\tstruct _objc_method_list *instance_methods;\n";
1052 Result += "\tstruct _objc_method_list *class_methods;\n";
1053 Result += "\tstruct _objc_protocol_list *protocols;\n";
1054 Result += "\tunsigned int size;\n";
1055 Result += "\tstruct _objc_property_list *instance_properties;\n";
1056 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001057 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001058 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001059 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1060 Result += FullCategoryName;
1061 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1062 Result += IDecl->getName();
1063 Result += "\"\n\t, \"";
1064 Result += ClassDecl->getName();
1065 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001066
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001067 if (IDecl->getNumInstanceMethods() > 0) {
1068 Result += "\t, (struct _objc_method_list *)"
1069 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1070 Result += FullCategoryName;
1071 Result += "\n";
1072 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001073 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001074 Result += "\t, 0\n";
1075 if (IDecl->getNumClassMethods() > 0) {
1076 Result += "\t, (struct _objc_method_list *)"
1077 "&_OBJC_CATEGORY_CLASS_METHODS_";
1078 Result += FullCategoryName;
1079 Result += "\n";
1080 }
1081 else
1082 Result += "\t, 0\n";
1083
1084 if (CDecl->getNumReferencedProtocols() > 0) {
1085 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1086 Result += FullCategoryName;
1087 Result += "\n";
1088 }
1089 else
1090 Result += "\t, 0\n";
1091 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001092}
1093
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001094/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1095/// ivar offset.
1096void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1097 ObjcIvarDecl *ivar,
1098 std::string &Result) {
1099 Result += "offsetof(struct _interface_";
1100 Result += IDecl->getName();
1101 Result += ", ";
1102 Result += ivar->getName();
1103 Result += ")";
1104}
1105
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001106//===----------------------------------------------------------------------===//
1107// Meta Data Emission
1108//===----------------------------------------------------------------------===//
1109
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001110void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1111 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001112 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1113
1114 // Build _objc_ivar_list metadata for classes ivars if needed
1115 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1116 ? IDecl->getImplDeclNumIvars()
1117 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1118
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001119 SynthesizeObjcInternalStruct(CDecl, Result);
1120
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001121 if (NumIvars > 0) {
1122 static bool objc_ivar = false;
1123 if (!objc_ivar) {
1124 /* struct _objc_ivar {
1125 char *ivar_name;
1126 char *ivar_type;
1127 int ivar_offset;
1128 };
1129 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001130 Result += "\nstruct _objc_ivar {\n";
1131 Result += "\tchar *ivar_name;\n";
1132 Result += "\tchar *ivar_type;\n";
1133 Result += "\tint ivar_offset;\n";
1134 Result += "};\n";
1135
1136 /* struct _objc_ivar_list {
1137 int ivar_count;
1138 struct _objc_ivar ivar_list[];
1139 };
1140 */
1141 Result += "\nstruct _objc_ivar_list {\n";
1142 Result += "\tint ivar_count;\n";
1143 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001144 objc_ivar = true;
1145 }
1146
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001147 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1148 Result += IDecl->getName();
1149 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1150 "{\n\t";
1151 Result += utostr(NumIvars);
1152 Result += "\n";
1153
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001154 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1155 ? IDecl->getImplDeclIVars()
1156 : CDecl->getIntfDeclIvars();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001157 Result += "\t,{{\"";
1158 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001159 Result += "\", \"";
1160 std::string StrEncoding;
1161 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1162 Result += StrEncoding;
1163 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001164 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1165 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001166 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001167 Result += "\t ,{\"";
1168 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001169 Result += "\", \"";
1170 std::string StrEncoding;
1171 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1172 Result += StrEncoding;
1173 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001174 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1175 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001176 }
1177
1178 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001179 }
1180
1181 // Build _objc_method_list for class's instance methods if needed
1182 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1183 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001184 true,
1185 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001186
1187 // Build _objc_method_list for class's class methods if needed
1188 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001189 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001190 false,
1191 "", IDecl->getName(), Result);
1192
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001193 // Protocols referenced in class declaration?
1194 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1195 CDecl->getNumIntfRefProtocols(),
1196 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001197 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001198
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001199
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001200 // Declaration of class/meta-class metadata
1201 /* struct _objc_class {
1202 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001203 const char *super_class_name;
1204 char *name;
1205 long version;
1206 long info;
1207 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001208 struct _objc_ivar_list *ivars;
1209 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001210 struct objc_cache *cache;
1211 struct objc_protocol_list *protocols;
1212 const char *ivar_layout;
1213 struct _objc_class_ext *ext;
1214 };
1215 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001216 static bool objc_class = false;
1217 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001218 Result += "\nstruct _objc_class {\n";
1219 Result += "\tstruct _objc_class *isa;\n";
1220 Result += "\tconst char *super_class_name;\n";
1221 Result += "\tchar *name;\n";
1222 Result += "\tlong version;\n";
1223 Result += "\tlong info;\n";
1224 Result += "\tlong instance_size;\n";
1225 Result += "\tstruct _objc_ivar_list *ivars;\n";
1226 Result += "\tstruct _objc_method_list *methods;\n";
1227 Result += "\tstruct objc_cache *cache;\n";
1228 Result += "\tstruct _objc_protocol_list *protocols;\n";
1229 Result += "\tconst char *ivar_layout;\n";
1230 Result += "\tstruct _objc_class_ext *ext;\n";
1231 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001232 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001233 }
1234
1235 // Meta-class metadata generation.
1236 ObjcInterfaceDecl *RootClass = 0;
1237 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1238 while (SuperClass) {
1239 RootClass = SuperClass;
1240 SuperClass = SuperClass->getSuperClass();
1241 }
1242 SuperClass = CDecl->getSuperClass();
1243
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001244 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1245 Result += CDecl->getName();
1246 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1247 "{\n\t(struct _objc_class *)\"";
1248 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1249 Result += "\"";
1250
1251 if (SuperClass) {
1252 Result += ", \"";
1253 Result += SuperClass->getName();
1254 Result += "\", \"";
1255 Result += CDecl->getName();
1256 Result += "\"";
1257 }
1258 else {
1259 Result += ", 0, \"";
1260 Result += CDecl->getName();
1261 Result += "\"";
1262 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001263 // TODO: 'ivars' field for root class is currently set to 0.
1264 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001265 Result += ", 0,2, sizeof(struct _objc_class), 0";
1266 if (CDecl->getNumClassMethods() > 0) {
1267 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1268 Result += CDecl->getName();
1269 Result += "\n";
1270 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001271 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001272 Result += ", 0\n";
1273 if (CDecl->getNumIntfRefProtocols() > 0) {
1274 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1275 Result += CDecl->getName();
1276 Result += ",0,0\n";
1277 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001278 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001279 Result += "\t,0,0,0,0\n";
1280 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001281
1282 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001283 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1284 Result += CDecl->getName();
1285 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1286 "{\n\t&_OBJC_METACLASS_";
1287 Result += CDecl->getName();
1288 if (SuperClass) {
1289 Result += ", \"";
1290 Result += SuperClass->getName();
1291 Result += "\", \"";
1292 Result += CDecl->getName();
1293 Result += "\"";
1294 }
1295 else {
1296 Result += ", 0, \"";
1297 Result += CDecl->getName();
1298 Result += "\"";
1299 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001300 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001301 Result += ", 0,1";
1302 if (!ObjcSynthesizedStructs.count(CDecl))
1303 Result += ",0";
1304 else {
1305 // class has size. Must synthesize its size.
1306 Result += ",sizeof(struct _interface_";
1307 Result += CDecl->getName();
1308 Result += ")";
1309 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001310 if (NumIvars > 0) {
1311 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1312 Result += CDecl->getName();
1313 Result += "\n\t";
1314 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001315 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001316 Result += ",0";
1317 if (IDecl->getNumInstanceMethods() > 0) {
1318 Result += ", &_OBJC_INSTANCE_METHODS_";
1319 Result += CDecl->getName();
1320 Result += ", 0\n\t";
1321 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001322 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001323 Result += ",0,0";
1324 if (CDecl->getNumIntfRefProtocols() > 0) {
1325 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1326 Result += CDecl->getName();
1327 Result += ", 0,0\n";
1328 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001329 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001330 Result += ",0,0,0\n";
1331 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001332}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001333
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001334void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001335 int ClsDefCount = ClassImplementation.size();
1336 int CatDefCount = CategoryImplementation.size();
1337 if (ClsDefCount == 0 && CatDefCount == 0)
1338 return;
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001339
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001340 // TODO: This is temporary until we decide how to access objc types in a
1341 // c program
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001342 Result += "#include <Objc/objc.h>\n";
1343 // This is needed for use of offsetof
1344 Result += "#include <stddef.h>\n";
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001345
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001346 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001347 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001348 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001349
1350 // For each implemented category, write out all its meta data.
1351 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001352 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001353
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001354 // Write objc_symtab metadata
1355 /*
1356 struct _objc_symtab
1357 {
1358 long sel_ref_cnt;
1359 SEL *refs;
1360 short cls_def_cnt;
1361 short cat_def_cnt;
1362 void *defs[cls_def_cnt + cat_def_cnt];
1363 };
1364 */
1365
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001366 Result += "\nstruct _objc_symtab {\n";
1367 Result += "\tlong sel_ref_cnt;\n";
1368 Result += "\tSEL *refs;\n";
1369 Result += "\tshort cls_def_cnt;\n";
1370 Result += "\tshort cat_def_cnt;\n";
1371 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1372 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001373
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001374 Result += "static struct _objc_symtab "
1375 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1376 Result += "\t0, 0, " + utostr(ClsDefCount)
1377 + ", " + utostr(CatDefCount) + "\n";
1378 for (int i = 0; i < ClsDefCount; i++) {
1379 Result += "\t,&_OBJC_CLASS_";
1380 Result += ClassImplementation[i]->getName();
1381 Result += "\n";
1382 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001383
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001384 for (int i = 0; i < CatDefCount; i++) {
1385 Result += "\t,&_OBJC_CATEGORY_";
1386 Result += CategoryImplementation[i]->getClassInterface()->getName();
1387 Result += "_";
1388 Result += CategoryImplementation[i]->getName();
1389 Result += "\n";
1390 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001391
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001392 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001393
1394 // Write objc_module metadata
1395
1396 /*
1397 struct _objc_module {
1398 long version;
1399 long size;
1400 const char *name;
1401 struct _objc_symtab *symtab;
1402 }
1403 */
1404
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001405 Result += "\nstruct _objc_module {\n";
1406 Result += "\tlong version;\n";
1407 Result += "\tlong size;\n";
1408 Result += "\tconst char *name;\n";
1409 Result += "\tstruct _objc_symtab *symtab;\n";
1410 Result += "};\n\n";
1411 Result += "static struct _objc_module "
1412 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001413 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1414 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001415 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001416}
Chris Lattner6fe8b272007-10-16 22:36:42 +00001417