blob: 68ca1427320ad04c2d02aecf0118e3b259112553 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Steve Naroffebf2b562007-10-23 23:50:29 +000037
38 FunctionDecl *MsgSendFunctionDecl;
39 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000040 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000041
Steve Naroffbeaf2992007-11-03 11:27:19 +000042 // ObjC string constant support.
43 FileVarDecl *ConstantStringClassReference;
44 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000045
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000046 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000047 public:
Chris Lattner01c57482007-10-17 22:35:30 +000048 void Initialize(ASTContext &context, unsigned mainFileID) {
49 Context = &context;
50 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000051 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000052 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000053 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000054 SelGetUidFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000055 ConstantStringClassReference = 0;
56 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000057 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffab972d32007-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 Lattner77cd2a02007-10-11 00:43:27 +000064 }
Chris Lattner8a12c272007-10-11 18:38:32 +000065
Chris Lattnerf04da132007-10-24 17:06:59 +000066 // Top Level Driver code.
67 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000069 ~RewriteTest();
70
71 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000072 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000073 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000074 void RewriteTabs();
75 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000076 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000077 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000078 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000079 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Steve Naroff09b266e2007-10-30 23:14:51 +000080 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000081 void RewriteObjcQualifiedInterfaceTypes(
82 const FunctionTypeProto *proto, FunctionDecl *FD);
83 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000084
Chris Lattnerf04da132007-10-24 17:06:59 +000085 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000086 Stmt *RewriteFunctionBody(Stmt *S);
87 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
88 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +000089 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Steve Naroff934f2762007-10-24 22:48:43 +000090 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
91 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +000092 void SynthMsgSendFunctionDecl();
93 void SynthGetClassFunctionDecl();
94
Chris Lattnerf04da132007-10-24 17:06:59 +000095 // Metadata emission.
Steve Naroffbeaf2992007-11-03 11:27:19 +000096 void HandleObjcMetaDataEmission();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000097 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
98 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000099
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000100 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
101 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000102
103 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
104 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000105 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000106 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000107 const char *ClassName,
108 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000109
110 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
111 int NumProtocols,
112 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000113 const char *ClassName,
114 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000115 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
116 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000117 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
118 ObjcIvarDecl *ivar,
119 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000120 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000121 };
122}
123
Chris Lattner8a12c272007-10-11 18:38:32 +0000124ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000125
Chris Lattnerf04da132007-10-24 17:06:59 +0000126//===----------------------------------------------------------------------===//
127// Top Level Driver Code
128//===----------------------------------------------------------------------===//
129
Chris Lattner8a12c272007-10-11 18:38:32 +0000130void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000131 // Two cases: either the decl could be in the main file, or it could be in a
132 // #included file. If the former, rewrite it now. If the later, check to see
133 // if we rewrote the #include/#import.
134 SourceLocation Loc = D->getLocation();
135 Loc = SM->getLogicalLoc(Loc);
136
137 // If this is for a builtin, ignore it.
138 if (Loc.isInvalid()) return;
139
Steve Naroffebf2b562007-10-23 23:50:29 +0000140 // Look for built-in declarations that we need to refer during the rewrite.
141 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000142 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000143 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
144 // declared in <Foundation/NSString.h>
145 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
146 ConstantStringClassReference = FVD;
147 return;
148 }
Steve Naroffbef11852007-10-26 20:53:56 +0000149 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
150 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000151 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
152 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000153 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
154 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000155 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000156 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000157 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
158 return HandleDeclInMainFile(D);
159
Chris Lattnerf04da132007-10-24 17:06:59 +0000160 // Otherwise, see if there is a #import in the main file that should be
161 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000162 RewriteInclude(Loc);
163}
164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165/// HandleDeclInMainFile - This is called for each top-level decl defined in the
166/// main file of the input.
167void RewriteTest::HandleDeclInMainFile(Decl *D) {
168 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
169 if (Stmt *Body = FD->getBody())
170 FD->setBody(RewriteFunctionBody(Body));
171
172 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
173 ClassImplementation.push_back(CI);
174 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
175 CategoryImplementation.push_back(CI);
176 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
177 RewriteForwardClassDecl(CD);
178 // Nothing yet.
179}
180
181RewriteTest::~RewriteTest() {
182 // Get the top-level buffer that this corresponds to.
183 RewriteTabs();
184
185 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
186 // we are done.
187 if (const RewriteBuffer *RewriteBuf =
188 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000189 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000190 std::string S(RewriteBuf->begin(), RewriteBuf->end());
191 printf("%s\n", S.c_str());
192 } else {
193 printf("No changes\n");
194 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000195
196}
197
Steve Naroffbeaf2992007-11-03 11:27:19 +0000198/// HandleObjcMetaDataEmission - main routine to generate objective-c's
199/// metadata.
200void RewriteTest::HandleObjcMetaDataEmission() {
201 // Rewrite Objective-c meta data*
202 std::string ResultStr;
203 WriteObjcMetaData(ResultStr);
204 // For now just print the string out.
205 printf("%s", ResultStr.c_str());
206}
207
Chris Lattnerf04da132007-10-24 17:06:59 +0000208//===----------------------------------------------------------------------===//
209// Syntactic (non-AST) Rewriting Code
210//===----------------------------------------------------------------------===//
211
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000212void RewriteTest::RewriteInclude(SourceLocation Loc) {
213 // Rip up the #include stack to the main file.
214 SourceLocation IncLoc = Loc, NextLoc = Loc;
215 do {
216 IncLoc = Loc;
217 Loc = SM->getLogicalLoc(NextLoc);
218 NextLoc = SM->getIncludeLoc(Loc);
219 } while (!NextLoc.isInvalid());
220
221 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
222 // IncLoc indicates the header that was included if it is useful.
223 IncLoc = SM->getLogicalLoc(IncLoc);
224 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
225 Loc == LastIncLoc)
226 return;
227 LastIncLoc = Loc;
228
229 unsigned IncCol = SM->getColumnNumber(Loc);
230 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
231
232 // Replace the #import with #include.
233 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
234}
235
Chris Lattnerf04da132007-10-24 17:06:59 +0000236void RewriteTest::RewriteTabs() {
237 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
238 const char *MainBufStart = MainBuf.first;
239 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000240
Chris Lattnerf04da132007-10-24 17:06:59 +0000241 // Loop over the whole file, looking for tabs.
242 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
243 if (*BufPtr != '\t')
244 continue;
245
246 // Okay, we found a tab. This tab will turn into at least one character,
247 // but it depends on which 'virtual column' it is in. Compute that now.
248 unsigned VCol = 0;
249 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
250 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
251 ++VCol;
252
253 // Okay, now that we know the virtual column, we know how many spaces to
254 // insert. We assume 8-character tab-stops.
255 unsigned Spaces = 8-(VCol & 7);
256
257 // Get the location of the tab.
258 SourceLocation TabLoc =
259 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
260
261 // Rewrite the single tab character into a sequence of spaces.
262 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
263 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000264}
265
266
Chris Lattnerf04da132007-10-24 17:06:59 +0000267void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
268 int numDecls = ClassDecl->getNumForwardDecls();
269 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
270
271 // Get the start location and compute the semi location.
272 SourceLocation startLoc = ClassDecl->getLocation();
273 const char *startBuf = SM->getCharacterData(startLoc);
274 const char *semiPtr = strchr(startBuf, ';');
275
276 // Translate to typedef's that forward reference structs with the same name
277 // as the class. As a convenience, we include the original declaration
278 // as a comment.
279 std::string typedefString;
280 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000281 typedefString.append(startBuf, semiPtr-startBuf+1);
282 typedefString += "\n";
283 for (int i = 0; i < numDecls; i++) {
284 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000285 if (ObjcForwardDecls.count(ForwardDecl))
286 continue;
Steve Naroff934f2762007-10-24 22:48:43 +0000287 typedefString += "typedef struct ";
288 typedefString += ForwardDecl->getName();
289 typedefString += " ";
290 typedefString += ForwardDecl->getName();
291 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000292
293 // Mark this typedef as having been generated.
294 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000295 assert(false && "typedef already output");
Steve Naroff934f2762007-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 Lattnerf04da132007-10-24 17:06:59 +0000301}
302
Steve Naroff423cb562007-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 Naroff752d6ef2007-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 Naroffbef11852007-10-26 20:53:56 +0000342void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-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 Naroff2feac5e2007-10-30 03:43:13 +0000350 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000351
352 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000353 if (!ObjcForwardDecls.count(ClassDecl)) {
354 // we haven't seen a forward decl - generate a typedef.
355 ResultStr += "typedef struct ";
356 ResultStr += ClassDecl->getName();
357 ResultStr += " ";
358 ResultStr += ClassDecl->getName();
359 ResultStr += ";";
360
361 // Mark this typedef as having been generated.
362 ObjcForwardDecls.insert(ClassDecl);
363 }
Steve Narofff908a872007-10-30 02:23:23 +0000364 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
365
Steve Naroff2feac5e2007-10-30 03:43:13 +0000366 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000367 ResultStr.c_str(), ResultStr.size());
368
Steve Naroff423cb562007-10-30 13:30:57 +0000369 RewriteMethods(ClassDecl->getNumInstanceMethods(),
370 ClassDecl->getInstanceMethods());
371 RewriteMethods(ClassDecl->getNumClassMethods(),
372 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000373
Steve Naroff2feac5e2007-10-30 03:43:13 +0000374 // Lastly, comment out the @end.
375 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000376}
377
Chris Lattnerf04da132007-10-24 17:06:59 +0000378//===----------------------------------------------------------------------===//
379// Function Body / Expression rewriting
380//===----------------------------------------------------------------------===//
381
Chris Lattnere64b7772007-10-24 16:57:36 +0000382Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000383 // Otherwise, just rewrite all children.
384 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
385 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000386 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000387 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000388
389 // Handle specific things.
390 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
391 return RewriteAtEncode(AtEncode);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000392
393 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
394 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000395
Steve Naroff934f2762007-10-24 22:48:43 +0000396 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
397 // Before we rewrite it, put the original message expression in a comment.
398 SourceLocation startLoc = MessExpr->getLocStart();
399 SourceLocation endLoc = MessExpr->getLocEnd();
400
401 const char *startBuf = SM->getCharacterData(startLoc);
402 const char *endBuf = SM->getCharacterData(endLoc);
403
404 std::string messString;
405 messString += "// ";
406 messString.append(startBuf, endBuf-startBuf+1);
407 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000408
Steve Naroff934f2762007-10-24 22:48:43 +0000409 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
410 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
411 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000412 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000413 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000414 }
Chris Lattnere64b7772007-10-24 16:57:36 +0000415 // Return this stmt unmodified.
416 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000417}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000418
Chris Lattnere64b7772007-10-24 16:57:36 +0000419Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000420 // Create a new string expression.
421 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000422 std::string StrEncoding;
423 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
424 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
425 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000426 SourceLocation(), SourceLocation());
427 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000428 delete Exp;
429 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000430}
431
Steve Naroff934f2762007-10-24 22:48:43 +0000432CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
433 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000434 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000435 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000436
437 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000438 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000439
440 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000441 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000442 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
443
444 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000445
Steve Naroff934f2762007-10-24 22:48:43 +0000446 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
447}
448
Steve Naroffd5255f52007-11-01 13:24:47 +0000449static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
450 const char *&startRef, const char *&endRef) {
451 while (startBuf < endBuf) {
452 if (*startBuf == '<')
453 startRef = startBuf; // mark the start.
454 if (*startBuf == '>') {
455 assert((startRef && *startRef == '<') && "rewrite scanning error");
456 endRef = startBuf; // mark the end.
457 return true;
458 }
459 startBuf++;
460 }
461 return false;
462}
463
464bool RewriteTest::needToScanForQualifiers(QualType T) {
465 // FIXME: we don't currently represent "id <Protocol>" in the type system.
466 if (T == Context->getObjcIdType())
467 return true;
468
469 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000470 Type *pointeeType = pType->getPointeeType().getTypePtr();
471 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
472 return true; // we have "Class <Protocol> *".
473 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000474 return false;
475}
476
477void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
478 const FunctionTypeProto *proto, FunctionDecl *FD) {
479
480 if (needToScanForQualifiers(proto->getResultType())) {
481 // Since types are unique, we need to scan the buffer.
482 SourceLocation Loc = FD->getLocation();
483
484 const char *endBuf = SM->getCharacterData(Loc);
485 const char *startBuf = endBuf;
486 while (*startBuf != ';')
487 startBuf--; // scan backward (from the decl location) for return type.
488 const char *startRef = 0, *endRef = 0;
489 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
490 // Get the locations of the startRef, endRef.
491 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
492 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
493 // Comment out the protocol references.
494 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
495 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000496 }
497 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000498 // Now check arguments.
499 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
500 if (needToScanForQualifiers(proto->getArgType(i))) {
501 // Since types are unique, we need to scan the buffer.
502 SourceLocation Loc = FD->getLocation();
503
504 const char *startBuf = SM->getCharacterData(Loc);
505 const char *endBuf = startBuf;
506 while (*endBuf != ';')
507 endBuf++; // scan forward (from the decl location) for argument types.
508 const char *startRef = 0, *endRef = 0;
509 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
510 // Get the locations of the startRef, endRef.
511 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
512 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
513 // Comment out the protocol references.
514 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
515 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
516 }
517 }
518 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000519}
520
Steve Naroff09b266e2007-10-30 23:14:51 +0000521void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
522 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000523 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000524 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000525 return;
526 }
527 // Check for ObjC 'id' and class types that have been adorned with protocol
528 // information (id<p>, C<p>*). The protocol references need to be rewritten!
529 const FunctionType *funcType = FD->getType()->getAsFunctionType();
530 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000531 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
532 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000533}
534
535// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
536void RewriteTest::SynthMsgSendFunctionDecl() {
537 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
538 llvm::SmallVector<QualType, 16> ArgTys;
539 QualType argT = Context->getObjcIdType();
540 assert(!argT.isNull() && "Can't find 'id' type");
541 ArgTys.push_back(argT);
542 argT = Context->getObjcSelType();
543 assert(!argT.isNull() && "Can't find 'SEL' type");
544 ArgTys.push_back(argT);
545 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
546 &ArgTys[0], ArgTys.size(),
547 true /*isVariadic*/);
548 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
549 msgSendIdent, msgSendType,
550 FunctionDecl::Extern, false, 0);
551}
552
553// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
554void RewriteTest::SynthGetClassFunctionDecl() {
555 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
556 llvm::SmallVector<QualType, 16> ArgTys;
557 ArgTys.push_back(Context->getPointerType(
558 Context->CharTy.getQualifiedType(QualType::Const)));
559 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
560 &ArgTys[0], ArgTys.size(),
561 false /*isVariadic*/);
562 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
563 getClassIdent, getClassType,
564 FunctionDecl::Extern, false, 0);
565}
566
Steve Naroffbeaf2992007-11-03 11:27:19 +0000567Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
568 assert(ConstantStringClassReference && "Can't find constant string reference");
569 llvm::SmallVector<Expr*, 4> InitExprs;
570
571 // Synthesize "(Class)&_NSConstantStringClassReference"
572 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
573 ConstantStringClassReference->getType(),
574 SourceLocation());
575 QualType expType = Context->getPointerType(ClsRef->getType());
576 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
577 expType, SourceLocation());
578 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
579 SourceLocation());
580 InitExprs.push_back(cast); // set the 'isa'.
581 InitExprs.push_back(Exp->getString()); // set "char *bytes".
582 unsigned IntSize = static_cast<unsigned>(
583 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
584 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
585 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
586 Exp->getLocStart());
587 InitExprs.push_back(len); // set "int numBytes".
588
589 // struct NSConstantString
590 QualType CFConstantStrType = Context->getCFConstantStringType();
591 // (struct NSConstantString) { <exprs from above> }
592 InitListExpr *ILE = new InitListExpr(SourceLocation(),
593 &InitExprs[0], InitExprs.size(),
594 SourceLocation());
595 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
596 // struct NSConstantString *
597 expType = Context->getPointerType(StrRep->getType());
598 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
599 SourceLocation());
600 // struct NSString *
601 if (!NSStringRecord)
602 NSStringRecord = new RecordDecl(Decl::Struct, SourceLocation(),
603 &Context->Idents.get("NSString"), 0);
604 expType = Context->getPointerType(Context->getTagDeclType(NSStringRecord));
605 cast = new CastExpr(expType, Unop, SourceLocation());
606 Rewrite.ReplaceStmt(Exp, cast);
607 delete Exp;
608 return StrRep;
609}
610
Steve Naroff934f2762007-10-24 22:48:43 +0000611Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000612 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000613 if (!MsgSendFunctionDecl)
614 SynthMsgSendFunctionDecl();
615 if (!GetClassFunctionDecl)
616 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000617
618 // Synthesize a call to objc_msgSend().
619 llvm::SmallVector<Expr*, 8> MsgExprs;
620 IdentifierInfo *clsName = Exp->getClassName();
621
622 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
623 if (clsName) { // class message.
624 llvm::SmallVector<Expr*, 8> ClsExprs;
625 QualType argType = Context->getPointerType(Context->CharTy);
626 ClsExprs.push_back(new StringLiteral(clsName->getName(),
627 clsName->getLength(),
628 false, argType, SourceLocation(),
629 SourceLocation()));
630 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
631 &ClsExprs[0], ClsExprs.size());
632 MsgExprs.push_back(Cls);
633 } else // instance message.
634 MsgExprs.push_back(Exp->getReceiver());
635
Steve Naroffbeaf2992007-11-03 11:27:19 +0000636 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000637 llvm::SmallVector<Expr*, 8> SelExprs;
638 QualType argType = Context->getPointerType(Context->CharTy);
639 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
640 Exp->getSelector().getName().size(),
641 false, argType, SourceLocation(),
642 SourceLocation()));
643 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
644 &SelExprs[0], SelExprs.size());
645 MsgExprs.push_back(SelExp);
646
647 // Now push any user supplied arguments.
648 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
649 MsgExprs.push_back(Exp->getArg(i));
650 // We've transferred the ownership to MsgExprs. Null out the argument in
651 // the original expression, since we will delete it below.
652 Exp->setArg(i, 0);
653 }
Steve Naroffab972d32007-11-04 22:37:50 +0000654 // Generate the funky cast.
655 CastExpr *cast;
656 llvm::SmallVector<QualType, 8> ArgTypes;
657 QualType returnType;
658
659 // Push 'id' and 'SEL', the 2 implicit arguments.
660 ArgTypes.push_back(Context->getObjcIdType());
661 ArgTypes.push_back(Context->getObjcSelType());
662 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
663 // Push any user argument types.
664 for (int i = 0; i < mDecl->getNumParams(); i++)
665 ArgTypes.push_back(mDecl->getParamDecl(i)->getType());
666 returnType = mDecl->getResultType();
667 } else {
668 returnType = Context->getObjcIdType();
669 }
670 // Get the type, we will need to reference it in a couple spots.
671 QualType msgSendType = MsgSendFunctionDecl->getType();
672
673 // Create a reference to the objc_msgSend() declaration.
674 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
675
676 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
677 // If we don't do this cast, we get the following bizarre warning/note:
678 // xx.m:13: warning: function called through a non-compatible type
679 // xx.m:13: note: if this code is reached, the program will abort
680 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
681 SourceLocation());
682
683 // Now do the "normal" pointer to function cast.
684 QualType castType = Context->getFunctionType(returnType,
685 &ArgTypes[0], ArgTypes.size(),
686 false/*FIXME:variadic*/);
687 castType = Context->getPointerType(castType);
688 cast = new CastExpr(castType, cast, SourceLocation());
689
690 // Don't forget the parens to enforce the proper binding.
691 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
692
693 const FunctionType *FT = msgSendType->getAsFunctionType();
694 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
695 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000696 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000697 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000698
Chris Lattnere64b7772007-10-24 16:57:36 +0000699 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000700 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000701}
702
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000703/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
704/// an objective-c class with ivars.
705void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
706 std::string &Result) {
707 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
708 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000709 // Do not synthesize more than once.
710 if (ObjcSynthesizedStructs.count(CDecl))
711 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000712 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
713 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
714 // Do it for the root
715 SynthesizeObjcInternalStruct(RCDecl, Result);
716 }
717
718 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000719 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000720 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000721 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
722 return;
723
Steve Naroff04960052007-11-01 17:12:31 +0000724 Result += "\nstruct ";
725 Result += CDecl->getName();
726 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
727 Result += " {\n struct ";
728 Result += RCDecl->getName();
729 Result += " _";
730 Result += RCDecl->getName();
731 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000732 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000733 else
734 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000735
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000736 if (NumIvars > 0) {
737 SourceLocation LocStart = CDecl->getLocStart();
738 SourceLocation LocEnd = CDecl->getLocEnd();
739
740 const char *startBuf = SM->getCharacterData(LocStart);
741 const char *endBuf = SM->getCharacterData(LocEnd);
742 startBuf = strchr(startBuf, '{');
743 assert((startBuf && endBuf)
744 && "SynthesizeObjcInternalStruct - malformed @interface");
745 startBuf++; // past '{'
746 while (startBuf < endBuf) {
747 if (*startBuf == '@') {
748 startBuf = strchr(startBuf, 'p');
749 // FIXME: presence of @public, etc. inside comment results in
750 // this transformation as well, which is still correct c-code.
751 if (!strncmp(startBuf, "public", strlen("public"))) {
752 startBuf += strlen("public");
753 Result += "/* @public */";
754 }
755 else if (!strncmp(startBuf, "private", strlen("private"))) {
756 startBuf += strlen("private");
757 Result += "/* @private */";
758 }
759 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
760 startBuf += strlen("protected");
761 Result += "/* @protected */";
762 }
763 }
764 Result += *startBuf++;
765 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000766 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000767
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000768 Result += "};\n";
769 // Mark this struct as having been generated.
770 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000771 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000772}
773
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000774// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
775/// class methods.
776void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
777 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000778 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000779 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000780 const char *ClassName,
781 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000782 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000783 if (NumMethods > 0 && !objc_impl_method) {
784 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000785 SEL _cmd;
786 char *method_types;
787 void *_imp;
788 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000789 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000790 Result += "\nstruct _objc_method {\n";
791 Result += "\tSEL _cmd;\n";
792 Result += "\tchar *method_types;\n";
793 Result += "\tvoid *_imp;\n";
794 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000795
796 /* struct _objc_method_list {
797 struct _objc_method_list *next_method;
798 int method_count;
799 struct _objc_method method_list[];
800 }
801 */
802 Result += "\nstruct _objc_method_list {\n";
803 Result += "\tstruct _objc_method_list *next_method;\n";
804 Result += "\tint method_count;\n";
805 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000806 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000807 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000808 // Build _objc_method_list for class's methods if needed
809 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000810 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +0000811 Result += prefix;
812 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
813 Result += "_METHODS_";
814 Result += ClassName;
815 Result += " __attribute__ ((section (\"__OBJC, __";
816 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000817 Result += "_meth\")))= ";
818 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
819
820 Result += "\t,{{(SEL)\"";
821 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000822 std::string MethodTypeString;
823 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
824 Result += "\", \"";
825 Result += MethodTypeString;
826 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000827 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000828 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000829 Result += "\t ,{(SEL)\"";
830 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000831 std::string MethodTypeString;
832 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
833 Result += "\", \"";
834 Result += MethodTypeString;
835 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000836 }
837 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000838 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000839}
840
841/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
842void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
843 int NumProtocols,
844 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000845 const char *ClassName,
846 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000847 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000848 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000849 for (int i = 0; i < NumProtocols; i++) {
850 ObjcProtocolDecl *PDecl = Protocols[i];
851 // Output struct protocol_methods holder of method selector and type.
852 if (!objc_protocol_methods &&
853 (PDecl->getNumInstanceMethods() > 0
854 || PDecl->getNumClassMethods() > 0)) {
855 /* struct protocol_methods {
856 SEL _cmd;
857 char *method_types;
858 }
859 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000860 Result += "\nstruct protocol_methods {\n";
861 Result += "\tSEL _cmd;\n";
862 Result += "\tchar *method_types;\n";
863 Result += "};\n";
864
865 /* struct _objc_protocol_method_list {
866 int protocol_method_count;
867 struct protocol_methods protocols[];
868 }
869 */
870 Result += "\nstruct _objc_protocol_method_list {\n";
871 Result += "\tint protocol_method_count;\n";
872 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000873 objc_protocol_methods = true;
874 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000875
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000876 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000877 int NumMethods = PDecl->getNumInstanceMethods();
878 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000879 Result += "\nstatic struct _objc_protocol_method_list "
880 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
881 Result += PDecl->getName();
882 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
883 "{\n\t" + utostr(NumMethods) + "\n";
884
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000885 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000886 Result += "\t,{{(SEL)\"";
887 Result += Methods[0]->getSelector().getName().c_str();
888 Result += "\", \"\"}\n";
889
890 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000891 Result += "\t ,{(SEL)\"";
892 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000893 std::string MethodTypeString;
894 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
895 Result += "\", \"";
896 Result += MethodTypeString;
897 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000898 }
899 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000900 }
901
902 // Output class methods declared in this protocol.
903 NumMethods = PDecl->getNumClassMethods();
904 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000905 Result += "\nstatic struct _objc_protocol_method_list "
906 "_OBJC_PROTOCOL_CLASS_METHODS_";
907 Result += PDecl->getName();
908 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
909 "{\n\t";
910 Result += utostr(NumMethods);
911 Result += "\n";
912
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000913 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000914 Result += "\t,{{(SEL)\"";
915 Result += Methods[0]->getSelector().getName().c_str();
916 Result += "\", \"\"}\n";
917
918 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000919 Result += "\t ,{(SEL)\"";
920 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000921 std::string MethodTypeString;
922 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
923 Result += "\", \"";
924 Result += MethodTypeString;
925 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000926 }
927 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000928 }
929 // Output:
930 /* struct _objc_protocol {
931 // Objective-C 1.0 extensions
932 struct _objc_protocol_extension *isa;
933 char *protocol_name;
934 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000935 struct _objc_protocol_method_list *instance_methods;
936 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000937 };
938 */
939 static bool objc_protocol = false;
940 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000941 Result += "\nstruct _objc_protocol {\n";
942 Result += "\tstruct _objc_protocol_extension *isa;\n";
943 Result += "\tchar *protocol_name;\n";
944 Result += "\tstruct _objc_protocol **protocol_list;\n";
945 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
946 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
947 Result += "};\n";
948
949 /* struct _objc_protocol_list {
950 struct _objc_protocol_list *next;
951 int protocol_count;
952 struct _objc_protocol *class_protocols[];
953 }
954 */
955 Result += "\nstruct _objc_protocol_list {\n";
956 Result += "\tstruct _objc_protocol_list *next;\n";
957 Result += "\tint protocol_count;\n";
958 Result += "\tstruct _objc_protocol *class_protocols[];\n";
959 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000960 objc_protocol = true;
961 }
962
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000963 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
964 Result += PDecl->getName();
965 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
966 "{\n\t0, \"";
967 Result += PDecl->getName();
968 Result += "\", 0, ";
969 if (PDecl->getInstanceMethods() > 0) {
970 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
971 Result += PDecl->getName();
972 Result += ", ";
973 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000974 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000975 Result += "0, ";
976 if (PDecl->getClassMethods() > 0) {
977 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
978 Result += PDecl->getName();
979 Result += "\n";
980 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000981 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000982 Result += "0\n";
983 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000984 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000985 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000986 Result += "\nstatic struct _objc_protocol_list _OBJC_";
987 Result += prefix;
988 Result += "_PROTOCOLS_";
989 Result += ClassName;
990 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
991 "{\n\t0, ";
992 Result += utostr(NumProtocols);
993 Result += "\n";
994
995 Result += "\t,{&_OBJC_PROTOCOL_";
996 Result += Protocols[0]->getName();
997 Result += " \n";
998
999 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001000 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001001 Result += "\t ,&_OBJC_PROTOCOL_";
1002 Result += PDecl->getName();
1003 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001004 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001005 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001006 }
1007}
1008
1009/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1010/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001011void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1012 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001013 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1014 // Find category declaration for this implementation.
1015 ObjcCategoryDecl *CDecl;
1016 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1017 CDecl = CDecl->getNextClassCategory())
1018 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1019 break;
1020 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1021
1022 char *FullCategoryName = (char*)alloca(
1023 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1024 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1025
1026 // Build _objc_method_list for class's instance methods if needed
1027 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1028 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001029 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001030 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001031
1032 // Build _objc_method_list for class's class methods if needed
1033 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1034 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001035 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001036 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001037
1038 // Protocols referenced in class declaration?
1039 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1040 CDecl->getNumReferencedProtocols(),
1041 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001042 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001043
1044 /* struct _objc_category {
1045 char *category_name;
1046 char *class_name;
1047 struct _objc_method_list *instance_methods;
1048 struct _objc_method_list *class_methods;
1049 struct _objc_protocol_list *protocols;
1050 // Objective-C 1.0 extensions
1051 uint32_t size; // sizeof (struct _objc_category)
1052 struct _objc_property_list *instance_properties; // category's own
1053 // @property decl.
1054 };
1055 */
1056
1057 static bool objc_category = false;
1058 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001059 Result += "\nstruct _objc_category {\n";
1060 Result += "\tchar *category_name;\n";
1061 Result += "\tchar *class_name;\n";
1062 Result += "\tstruct _objc_method_list *instance_methods;\n";
1063 Result += "\tstruct _objc_method_list *class_methods;\n";
1064 Result += "\tstruct _objc_protocol_list *protocols;\n";
1065 Result += "\tunsigned int size;\n";
1066 Result += "\tstruct _objc_property_list *instance_properties;\n";
1067 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001068 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001069 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001070 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1071 Result += FullCategoryName;
1072 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1073 Result += IDecl->getName();
1074 Result += "\"\n\t, \"";
1075 Result += ClassDecl->getName();
1076 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001077
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001078 if (IDecl->getNumInstanceMethods() > 0) {
1079 Result += "\t, (struct _objc_method_list *)"
1080 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1081 Result += FullCategoryName;
1082 Result += "\n";
1083 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001084 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001085 Result += "\t, 0\n";
1086 if (IDecl->getNumClassMethods() > 0) {
1087 Result += "\t, (struct _objc_method_list *)"
1088 "&_OBJC_CATEGORY_CLASS_METHODS_";
1089 Result += FullCategoryName;
1090 Result += "\n";
1091 }
1092 else
1093 Result += "\t, 0\n";
1094
1095 if (CDecl->getNumReferencedProtocols() > 0) {
1096 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1097 Result += FullCategoryName;
1098 Result += "\n";
1099 }
1100 else
1101 Result += "\t, 0\n";
1102 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001103}
1104
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001105/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1106/// ivar offset.
1107void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1108 ObjcIvarDecl *ivar,
1109 std::string &Result) {
1110 Result += "offsetof(struct _interface_";
1111 Result += IDecl->getName();
1112 Result += ", ";
1113 Result += ivar->getName();
1114 Result += ")";
1115}
1116
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001117//===----------------------------------------------------------------------===//
1118// Meta Data Emission
1119//===----------------------------------------------------------------------===//
1120
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001121void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1122 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001123 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1124
1125 // Build _objc_ivar_list metadata for classes ivars if needed
1126 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1127 ? IDecl->getImplDeclNumIvars()
1128 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1129
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001130 SynthesizeObjcInternalStruct(CDecl, Result);
1131
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001132 if (NumIvars > 0) {
1133 static bool objc_ivar = false;
1134 if (!objc_ivar) {
1135 /* struct _objc_ivar {
1136 char *ivar_name;
1137 char *ivar_type;
1138 int ivar_offset;
1139 };
1140 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001141 Result += "\nstruct _objc_ivar {\n";
1142 Result += "\tchar *ivar_name;\n";
1143 Result += "\tchar *ivar_type;\n";
1144 Result += "\tint ivar_offset;\n";
1145 Result += "};\n";
1146
1147 /* struct _objc_ivar_list {
1148 int ivar_count;
1149 struct _objc_ivar ivar_list[];
1150 };
1151 */
1152 Result += "\nstruct _objc_ivar_list {\n";
1153 Result += "\tint ivar_count;\n";
1154 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001155 objc_ivar = true;
1156 }
1157
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001158 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1159 Result += IDecl->getName();
1160 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1161 "{\n\t";
1162 Result += utostr(NumIvars);
1163 Result += "\n";
1164
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001165 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1166 ? IDecl->getImplDeclIVars()
1167 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001168 Result += "\t,{{\"";
1169 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001170 Result += "\", \"";
1171 std::string StrEncoding;
1172 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1173 Result += StrEncoding;
1174 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001175 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1176 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001177 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001178 Result += "\t ,{\"";
1179 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001180 Result += "\", \"";
1181 std::string StrEncoding;
1182 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1183 Result += StrEncoding;
1184 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001185 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1186 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001187 }
1188
1189 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001190 }
1191
1192 // Build _objc_method_list for class's instance methods if needed
1193 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1194 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001195 true,
1196 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001197
1198 // Build _objc_method_list for class's class methods if needed
1199 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001200 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001201 false,
1202 "", IDecl->getName(), Result);
1203
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001204 // Protocols referenced in class declaration?
1205 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1206 CDecl->getNumIntfRefProtocols(),
1207 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001208 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001209
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001210
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001211 // Declaration of class/meta-class metadata
1212 /* struct _objc_class {
1213 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001214 const char *super_class_name;
1215 char *name;
1216 long version;
1217 long info;
1218 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001219 struct _objc_ivar_list *ivars;
1220 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001221 struct objc_cache *cache;
1222 struct objc_protocol_list *protocols;
1223 const char *ivar_layout;
1224 struct _objc_class_ext *ext;
1225 };
1226 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001227 static bool objc_class = false;
1228 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001229 Result += "\nstruct _objc_class {\n";
1230 Result += "\tstruct _objc_class *isa;\n";
1231 Result += "\tconst char *super_class_name;\n";
1232 Result += "\tchar *name;\n";
1233 Result += "\tlong version;\n";
1234 Result += "\tlong info;\n";
1235 Result += "\tlong instance_size;\n";
1236 Result += "\tstruct _objc_ivar_list *ivars;\n";
1237 Result += "\tstruct _objc_method_list *methods;\n";
1238 Result += "\tstruct objc_cache *cache;\n";
1239 Result += "\tstruct _objc_protocol_list *protocols;\n";
1240 Result += "\tconst char *ivar_layout;\n";
1241 Result += "\tstruct _objc_class_ext *ext;\n";
1242 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001243 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001244 }
1245
1246 // Meta-class metadata generation.
1247 ObjcInterfaceDecl *RootClass = 0;
1248 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1249 while (SuperClass) {
1250 RootClass = SuperClass;
1251 SuperClass = SuperClass->getSuperClass();
1252 }
1253 SuperClass = CDecl->getSuperClass();
1254
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001255 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1256 Result += CDecl->getName();
1257 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1258 "{\n\t(struct _objc_class *)\"";
1259 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1260 Result += "\"";
1261
1262 if (SuperClass) {
1263 Result += ", \"";
1264 Result += SuperClass->getName();
1265 Result += "\", \"";
1266 Result += CDecl->getName();
1267 Result += "\"";
1268 }
1269 else {
1270 Result += ", 0, \"";
1271 Result += CDecl->getName();
1272 Result += "\"";
1273 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001274 // TODO: 'ivars' field for root class is currently set to 0.
1275 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001276 Result += ", 0,2, sizeof(struct _objc_class), 0";
1277 if (CDecl->getNumClassMethods() > 0) {
1278 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1279 Result += CDecl->getName();
1280 Result += "\n";
1281 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001282 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001283 Result += ", 0\n";
1284 if (CDecl->getNumIntfRefProtocols() > 0) {
1285 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1286 Result += CDecl->getName();
1287 Result += ",0,0\n";
1288 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001289 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001290 Result += "\t,0,0,0,0\n";
1291 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001292
1293 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001294 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1295 Result += CDecl->getName();
1296 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1297 "{\n\t&_OBJC_METACLASS_";
1298 Result += CDecl->getName();
1299 if (SuperClass) {
1300 Result += ", \"";
1301 Result += SuperClass->getName();
1302 Result += "\", \"";
1303 Result += CDecl->getName();
1304 Result += "\"";
1305 }
1306 else {
1307 Result += ", 0, \"";
1308 Result += CDecl->getName();
1309 Result += "\"";
1310 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001311 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001312 Result += ", 0,1";
1313 if (!ObjcSynthesizedStructs.count(CDecl))
1314 Result += ",0";
1315 else {
1316 // class has size. Must synthesize its size.
1317 Result += ",sizeof(struct _interface_";
1318 Result += CDecl->getName();
1319 Result += ")";
1320 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001321 if (NumIvars > 0) {
1322 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1323 Result += CDecl->getName();
1324 Result += "\n\t";
1325 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001326 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001327 Result += ",0";
1328 if (IDecl->getNumInstanceMethods() > 0) {
1329 Result += ", &_OBJC_INSTANCE_METHODS_";
1330 Result += CDecl->getName();
1331 Result += ", 0\n\t";
1332 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001333 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001334 Result += ",0,0";
1335 if (CDecl->getNumIntfRefProtocols() > 0) {
1336 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1337 Result += CDecl->getName();
1338 Result += ", 0,0\n";
1339 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001340 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001341 Result += ",0,0,0\n";
1342 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001343}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001344
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001345void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001346 int ClsDefCount = ClassImplementation.size();
1347 int CatDefCount = CategoryImplementation.size();
1348 if (ClsDefCount == 0 && CatDefCount == 0)
1349 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001350
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001351 // TODO: This is temporary until we decide how to access objc types in a
1352 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001353 Result += "#include <Objc/objc.h>\n";
1354 // This is needed for use of offsetof
1355 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001356
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001357 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001358 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001359 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001360
1361 // For each implemented category, write out all its meta data.
1362 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001363 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001364
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001365 // Write objc_symtab metadata
1366 /*
1367 struct _objc_symtab
1368 {
1369 long sel_ref_cnt;
1370 SEL *refs;
1371 short cls_def_cnt;
1372 short cat_def_cnt;
1373 void *defs[cls_def_cnt + cat_def_cnt];
1374 };
1375 */
1376
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001377 Result += "\nstruct _objc_symtab {\n";
1378 Result += "\tlong sel_ref_cnt;\n";
1379 Result += "\tSEL *refs;\n";
1380 Result += "\tshort cls_def_cnt;\n";
1381 Result += "\tshort cat_def_cnt;\n";
1382 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1383 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001384
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001385 Result += "static struct _objc_symtab "
1386 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1387 Result += "\t0, 0, " + utostr(ClsDefCount)
1388 + ", " + utostr(CatDefCount) + "\n";
1389 for (int i = 0; i < ClsDefCount; i++) {
1390 Result += "\t,&_OBJC_CLASS_";
1391 Result += ClassImplementation[i]->getName();
1392 Result += "\n";
1393 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001394
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001395 for (int i = 0; i < CatDefCount; i++) {
1396 Result += "\t,&_OBJC_CATEGORY_";
1397 Result += CategoryImplementation[i]->getClassInterface()->getName();
1398 Result += "_";
1399 Result += CategoryImplementation[i]->getName();
1400 Result += "\n";
1401 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001402
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001403 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001404
1405 // Write objc_module metadata
1406
1407 /*
1408 struct _objc_module {
1409 long version;
1410 long size;
1411 const char *name;
1412 struct _objc_symtab *symtab;
1413 }
1414 */
1415
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001416 Result += "\nstruct _objc_module {\n";
1417 Result += "\tlong version;\n";
1418 Result += "\tlong size;\n";
1419 Result += "\tconst char *name;\n";
1420 Result += "\tstruct _objc_symtab *symtab;\n";
1421 Result += "};\n\n";
1422 Result += "static struct _objc_module "
1423 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001424 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1425 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001426 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001427}
Chris Lattner311ff022007-10-16 22:36:42 +00001428