blob: 58de9f60c15911147eb8cee04930f1f2815988bb [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.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000096 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
97 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000098
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000099 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
100 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000101
102 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
103 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000104 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000105 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000106 const char *ClassName,
107 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000108
109 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
110 int NumProtocols,
111 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000112 const char *ClassName,
113 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000114 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
115 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000116 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
117 ObjcIvarDecl *ivar,
118 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000119 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000120 };
121}
122
Chris Lattner8a12c272007-10-11 18:38:32 +0000123ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000124
Chris Lattnerf04da132007-10-24 17:06:59 +0000125//===----------------------------------------------------------------------===//
126// Top Level Driver Code
127//===----------------------------------------------------------------------===//
128
Chris Lattner8a12c272007-10-11 18:38:32 +0000129void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-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 Naroffebf2b562007-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 Naroff09b266e2007-10-30 23:14:51 +0000141 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-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 Naroffbef11852007-10-26 20:53:56 +0000148 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
149 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000150 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
151 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000152 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
153 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000154 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000156 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
157 return HandleDeclInMainFile(D);
158
Chris Lattnerf04da132007-10-24 17:06:59 +0000159 // Otherwise, see if there is a #import in the main file that should be
160 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000161 RewriteInclude(Loc);
162}
163
Chris Lattnerf04da132007-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 Naroffbeaf2992007-11-03 11:27:19 +0000188 //printf("Changed:\n");
Chris Lattnerf04da132007-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 Jahanian26e4cd32007-10-26 19:46:17 +0000194
195}
196
Chris Lattnerf04da132007-10-24 17:06:59 +0000197//===----------------------------------------------------------------------===//
198// Syntactic (non-AST) Rewriting Code
199//===----------------------------------------------------------------------===//
200
Chris Lattner2c64b7b2007-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 Lattnerf04da132007-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 Jahanian545b9ae2007-10-18 19:23:00 +0000229
Chris Lattnerf04da132007-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 Lattner8a12c272007-10-11 18:38:32 +0000253}
254
255
Chris Lattnerf04da132007-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 Naroff934f2762007-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 Naroff8749be52007-10-31 22:11:35 +0000274 if (ObjcForwardDecls.count(ForwardDecl))
275 continue;
Steve Naroff352336b2007-11-05 14:36:37 +0000276 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000277 typedefString += ForwardDecl->getName();
278 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000279
280 // Mark this typedef as having been generated.
281 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000282 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000283 }
284
285 // Replace the @class with typedefs corresponding to the classes.
286 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
287 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000288}
289
Steve Naroff423cb562007-10-30 13:30:57 +0000290void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
291 for (int i = 0; i < nMethods; i++) {
292 ObjcMethodDecl *Method = Methods[i];
293 SourceLocation Loc = Method->getLocStart();
294
295 Rewrite.ReplaceText(Loc, 0, "// ", 3);
296
297 // FIXME: handle methods that are declared across multiple lines.
298 }
299}
300
301void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
302 SourceLocation LocStart = CatDecl->getLocStart();
303
304 // FIXME: handle category headers that are declared across multiple lines.
305 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
306
307 RewriteMethods(CatDecl->getNumInstanceMethods(),
308 CatDecl->getInstanceMethods());
309 RewriteMethods(CatDecl->getNumClassMethods(),
310 CatDecl->getClassMethods());
311 // Lastly, comment out the @end.
312 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
313}
314
Steve Naroff752d6ef2007-10-30 16:42:30 +0000315void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
316 SourceLocation LocStart = PDecl->getLocStart();
317
318 // FIXME: handle protocol headers that are declared across multiple lines.
319 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
320
321 RewriteMethods(PDecl->getNumInstanceMethods(),
322 PDecl->getInstanceMethods());
323 RewriteMethods(PDecl->getNumClassMethods(),
324 PDecl->getClassMethods());
325 // Lastly, comment out the @end.
326 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
327}
328
Steve Naroffbef11852007-10-26 20:53:56 +0000329void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000330
331 SourceLocation LocStart = ClassDecl->getLocStart();
332 SourceLocation LocEnd = ClassDecl->getLocEnd();
333
334 const char *startBuf = SM->getCharacterData(LocStart);
335 const char *endBuf = SM->getCharacterData(LocEnd);
336
Steve Naroff2feac5e2007-10-30 03:43:13 +0000337 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000338
339 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000340 if (!ObjcForwardDecls.count(ClassDecl)) {
341 // we haven't seen a forward decl - generate a typedef.
Steve Naroff352336b2007-11-05 14:36:37 +0000342 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000343 ResultStr += ClassDecl->getName();
344 ResultStr += ";";
345
346 // Mark this typedef as having been generated.
347 ObjcForwardDecls.insert(ClassDecl);
348 }
Steve Narofff908a872007-10-30 02:23:23 +0000349 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
350
Steve Naroff2feac5e2007-10-30 03:43:13 +0000351 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000352 ResultStr.c_str(), ResultStr.size());
353
Steve Naroff423cb562007-10-30 13:30:57 +0000354 RewriteMethods(ClassDecl->getNumInstanceMethods(),
355 ClassDecl->getInstanceMethods());
356 RewriteMethods(ClassDecl->getNumClassMethods(),
357 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000358
Steve Naroff2feac5e2007-10-30 03:43:13 +0000359 // Lastly, comment out the @end.
360 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000361}
362
Chris Lattnerf04da132007-10-24 17:06:59 +0000363//===----------------------------------------------------------------------===//
364// Function Body / Expression rewriting
365//===----------------------------------------------------------------------===//
366
Chris Lattnere64b7772007-10-24 16:57:36 +0000367Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000368 // Otherwise, just rewrite all children.
369 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
370 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000371 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000372 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000373
374 // Handle specific things.
375 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
376 return RewriteAtEncode(AtEncode);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000377
378 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
379 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000380
Steve Naroff934f2762007-10-24 22:48:43 +0000381 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
382 // Before we rewrite it, put the original message expression in a comment.
383 SourceLocation startLoc = MessExpr->getLocStart();
384 SourceLocation endLoc = MessExpr->getLocEnd();
385
386 const char *startBuf = SM->getCharacterData(startLoc);
387 const char *endBuf = SM->getCharacterData(endLoc);
388
389 std::string messString;
390 messString += "// ";
391 messString.append(startBuf, endBuf-startBuf+1);
392 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000393
Steve Naroff934f2762007-10-24 22:48:43 +0000394 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
395 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
396 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000397 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000398 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000399 }
Chris Lattnere64b7772007-10-24 16:57:36 +0000400 // Return this stmt unmodified.
401 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000402}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000403
Chris Lattnere64b7772007-10-24 16:57:36 +0000404Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000405 // Create a new string expression.
406 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000407 std::string StrEncoding;
408 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
409 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
410 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000411 SourceLocation(), SourceLocation());
412 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000413 delete Exp;
414 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000415}
416
Steve Naroff934f2762007-10-24 22:48:43 +0000417CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
418 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000419 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000420 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000421
422 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000423 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000424
425 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000426 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000427 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
428
429 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000430
Steve Naroff934f2762007-10-24 22:48:43 +0000431 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
432}
433
Steve Naroffd5255f52007-11-01 13:24:47 +0000434static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
435 const char *&startRef, const char *&endRef) {
436 while (startBuf < endBuf) {
437 if (*startBuf == '<')
438 startRef = startBuf; // mark the start.
439 if (*startBuf == '>') {
440 assert((startRef && *startRef == '<') && "rewrite scanning error");
441 endRef = startBuf; // mark the end.
442 return true;
443 }
444 startBuf++;
445 }
446 return false;
447}
448
449bool RewriteTest::needToScanForQualifiers(QualType T) {
450 // FIXME: we don't currently represent "id <Protocol>" in the type system.
451 if (T == Context->getObjcIdType())
452 return true;
453
454 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000455 Type *pointeeType = pType->getPointeeType().getTypePtr();
456 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
457 return true; // we have "Class <Protocol> *".
458 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000459 return false;
460}
461
462void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
463 const FunctionTypeProto *proto, FunctionDecl *FD) {
464
465 if (needToScanForQualifiers(proto->getResultType())) {
466 // Since types are unique, we need to scan the buffer.
467 SourceLocation Loc = FD->getLocation();
468
469 const char *endBuf = SM->getCharacterData(Loc);
470 const char *startBuf = endBuf;
471 while (*startBuf != ';')
472 startBuf--; // scan backward (from the decl location) for return type.
473 const char *startRef = 0, *endRef = 0;
474 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
475 // Get the locations of the startRef, endRef.
476 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
477 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
478 // Comment out the protocol references.
479 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
480 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000481 }
482 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000483 // Now check arguments.
484 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
485 if (needToScanForQualifiers(proto->getArgType(i))) {
486 // Since types are unique, we need to scan the buffer.
487 SourceLocation Loc = FD->getLocation();
488
489 const char *startBuf = SM->getCharacterData(Loc);
490 const char *endBuf = startBuf;
491 while (*endBuf != ';')
492 endBuf++; // scan forward (from the decl location) for argument types.
493 const char *startRef = 0, *endRef = 0;
494 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
495 // Get the locations of the startRef, endRef.
496 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
497 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
498 // Comment out the protocol references.
499 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
500 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
501 }
502 }
503 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000504}
505
Steve Naroff09b266e2007-10-30 23:14:51 +0000506void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
507 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000508 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000509 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000510 return;
511 }
512 // Check for ObjC 'id' and class types that have been adorned with protocol
513 // information (id<p>, C<p>*). The protocol references need to be rewritten!
514 const FunctionType *funcType = FD->getType()->getAsFunctionType();
515 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000516 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
517 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000518}
519
520// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
521void RewriteTest::SynthMsgSendFunctionDecl() {
522 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
523 llvm::SmallVector<QualType, 16> ArgTys;
524 QualType argT = Context->getObjcIdType();
525 assert(!argT.isNull() && "Can't find 'id' type");
526 ArgTys.push_back(argT);
527 argT = Context->getObjcSelType();
528 assert(!argT.isNull() && "Can't find 'SEL' type");
529 ArgTys.push_back(argT);
530 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
531 &ArgTys[0], ArgTys.size(),
532 true /*isVariadic*/);
533 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
534 msgSendIdent, msgSendType,
535 FunctionDecl::Extern, false, 0);
536}
537
538// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
539void RewriteTest::SynthGetClassFunctionDecl() {
540 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
541 llvm::SmallVector<QualType, 16> ArgTys;
542 ArgTys.push_back(Context->getPointerType(
543 Context->CharTy.getQualifiedType(QualType::Const)));
544 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
545 &ArgTys[0], ArgTys.size(),
546 false /*isVariadic*/);
547 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
548 getClassIdent, getClassType,
549 FunctionDecl::Extern, false, 0);
550}
551
Steve Naroffbeaf2992007-11-03 11:27:19 +0000552Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
553 assert(ConstantStringClassReference && "Can't find constant string reference");
554 llvm::SmallVector<Expr*, 4> InitExprs;
555
556 // Synthesize "(Class)&_NSConstantStringClassReference"
557 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
558 ConstantStringClassReference->getType(),
559 SourceLocation());
560 QualType expType = Context->getPointerType(ClsRef->getType());
561 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
562 expType, SourceLocation());
563 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
564 SourceLocation());
565 InitExprs.push_back(cast); // set the 'isa'.
566 InitExprs.push_back(Exp->getString()); // set "char *bytes".
567 unsigned IntSize = static_cast<unsigned>(
568 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
569 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
570 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
571 Exp->getLocStart());
572 InitExprs.push_back(len); // set "int numBytes".
573
574 // struct NSConstantString
575 QualType CFConstantStrType = Context->getCFConstantStringType();
576 // (struct NSConstantString) { <exprs from above> }
577 InitListExpr *ILE = new InitListExpr(SourceLocation(),
578 &InitExprs[0], InitExprs.size(),
579 SourceLocation());
580 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
581 // struct NSConstantString *
582 expType = Context->getPointerType(StrRep->getType());
583 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
584 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000585 // cast to NSConstantString *
586 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000587 Rewrite.ReplaceStmt(Exp, cast);
588 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000589 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +0000590}
591
Steve Naroff934f2762007-10-24 22:48:43 +0000592Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000593 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000594 if (!MsgSendFunctionDecl)
595 SynthMsgSendFunctionDecl();
596 if (!GetClassFunctionDecl)
597 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000598
599 // Synthesize a call to objc_msgSend().
600 llvm::SmallVector<Expr*, 8> MsgExprs;
601 IdentifierInfo *clsName = Exp->getClassName();
602
603 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
604 if (clsName) { // class message.
605 llvm::SmallVector<Expr*, 8> ClsExprs;
606 QualType argType = Context->getPointerType(Context->CharTy);
607 ClsExprs.push_back(new StringLiteral(clsName->getName(),
608 clsName->getLength(),
609 false, argType, SourceLocation(),
610 SourceLocation()));
611 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
612 &ClsExprs[0], ClsExprs.size());
613 MsgExprs.push_back(Cls);
614 } else // instance message.
615 MsgExprs.push_back(Exp->getReceiver());
616
Steve Naroffbeaf2992007-11-03 11:27:19 +0000617 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000618 llvm::SmallVector<Expr*, 8> SelExprs;
619 QualType argType = Context->getPointerType(Context->CharTy);
620 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
621 Exp->getSelector().getName().size(),
622 false, argType, SourceLocation(),
623 SourceLocation()));
624 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
625 &SelExprs[0], SelExprs.size());
626 MsgExprs.push_back(SelExp);
627
628 // Now push any user supplied arguments.
629 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
630 MsgExprs.push_back(Exp->getArg(i));
631 // We've transferred the ownership to MsgExprs. Null out the argument in
632 // the original expression, since we will delete it below.
633 Exp->setArg(i, 0);
634 }
Steve Naroffab972d32007-11-04 22:37:50 +0000635 // Generate the funky cast.
636 CastExpr *cast;
637 llvm::SmallVector<QualType, 8> ArgTypes;
638 QualType returnType;
639
640 // Push 'id' and 'SEL', the 2 implicit arguments.
641 ArgTypes.push_back(Context->getObjcIdType());
642 ArgTypes.push_back(Context->getObjcSelType());
643 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
644 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +0000645 for (int i = 0; i < mDecl->getNumParams(); i++) {
646 QualType t = mDecl->getParamDecl(i)->getType();
647 if (t == Context->getObjcClassType())
648 t = Context->getObjcIdType(); // Convert "Class"->"id"
649 ArgTypes.push_back(t);
650 }
Steve Naroffab972d32007-11-04 22:37:50 +0000651 returnType = mDecl->getResultType();
652 } else {
653 returnType = Context->getObjcIdType();
654 }
655 // Get the type, we will need to reference it in a couple spots.
656 QualType msgSendType = MsgSendFunctionDecl->getType();
657
658 // Create a reference to the objc_msgSend() declaration.
659 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
660
661 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
662 // If we don't do this cast, we get the following bizarre warning/note:
663 // xx.m:13: warning: function called through a non-compatible type
664 // xx.m:13: note: if this code is reached, the program will abort
665 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
666 SourceLocation());
667
668 // Now do the "normal" pointer to function cast.
669 QualType castType = Context->getFunctionType(returnType,
670 &ArgTypes[0], ArgTypes.size(),
671 false/*FIXME:variadic*/);
672 castType = Context->getPointerType(castType);
673 cast = new CastExpr(castType, cast, SourceLocation());
674
675 // Don't forget the parens to enforce the proper binding.
676 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
677
678 const FunctionType *FT = msgSendType->getAsFunctionType();
679 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
680 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000681 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000682 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000683
Chris Lattnere64b7772007-10-24 16:57:36 +0000684 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000685 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000686}
687
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000688/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
689/// an objective-c class with ivars.
690void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
691 std::string &Result) {
692 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
693 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000694 // Do not synthesize more than once.
695 if (ObjcSynthesizedStructs.count(CDecl))
696 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000697 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
698 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
699 // Do it for the root
700 SynthesizeObjcInternalStruct(RCDecl, Result);
701 }
702
703 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000704 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000705 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000706 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
707 return;
708
Steve Naroff04960052007-11-01 17:12:31 +0000709 Result += "\nstruct ";
710 Result += CDecl->getName();
711 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
712 Result += " {\n struct ";
713 Result += RCDecl->getName();
714 Result += " _";
715 Result += RCDecl->getName();
716 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000717 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000718 else
719 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000720
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000721 if (NumIvars > 0) {
722 SourceLocation LocStart = CDecl->getLocStart();
723 SourceLocation LocEnd = CDecl->getLocEnd();
724
725 const char *startBuf = SM->getCharacterData(LocStart);
726 const char *endBuf = SM->getCharacterData(LocEnd);
727 startBuf = strchr(startBuf, '{');
728 assert((startBuf && endBuf)
729 && "SynthesizeObjcInternalStruct - malformed @interface");
730 startBuf++; // past '{'
731 while (startBuf < endBuf) {
732 if (*startBuf == '@') {
733 startBuf = strchr(startBuf, 'p');
734 // FIXME: presence of @public, etc. inside comment results in
735 // this transformation as well, which is still correct c-code.
736 if (!strncmp(startBuf, "public", strlen("public"))) {
737 startBuf += strlen("public");
738 Result += "/* @public */";
739 }
740 else if (!strncmp(startBuf, "private", strlen("private"))) {
741 startBuf += strlen("private");
742 Result += "/* @private */";
743 }
744 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
745 startBuf += strlen("protected");
746 Result += "/* @protected */";
747 }
748 }
749 Result += *startBuf++;
750 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000751 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000752
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000753 Result += "};\n";
754 // Mark this struct as having been generated.
755 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000756 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000757}
758
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000759// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
760/// class methods.
761void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
762 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000763 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000764 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000765 const char *ClassName,
766 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000767 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000768 if (NumMethods > 0 && !objc_impl_method) {
769 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000770 SEL _cmd;
771 char *method_types;
772 void *_imp;
773 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000774 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000775 Result += "\nstruct _objc_method {\n";
776 Result += "\tSEL _cmd;\n";
777 Result += "\tchar *method_types;\n";
778 Result += "\tvoid *_imp;\n";
779 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000780
781 /* struct _objc_method_list {
782 struct _objc_method_list *next_method;
783 int method_count;
784 struct _objc_method method_list[];
785 }
786 */
787 Result += "\nstruct _objc_method_list {\n";
788 Result += "\tstruct _objc_method_list *next_method;\n";
789 Result += "\tint method_count;\n";
790 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000791 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000792 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000793 // Build _objc_method_list for class's methods if needed
794 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000795 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +0000796 Result += prefix;
797 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
798 Result += "_METHODS_";
799 Result += ClassName;
800 Result += " __attribute__ ((section (\"__OBJC, __";
801 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000802 Result += "_meth\")))= ";
803 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
804
805 Result += "\t,{{(SEL)\"";
806 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000807 std::string MethodTypeString;
808 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
809 Result += "\", \"";
810 Result += MethodTypeString;
811 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000812 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000813 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000814 Result += "\t ,{(SEL)\"";
815 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000816 std::string MethodTypeString;
817 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
818 Result += "\", \"";
819 Result += MethodTypeString;
820 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000821 }
822 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000823 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000824}
825
826/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
827void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
828 int NumProtocols,
829 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000830 const char *ClassName,
831 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000832 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000833 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000834 for (int i = 0; i < NumProtocols; i++) {
835 ObjcProtocolDecl *PDecl = Protocols[i];
836 // Output struct protocol_methods holder of method selector and type.
837 if (!objc_protocol_methods &&
838 (PDecl->getNumInstanceMethods() > 0
839 || PDecl->getNumClassMethods() > 0)) {
840 /* struct protocol_methods {
841 SEL _cmd;
842 char *method_types;
843 }
844 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000845 Result += "\nstruct protocol_methods {\n";
846 Result += "\tSEL _cmd;\n";
847 Result += "\tchar *method_types;\n";
848 Result += "};\n";
849
850 /* struct _objc_protocol_method_list {
851 int protocol_method_count;
852 struct protocol_methods protocols[];
853 }
854 */
855 Result += "\nstruct _objc_protocol_method_list {\n";
856 Result += "\tint protocol_method_count;\n";
857 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000858 objc_protocol_methods = true;
859 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000860
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000861 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000862 int NumMethods = PDecl->getNumInstanceMethods();
863 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000864 Result += "\nstatic struct _objc_protocol_method_list "
865 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
866 Result += PDecl->getName();
867 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
868 "{\n\t" + utostr(NumMethods) + "\n";
869
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000870 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000871 Result += "\t,{{(SEL)\"";
872 Result += Methods[0]->getSelector().getName().c_str();
873 Result += "\", \"\"}\n";
874
875 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000876 Result += "\t ,{(SEL)\"";
877 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000878 std::string MethodTypeString;
879 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
880 Result += "\", \"";
881 Result += MethodTypeString;
882 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000883 }
884 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000885 }
886
887 // Output class methods declared in this protocol.
888 NumMethods = PDecl->getNumClassMethods();
889 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000890 Result += "\nstatic struct _objc_protocol_method_list "
891 "_OBJC_PROTOCOL_CLASS_METHODS_";
892 Result += PDecl->getName();
893 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
894 "{\n\t";
895 Result += utostr(NumMethods);
896 Result += "\n";
897
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000898 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000899 Result += "\t,{{(SEL)\"";
900 Result += Methods[0]->getSelector().getName().c_str();
901 Result += "\", \"\"}\n";
902
903 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000904 Result += "\t ,{(SEL)\"";
905 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000906 std::string MethodTypeString;
907 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
908 Result += "\", \"";
909 Result += MethodTypeString;
910 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000911 }
912 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000913 }
914 // Output:
915 /* struct _objc_protocol {
916 // Objective-C 1.0 extensions
917 struct _objc_protocol_extension *isa;
918 char *protocol_name;
919 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000920 struct _objc_protocol_method_list *instance_methods;
921 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000922 };
923 */
924 static bool objc_protocol = false;
925 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000926 Result += "\nstruct _objc_protocol {\n";
927 Result += "\tstruct _objc_protocol_extension *isa;\n";
928 Result += "\tchar *protocol_name;\n";
929 Result += "\tstruct _objc_protocol **protocol_list;\n";
930 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
931 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
932 Result += "};\n";
933
934 /* struct _objc_protocol_list {
935 struct _objc_protocol_list *next;
936 int protocol_count;
937 struct _objc_protocol *class_protocols[];
938 }
939 */
940 Result += "\nstruct _objc_protocol_list {\n";
941 Result += "\tstruct _objc_protocol_list *next;\n";
942 Result += "\tint protocol_count;\n";
943 Result += "\tstruct _objc_protocol *class_protocols[];\n";
944 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000945 objc_protocol = true;
946 }
947
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000948 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
949 Result += PDecl->getName();
950 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
951 "{\n\t0, \"";
952 Result += PDecl->getName();
953 Result += "\", 0, ";
954 if (PDecl->getInstanceMethods() > 0) {
955 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
956 Result += PDecl->getName();
957 Result += ", ";
958 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000959 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000960 Result += "0, ";
961 if (PDecl->getClassMethods() > 0) {
962 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
963 Result += PDecl->getName();
964 Result += "\n";
965 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000966 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000967 Result += "0\n";
968 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000969 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000970 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000971 Result += "\nstatic struct _objc_protocol_list _OBJC_";
972 Result += prefix;
973 Result += "_PROTOCOLS_";
974 Result += ClassName;
975 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
976 "{\n\t0, ";
977 Result += utostr(NumProtocols);
978 Result += "\n";
979
980 Result += "\t,{&_OBJC_PROTOCOL_";
981 Result += Protocols[0]->getName();
982 Result += " \n";
983
984 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000985 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000986 Result += "\t ,&_OBJC_PROTOCOL_";
987 Result += PDecl->getName();
988 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000989 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000990 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000991 }
992}
993
994/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
995/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000996void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
997 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000998 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
999 // Find category declaration for this implementation.
1000 ObjcCategoryDecl *CDecl;
1001 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1002 CDecl = CDecl->getNextClassCategory())
1003 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1004 break;
1005 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1006
1007 char *FullCategoryName = (char*)alloca(
1008 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1009 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1010
1011 // Build _objc_method_list for class's instance methods if needed
1012 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1013 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001014 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001015 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001016
1017 // Build _objc_method_list for class's class methods if needed
1018 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1019 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001020 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001021 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001022
1023 // Protocols referenced in class declaration?
1024 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1025 CDecl->getNumReferencedProtocols(),
1026 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001027 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001028
1029 /* struct _objc_category {
1030 char *category_name;
1031 char *class_name;
1032 struct _objc_method_list *instance_methods;
1033 struct _objc_method_list *class_methods;
1034 struct _objc_protocol_list *protocols;
1035 // Objective-C 1.0 extensions
1036 uint32_t size; // sizeof (struct _objc_category)
1037 struct _objc_property_list *instance_properties; // category's own
1038 // @property decl.
1039 };
1040 */
1041
1042 static bool objc_category = false;
1043 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001044 Result += "\nstruct _objc_category {\n";
1045 Result += "\tchar *category_name;\n";
1046 Result += "\tchar *class_name;\n";
1047 Result += "\tstruct _objc_method_list *instance_methods;\n";
1048 Result += "\tstruct _objc_method_list *class_methods;\n";
1049 Result += "\tstruct _objc_protocol_list *protocols;\n";
1050 Result += "\tunsigned int size;\n";
1051 Result += "\tstruct _objc_property_list *instance_properties;\n";
1052 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001053 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001054 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001055 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1056 Result += FullCategoryName;
1057 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1058 Result += IDecl->getName();
1059 Result += "\"\n\t, \"";
1060 Result += ClassDecl->getName();
1061 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001062
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001063 if (IDecl->getNumInstanceMethods() > 0) {
1064 Result += "\t, (struct _objc_method_list *)"
1065 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1066 Result += FullCategoryName;
1067 Result += "\n";
1068 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001069 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001070 Result += "\t, 0\n";
1071 if (IDecl->getNumClassMethods() > 0) {
1072 Result += "\t, (struct _objc_method_list *)"
1073 "&_OBJC_CATEGORY_CLASS_METHODS_";
1074 Result += FullCategoryName;
1075 Result += "\n";
1076 }
1077 else
1078 Result += "\t, 0\n";
1079
1080 if (CDecl->getNumReferencedProtocols() > 0) {
1081 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1082 Result += FullCategoryName;
1083 Result += "\n";
1084 }
1085 else
1086 Result += "\t, 0\n";
1087 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001088}
1089
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001090/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1091/// ivar offset.
1092void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1093 ObjcIvarDecl *ivar,
1094 std::string &Result) {
1095 Result += "offsetof(struct _interface_";
1096 Result += IDecl->getName();
1097 Result += ", ";
1098 Result += ivar->getName();
1099 Result += ")";
1100}
1101
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001102//===----------------------------------------------------------------------===//
1103// Meta Data Emission
1104//===----------------------------------------------------------------------===//
1105
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001106void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1107 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001108 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1109
1110 // Build _objc_ivar_list metadata for classes ivars if needed
1111 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1112 ? IDecl->getImplDeclNumIvars()
1113 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1114
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001115 SynthesizeObjcInternalStruct(CDecl, Result);
1116
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001117 if (NumIvars > 0) {
1118 static bool objc_ivar = false;
1119 if (!objc_ivar) {
1120 /* struct _objc_ivar {
1121 char *ivar_name;
1122 char *ivar_type;
1123 int ivar_offset;
1124 };
1125 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001126 Result += "\nstruct _objc_ivar {\n";
1127 Result += "\tchar *ivar_name;\n";
1128 Result += "\tchar *ivar_type;\n";
1129 Result += "\tint ivar_offset;\n";
1130 Result += "};\n";
1131
1132 /* struct _objc_ivar_list {
1133 int ivar_count;
1134 struct _objc_ivar ivar_list[];
1135 };
1136 */
1137 Result += "\nstruct _objc_ivar_list {\n";
1138 Result += "\tint ivar_count;\n";
1139 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001140 objc_ivar = true;
1141 }
1142
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001143 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1144 Result += IDecl->getName();
1145 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1146 "{\n\t";
1147 Result += utostr(NumIvars);
1148 Result += "\n";
1149
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001150 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1151 ? IDecl->getImplDeclIVars()
1152 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001153 Result += "\t,{{\"";
1154 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001155 Result += "\", \"";
1156 std::string StrEncoding;
1157 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1158 Result += StrEncoding;
1159 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001160 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1161 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001162 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001163 Result += "\t ,{\"";
1164 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001165 Result += "\", \"";
1166 std::string StrEncoding;
1167 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1168 Result += StrEncoding;
1169 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001170 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1171 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001172 }
1173
1174 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001175 }
1176
1177 // Build _objc_method_list for class's instance methods if needed
1178 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1179 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001180 true,
1181 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001182
1183 // Build _objc_method_list for class's class methods if needed
1184 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001185 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001186 false,
1187 "", IDecl->getName(), Result);
1188
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001189 // Protocols referenced in class declaration?
1190 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1191 CDecl->getNumIntfRefProtocols(),
1192 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001193 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001194
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001195
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001196 // Declaration of class/meta-class metadata
1197 /* struct _objc_class {
1198 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001199 const char *super_class_name;
1200 char *name;
1201 long version;
1202 long info;
1203 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001204 struct _objc_ivar_list *ivars;
1205 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001206 struct objc_cache *cache;
1207 struct objc_protocol_list *protocols;
1208 const char *ivar_layout;
1209 struct _objc_class_ext *ext;
1210 };
1211 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001212 static bool objc_class = false;
1213 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001214 Result += "\nstruct _objc_class {\n";
1215 Result += "\tstruct _objc_class *isa;\n";
1216 Result += "\tconst char *super_class_name;\n";
1217 Result += "\tchar *name;\n";
1218 Result += "\tlong version;\n";
1219 Result += "\tlong info;\n";
1220 Result += "\tlong instance_size;\n";
1221 Result += "\tstruct _objc_ivar_list *ivars;\n";
1222 Result += "\tstruct _objc_method_list *methods;\n";
1223 Result += "\tstruct objc_cache *cache;\n";
1224 Result += "\tstruct _objc_protocol_list *protocols;\n";
1225 Result += "\tconst char *ivar_layout;\n";
1226 Result += "\tstruct _objc_class_ext *ext;\n";
1227 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001228 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001229 }
1230
1231 // Meta-class metadata generation.
1232 ObjcInterfaceDecl *RootClass = 0;
1233 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1234 while (SuperClass) {
1235 RootClass = SuperClass;
1236 SuperClass = SuperClass->getSuperClass();
1237 }
1238 SuperClass = CDecl->getSuperClass();
1239
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001240 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1241 Result += CDecl->getName();
1242 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1243 "{\n\t(struct _objc_class *)\"";
1244 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1245 Result += "\"";
1246
1247 if (SuperClass) {
1248 Result += ", \"";
1249 Result += SuperClass->getName();
1250 Result += "\", \"";
1251 Result += CDecl->getName();
1252 Result += "\"";
1253 }
1254 else {
1255 Result += ", 0, \"";
1256 Result += CDecl->getName();
1257 Result += "\"";
1258 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001259 // TODO: 'ivars' field for root class is currently set to 0.
1260 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001261 Result += ", 0,2, sizeof(struct _objc_class), 0";
1262 if (CDecl->getNumClassMethods() > 0) {
1263 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1264 Result += CDecl->getName();
1265 Result += "\n";
1266 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001267 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001268 Result += ", 0\n";
1269 if (CDecl->getNumIntfRefProtocols() > 0) {
1270 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1271 Result += CDecl->getName();
1272 Result += ",0,0\n";
1273 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001274 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001275 Result += "\t,0,0,0,0\n";
1276 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001277
1278 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001279 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1280 Result += CDecl->getName();
1281 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1282 "{\n\t&_OBJC_METACLASS_";
1283 Result += CDecl->getName();
1284 if (SuperClass) {
1285 Result += ", \"";
1286 Result += SuperClass->getName();
1287 Result += "\", \"";
1288 Result += CDecl->getName();
1289 Result += "\"";
1290 }
1291 else {
1292 Result += ", 0, \"";
1293 Result += CDecl->getName();
1294 Result += "\"";
1295 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001296 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001297 Result += ", 0,1";
1298 if (!ObjcSynthesizedStructs.count(CDecl))
1299 Result += ",0";
1300 else {
1301 // class has size. Must synthesize its size.
1302 Result += ",sizeof(struct _interface_";
1303 Result += CDecl->getName();
1304 Result += ")";
1305 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001306 if (NumIvars > 0) {
1307 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1308 Result += CDecl->getName();
1309 Result += "\n\t";
1310 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001311 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001312 Result += ",0";
1313 if (IDecl->getNumInstanceMethods() > 0) {
1314 Result += ", &_OBJC_INSTANCE_METHODS_";
1315 Result += CDecl->getName();
1316 Result += ", 0\n\t";
1317 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001318 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001319 Result += ",0,0";
1320 if (CDecl->getNumIntfRefProtocols() > 0) {
1321 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1322 Result += CDecl->getName();
1323 Result += ", 0,0\n";
1324 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001325 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001326 Result += ",0,0,0\n";
1327 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001328}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001329
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001330void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001331 int ClsDefCount = ClassImplementation.size();
1332 int CatDefCount = CategoryImplementation.size();
1333 if (ClsDefCount == 0 && CatDefCount == 0)
1334 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001335
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001336 // TODO: This is temporary until we decide how to access objc types in a
1337 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001338 Result += "#include <Objc/objc.h>\n";
1339 // This is needed for use of offsetof
1340 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001341
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001342 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001343 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001344 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001345
1346 // For each implemented category, write out all its meta data.
1347 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001348 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001349
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001350 // Write objc_symtab metadata
1351 /*
1352 struct _objc_symtab
1353 {
1354 long sel_ref_cnt;
1355 SEL *refs;
1356 short cls_def_cnt;
1357 short cat_def_cnt;
1358 void *defs[cls_def_cnt + cat_def_cnt];
1359 };
1360 */
1361
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001362 Result += "\nstruct _objc_symtab {\n";
1363 Result += "\tlong sel_ref_cnt;\n";
1364 Result += "\tSEL *refs;\n";
1365 Result += "\tshort cls_def_cnt;\n";
1366 Result += "\tshort cat_def_cnt;\n";
1367 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1368 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001369
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001370 Result += "static struct _objc_symtab "
1371 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1372 Result += "\t0, 0, " + utostr(ClsDefCount)
1373 + ", " + utostr(CatDefCount) + "\n";
1374 for (int i = 0; i < ClsDefCount; i++) {
1375 Result += "\t,&_OBJC_CLASS_";
1376 Result += ClassImplementation[i]->getName();
1377 Result += "\n";
1378 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001379
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001380 for (int i = 0; i < CatDefCount; i++) {
1381 Result += "\t,&_OBJC_CATEGORY_";
1382 Result += CategoryImplementation[i]->getClassInterface()->getName();
1383 Result += "_";
1384 Result += CategoryImplementation[i]->getName();
1385 Result += "\n";
1386 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001387
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001388 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001389
1390 // Write objc_module metadata
1391
1392 /*
1393 struct _objc_module {
1394 long version;
1395 long size;
1396 const char *name;
1397 struct _objc_symtab *symtab;
1398 }
1399 */
1400
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001401 Result += "\nstruct _objc_module {\n";
1402 Result += "\tlong version;\n";
1403 Result += "\tlong size;\n";
1404 Result += "\tconst char *name;\n";
1405 Result += "\tstruct _objc_symtab *symtab;\n";
1406 Result += "};\n\n";
1407 Result += "static struct _objc_module "
1408 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001409 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1410 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001411 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001412}
Chris Lattner311ff022007-10-16 22:36:42 +00001413