blob: b4d2fdf4a7bfce13c1fbfdff1415961bd494785e [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;
45
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);
Chris Lattner77cd2a02007-10-11 00:43:27 +000058 }
Chris Lattner8a12c272007-10-11 18:38:32 +000059
Chris Lattnerf04da132007-10-24 17:06:59 +000060 // Top Level Driver code.
61 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000062 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000063 ~RewriteTest();
64
65 // Syntactic Rewriting.
Chris Lattner2c64b7b2007-10-16 21:07:07 +000066 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000067 void RewriteTabs();
68 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000069 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000070 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000071 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000072 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Steve Naroff09b266e2007-10-30 23:14:51 +000073 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000074 void RewriteObjcQualifiedInterfaceTypes(
75 const FunctionTypeProto *proto, FunctionDecl *FD);
76 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000077
Chris Lattnerf04da132007-10-24 17:06:59 +000078 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000079 Stmt *RewriteFunctionBody(Stmt *S);
80 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
81 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +000082 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Steve Naroff934f2762007-10-24 22:48:43 +000083 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
84 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +000085 void SynthMsgSendFunctionDecl();
86 void SynthGetClassFunctionDecl();
87
Chris Lattnerf04da132007-10-24 17:06:59 +000088 // Metadata emission.
Steve Naroffbeaf2992007-11-03 11:27:19 +000089 void HandleObjcMetaDataEmission();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000090 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
91 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000092
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000093 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
94 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000095
96 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
97 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +000098 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000099 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000100 const char *ClassName,
101 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000102
103 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
104 int NumProtocols,
105 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000106 const char *ClassName,
107 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000108 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
109 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000110 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
111 ObjcIvarDecl *ivar,
112 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000113 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000114 };
115}
116
Chris Lattner8a12c272007-10-11 18:38:32 +0000117ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000118
Chris Lattnerf04da132007-10-24 17:06:59 +0000119//===----------------------------------------------------------------------===//
120// Top Level Driver Code
121//===----------------------------------------------------------------------===//
122
Chris Lattner8a12c272007-10-11 18:38:32 +0000123void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000124 // Two cases: either the decl could be in the main file, or it could be in a
125 // #included file. If the former, rewrite it now. If the later, check to see
126 // if we rewrote the #include/#import.
127 SourceLocation Loc = D->getLocation();
128 Loc = SM->getLogicalLoc(Loc);
129
130 // If this is for a builtin, ignore it.
131 if (Loc.isInvalid()) return;
132
Steve Naroffebf2b562007-10-23 23:50:29 +0000133 // Look for built-in declarations that we need to refer during the rewrite.
134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000135 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000136 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
137 // declared in <Foundation/NSString.h>
138 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
139 ConstantStringClassReference = FVD;
140 return;
141 }
Steve Naroffbef11852007-10-26 20:53:56 +0000142 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
143 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000144 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
145 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000146 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
147 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000148 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000149 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000150 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
151 return HandleDeclInMainFile(D);
152
Chris Lattnerf04da132007-10-24 17:06:59 +0000153 // Otherwise, see if there is a #import in the main file that should be
154 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000155 RewriteInclude(Loc);
156}
157
Chris Lattnerf04da132007-10-24 17:06:59 +0000158/// HandleDeclInMainFile - This is called for each top-level decl defined in the
159/// main file of the input.
160void RewriteTest::HandleDeclInMainFile(Decl *D) {
161 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
162 if (Stmt *Body = FD->getBody())
163 FD->setBody(RewriteFunctionBody(Body));
164
165 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
166 ClassImplementation.push_back(CI);
167 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
168 CategoryImplementation.push_back(CI);
169 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
170 RewriteForwardClassDecl(CD);
171 // Nothing yet.
172}
173
174RewriteTest::~RewriteTest() {
175 // Get the top-level buffer that this corresponds to.
176 RewriteTabs();
177
178 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
179 // we are done.
180 if (const RewriteBuffer *RewriteBuf =
181 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000182 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000183 std::string S(RewriteBuf->begin(), RewriteBuf->end());
184 printf("%s\n", S.c_str());
185 } else {
186 printf("No changes\n");
187 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000188
189}
190
Steve Naroffbeaf2992007-11-03 11:27:19 +0000191/// HandleObjcMetaDataEmission - main routine to generate objective-c's
192/// metadata.
193void RewriteTest::HandleObjcMetaDataEmission() {
194 // Rewrite Objective-c meta data*
195 std::string ResultStr;
196 WriteObjcMetaData(ResultStr);
197 // For now just print the string out.
198 printf("%s", ResultStr.c_str());
199}
200
Chris Lattnerf04da132007-10-24 17:06:59 +0000201//===----------------------------------------------------------------------===//
202// Syntactic (non-AST) Rewriting Code
203//===----------------------------------------------------------------------===//
204
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000205void RewriteTest::RewriteInclude(SourceLocation Loc) {
206 // Rip up the #include stack to the main file.
207 SourceLocation IncLoc = Loc, NextLoc = Loc;
208 do {
209 IncLoc = Loc;
210 Loc = SM->getLogicalLoc(NextLoc);
211 NextLoc = SM->getIncludeLoc(Loc);
212 } while (!NextLoc.isInvalid());
213
214 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
215 // IncLoc indicates the header that was included if it is useful.
216 IncLoc = SM->getLogicalLoc(IncLoc);
217 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
218 Loc == LastIncLoc)
219 return;
220 LastIncLoc = Loc;
221
222 unsigned IncCol = SM->getColumnNumber(Loc);
223 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
224
225 // Replace the #import with #include.
226 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
227}
228
Chris Lattnerf04da132007-10-24 17:06:59 +0000229void RewriteTest::RewriteTabs() {
230 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
231 const char *MainBufStart = MainBuf.first;
232 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000233
Chris Lattnerf04da132007-10-24 17:06:59 +0000234 // Loop over the whole file, looking for tabs.
235 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
236 if (*BufPtr != '\t')
237 continue;
238
239 // Okay, we found a tab. This tab will turn into at least one character,
240 // but it depends on which 'virtual column' it is in. Compute that now.
241 unsigned VCol = 0;
242 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
243 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
244 ++VCol;
245
246 // Okay, now that we know the virtual column, we know how many spaces to
247 // insert. We assume 8-character tab-stops.
248 unsigned Spaces = 8-(VCol & 7);
249
250 // Get the location of the tab.
251 SourceLocation TabLoc =
252 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
253
254 // Rewrite the single tab character into a sequence of spaces.
255 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
256 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000257}
258
259
Chris Lattnerf04da132007-10-24 17:06:59 +0000260void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
261 int numDecls = ClassDecl->getNumForwardDecls();
262 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
263
264 // Get the start location and compute the semi location.
265 SourceLocation startLoc = ClassDecl->getLocation();
266 const char *startBuf = SM->getCharacterData(startLoc);
267 const char *semiPtr = strchr(startBuf, ';');
268
269 // Translate to typedef's that forward reference structs with the same name
270 // as the class. As a convenience, we include the original declaration
271 // as a comment.
272 std::string typedefString;
273 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000274 typedefString.append(startBuf, semiPtr-startBuf+1);
275 typedefString += "\n";
276 for (int i = 0; i < numDecls; i++) {
277 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000278 if (ObjcForwardDecls.count(ForwardDecl))
279 continue;
Steve Naroff934f2762007-10-24 22:48:43 +0000280 typedefString += "typedef struct ";
281 typedefString += ForwardDecl->getName();
282 typedefString += " ";
283 typedefString += ForwardDecl->getName();
284 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000285
286 // Mark this typedef as having been generated.
287 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000288 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000289 }
290
291 // Replace the @class with typedefs corresponding to the classes.
292 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
293 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000294}
295
Steve Naroff423cb562007-10-30 13:30:57 +0000296void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
297 for (int i = 0; i < nMethods; i++) {
298 ObjcMethodDecl *Method = Methods[i];
299 SourceLocation Loc = Method->getLocStart();
300
301 Rewrite.ReplaceText(Loc, 0, "// ", 3);
302
303 // FIXME: handle methods that are declared across multiple lines.
304 }
305}
306
307void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
308 SourceLocation LocStart = CatDecl->getLocStart();
309
310 // FIXME: handle category headers that are declared across multiple lines.
311 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
312
313 RewriteMethods(CatDecl->getNumInstanceMethods(),
314 CatDecl->getInstanceMethods());
315 RewriteMethods(CatDecl->getNumClassMethods(),
316 CatDecl->getClassMethods());
317 // Lastly, comment out the @end.
318 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
319}
320
Steve Naroff752d6ef2007-10-30 16:42:30 +0000321void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
322 SourceLocation LocStart = PDecl->getLocStart();
323
324 // FIXME: handle protocol headers that are declared across multiple lines.
325 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
326
327 RewriteMethods(PDecl->getNumInstanceMethods(),
328 PDecl->getInstanceMethods());
329 RewriteMethods(PDecl->getNumClassMethods(),
330 PDecl->getClassMethods());
331 // Lastly, comment out the @end.
332 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
333}
334
Steve Naroffbef11852007-10-26 20:53:56 +0000335void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000336
337 SourceLocation LocStart = ClassDecl->getLocStart();
338 SourceLocation LocEnd = ClassDecl->getLocEnd();
339
340 const char *startBuf = SM->getCharacterData(LocStart);
341 const char *endBuf = SM->getCharacterData(LocEnd);
342
Steve Naroff2feac5e2007-10-30 03:43:13 +0000343 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000344
345 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000346 if (!ObjcForwardDecls.count(ClassDecl)) {
347 // we haven't seen a forward decl - generate a typedef.
348 ResultStr += "typedef struct ";
349 ResultStr += ClassDecl->getName();
350 ResultStr += " ";
351 ResultStr += ClassDecl->getName();
352 ResultStr += ";";
353
354 // Mark this typedef as having been generated.
355 ObjcForwardDecls.insert(ClassDecl);
356 }
Steve Narofff908a872007-10-30 02:23:23 +0000357 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
358
Steve Naroff2feac5e2007-10-30 03:43:13 +0000359 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000360 ResultStr.c_str(), ResultStr.size());
361
Steve Naroff423cb562007-10-30 13:30:57 +0000362 RewriteMethods(ClassDecl->getNumInstanceMethods(),
363 ClassDecl->getInstanceMethods());
364 RewriteMethods(ClassDecl->getNumClassMethods(),
365 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000366
Steve Naroff2feac5e2007-10-30 03:43:13 +0000367 // Lastly, comment out the @end.
368 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000369}
370
Chris Lattnerf04da132007-10-24 17:06:59 +0000371//===----------------------------------------------------------------------===//
372// Function Body / Expression rewriting
373//===----------------------------------------------------------------------===//
374
Chris Lattnere64b7772007-10-24 16:57:36 +0000375Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000376 // Otherwise, just rewrite all children.
377 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
378 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000379 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000380 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000381
382 // Handle specific things.
383 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
384 return RewriteAtEncode(AtEncode);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000385
386 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
387 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000388
Steve Naroff934f2762007-10-24 22:48:43 +0000389 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
390 // Before we rewrite it, put the original message expression in a comment.
391 SourceLocation startLoc = MessExpr->getLocStart();
392 SourceLocation endLoc = MessExpr->getLocEnd();
393
394 const char *startBuf = SM->getCharacterData(startLoc);
395 const char *endBuf = SM->getCharacterData(endLoc);
396
397 std::string messString;
398 messString += "// ";
399 messString.append(startBuf, endBuf-startBuf+1);
400 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000401
Steve Naroff934f2762007-10-24 22:48:43 +0000402 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
403 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
404 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000405 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000406 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000407 }
Chris Lattnere64b7772007-10-24 16:57:36 +0000408 // Return this stmt unmodified.
409 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000410}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000411
Chris Lattnere64b7772007-10-24 16:57:36 +0000412Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000413 // Create a new string expression.
414 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000415 std::string StrEncoding;
416 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
417 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
418 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000419 SourceLocation(), SourceLocation());
420 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000421 delete Exp;
422 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000423}
424
Steve Naroff934f2762007-10-24 22:48:43 +0000425CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
426 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000427 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000428 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000429
430 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000431 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000432
433 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000434 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000435 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
436
437 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000438
Steve Naroff934f2762007-10-24 22:48:43 +0000439 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
440}
441
Steve Naroffd5255f52007-11-01 13:24:47 +0000442static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
443 const char *&startRef, const char *&endRef) {
444 while (startBuf < endBuf) {
445 if (*startBuf == '<')
446 startRef = startBuf; // mark the start.
447 if (*startBuf == '>') {
448 assert((startRef && *startRef == '<') && "rewrite scanning error");
449 endRef = startBuf; // mark the end.
450 return true;
451 }
452 startBuf++;
453 }
454 return false;
455}
456
457bool RewriteTest::needToScanForQualifiers(QualType T) {
458 // FIXME: we don't currently represent "id <Protocol>" in the type system.
459 if (T == Context->getObjcIdType())
460 return true;
461
462 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000463 Type *pointeeType = pType->getPointeeType().getTypePtr();
464 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
465 return true; // we have "Class <Protocol> *".
466 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000467 return false;
468}
469
470void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
471 const FunctionTypeProto *proto, FunctionDecl *FD) {
472
473 if (needToScanForQualifiers(proto->getResultType())) {
474 // Since types are unique, we need to scan the buffer.
475 SourceLocation Loc = FD->getLocation();
476
477 const char *endBuf = SM->getCharacterData(Loc);
478 const char *startBuf = endBuf;
479 while (*startBuf != ';')
480 startBuf--; // scan backward (from the decl location) for return type.
481 const char *startRef = 0, *endRef = 0;
482 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
483 // Get the locations of the startRef, endRef.
484 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
485 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
486 // Comment out the protocol references.
487 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
488 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000489 }
490 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000491 // Now check arguments.
492 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
493 if (needToScanForQualifiers(proto->getArgType(i))) {
494 // Since types are unique, we need to scan the buffer.
495 SourceLocation Loc = FD->getLocation();
496
497 const char *startBuf = SM->getCharacterData(Loc);
498 const char *endBuf = startBuf;
499 while (*endBuf != ';')
500 endBuf++; // scan forward (from the decl location) for argument types.
501 const char *startRef = 0, *endRef = 0;
502 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
503 // Get the locations of the startRef, endRef.
504 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
505 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
506 // Comment out the protocol references.
507 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
508 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
509 }
510 }
511 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000512}
513
Steve Naroff09b266e2007-10-30 23:14:51 +0000514void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
515 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000516 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000517 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000518 return;
519 }
520 // Check for ObjC 'id' and class types that have been adorned with protocol
521 // information (id<p>, C<p>*). The protocol references need to be rewritten!
522 const FunctionType *funcType = FD->getType()->getAsFunctionType();
523 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000524 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
525 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000526}
527
528// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
529void RewriteTest::SynthMsgSendFunctionDecl() {
530 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
531 llvm::SmallVector<QualType, 16> ArgTys;
532 QualType argT = Context->getObjcIdType();
533 assert(!argT.isNull() && "Can't find 'id' type");
534 ArgTys.push_back(argT);
535 argT = Context->getObjcSelType();
536 assert(!argT.isNull() && "Can't find 'SEL' type");
537 ArgTys.push_back(argT);
538 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
539 &ArgTys[0], ArgTys.size(),
540 true /*isVariadic*/);
541 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
542 msgSendIdent, msgSendType,
543 FunctionDecl::Extern, false, 0);
544}
545
546// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
547void RewriteTest::SynthGetClassFunctionDecl() {
548 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
549 llvm::SmallVector<QualType, 16> ArgTys;
550 ArgTys.push_back(Context->getPointerType(
551 Context->CharTy.getQualifiedType(QualType::Const)));
552 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
553 &ArgTys[0], ArgTys.size(),
554 false /*isVariadic*/);
555 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
556 getClassIdent, getClassType,
557 FunctionDecl::Extern, false, 0);
558}
559
Steve Naroffbeaf2992007-11-03 11:27:19 +0000560Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
561 assert(ConstantStringClassReference && "Can't find constant string reference");
562 llvm::SmallVector<Expr*, 4> InitExprs;
563
564 // Synthesize "(Class)&_NSConstantStringClassReference"
565 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
566 ConstantStringClassReference->getType(),
567 SourceLocation());
568 QualType expType = Context->getPointerType(ClsRef->getType());
569 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
570 expType, SourceLocation());
571 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
572 SourceLocation());
573 InitExprs.push_back(cast); // set the 'isa'.
574 InitExprs.push_back(Exp->getString()); // set "char *bytes".
575 unsigned IntSize = static_cast<unsigned>(
576 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
577 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
578 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
579 Exp->getLocStart());
580 InitExprs.push_back(len); // set "int numBytes".
581
582 // struct NSConstantString
583 QualType CFConstantStrType = Context->getCFConstantStringType();
584 // (struct NSConstantString) { <exprs from above> }
585 InitListExpr *ILE = new InitListExpr(SourceLocation(),
586 &InitExprs[0], InitExprs.size(),
587 SourceLocation());
588 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
589 // struct NSConstantString *
590 expType = Context->getPointerType(StrRep->getType());
591 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
592 SourceLocation());
593 // struct NSString *
594 if (!NSStringRecord)
595 NSStringRecord = new RecordDecl(Decl::Struct, SourceLocation(),
596 &Context->Idents.get("NSString"), 0);
597 expType = Context->getPointerType(Context->getTagDeclType(NSStringRecord));
598 cast = new CastExpr(expType, Unop, SourceLocation());
599 Rewrite.ReplaceStmt(Exp, cast);
600 delete Exp;
601 return StrRep;
602}
603
Steve Naroff934f2762007-10-24 22:48:43 +0000604Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000605 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000606 if (!MsgSendFunctionDecl)
607 SynthMsgSendFunctionDecl();
608 if (!GetClassFunctionDecl)
609 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000610
611 // Synthesize a call to objc_msgSend().
612 llvm::SmallVector<Expr*, 8> MsgExprs;
613 IdentifierInfo *clsName = Exp->getClassName();
614
615 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
616 if (clsName) { // class message.
617 llvm::SmallVector<Expr*, 8> ClsExprs;
618 QualType argType = Context->getPointerType(Context->CharTy);
619 ClsExprs.push_back(new StringLiteral(clsName->getName(),
620 clsName->getLength(),
621 false, argType, SourceLocation(),
622 SourceLocation()));
623 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
624 &ClsExprs[0], ClsExprs.size());
625 MsgExprs.push_back(Cls);
626 } else // instance message.
627 MsgExprs.push_back(Exp->getReceiver());
628
Steve Naroffbeaf2992007-11-03 11:27:19 +0000629 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000630 llvm::SmallVector<Expr*, 8> SelExprs;
631 QualType argType = Context->getPointerType(Context->CharTy);
632 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
633 Exp->getSelector().getName().size(),
634 false, argType, SourceLocation(),
635 SourceLocation()));
636 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
637 &SelExprs[0], SelExprs.size());
638 MsgExprs.push_back(SelExp);
639
640 // Now push any user supplied arguments.
641 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
642 MsgExprs.push_back(Exp->getArg(i));
643 // We've transferred the ownership to MsgExprs. Null out the argument in
644 // the original expression, since we will delete it below.
645 Exp->setArg(i, 0);
646 }
647 CallExpr *MessExp = SynthesizeCallToFunctionDecl(MsgSendFunctionDecl,
648 &MsgExprs[0], MsgExprs.size());
649 // Now do the actual rewrite.
650 Rewrite.ReplaceStmt(Exp, MessExp);
651
Chris Lattnere64b7772007-10-24 16:57:36 +0000652 delete Exp;
Steve Naroff934f2762007-10-24 22:48:43 +0000653 return MessExp;
Steve Naroffebf2b562007-10-23 23:50:29 +0000654}
655
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000656/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
657/// an objective-c class with ivars.
658void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
659 std::string &Result) {
660 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
661 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000662 // Do not synthesize more than once.
663 if (ObjcSynthesizedStructs.count(CDecl))
664 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000665 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
666 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
667 // Do it for the root
668 SynthesizeObjcInternalStruct(RCDecl, Result);
669 }
670
671 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000672 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000673 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000674 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
675 return;
676
Steve Naroff04960052007-11-01 17:12:31 +0000677 Result += "\nstruct ";
678 Result += CDecl->getName();
679 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
680 Result += " {\n struct ";
681 Result += RCDecl->getName();
682 Result += " _";
683 Result += RCDecl->getName();
684 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000685 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000686 else
687 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000688
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000689 if (NumIvars > 0) {
690 SourceLocation LocStart = CDecl->getLocStart();
691 SourceLocation LocEnd = CDecl->getLocEnd();
692
693 const char *startBuf = SM->getCharacterData(LocStart);
694 const char *endBuf = SM->getCharacterData(LocEnd);
695 startBuf = strchr(startBuf, '{');
696 assert((startBuf && endBuf)
697 && "SynthesizeObjcInternalStruct - malformed @interface");
698 startBuf++; // past '{'
699 while (startBuf < endBuf) {
700 if (*startBuf == '@') {
701 startBuf = strchr(startBuf, 'p');
702 // FIXME: presence of @public, etc. inside comment results in
703 // this transformation as well, which is still correct c-code.
704 if (!strncmp(startBuf, "public", strlen("public"))) {
705 startBuf += strlen("public");
706 Result += "/* @public */";
707 }
708 else if (!strncmp(startBuf, "private", strlen("private"))) {
709 startBuf += strlen("private");
710 Result += "/* @private */";
711 }
712 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
713 startBuf += strlen("protected");
714 Result += "/* @protected */";
715 }
716 }
717 Result += *startBuf++;
718 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000719 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000720
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000721 Result += "};\n";
722 // Mark this struct as having been generated.
723 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000724 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000725}
726
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000727// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
728/// class methods.
729void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
730 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000731 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000732 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000733 const char *ClassName,
734 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000735 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000736 if (NumMethods > 0 && !objc_impl_method) {
737 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000738 SEL _cmd;
739 char *method_types;
740 void *_imp;
741 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000742 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000743 Result += "\nstruct _objc_method {\n";
744 Result += "\tSEL _cmd;\n";
745 Result += "\tchar *method_types;\n";
746 Result += "\tvoid *_imp;\n";
747 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000748
749 /* struct _objc_method_list {
750 struct _objc_method_list *next_method;
751 int method_count;
752 struct _objc_method method_list[];
753 }
754 */
755 Result += "\nstruct _objc_method_list {\n";
756 Result += "\tstruct _objc_method_list *next_method;\n";
757 Result += "\tint method_count;\n";
758 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000759 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000760 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000761 // Build _objc_method_list for class's methods if needed
762 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000763 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +0000764 Result += prefix;
765 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
766 Result += "_METHODS_";
767 Result += ClassName;
768 Result += " __attribute__ ((section (\"__OBJC, __";
769 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000770 Result += "_meth\")))= ";
771 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
772
773 Result += "\t,{{(SEL)\"";
774 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000775 std::string MethodTypeString;
776 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
777 Result += "\", \"";
778 Result += MethodTypeString;
779 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000780 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000781 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000782 Result += "\t ,{(SEL)\"";
783 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000784 std::string MethodTypeString;
785 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
786 Result += "\", \"";
787 Result += MethodTypeString;
788 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000789 }
790 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000791 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000792}
793
794/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
795void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
796 int NumProtocols,
797 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000798 const char *ClassName,
799 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000800 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000801 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000802 for (int i = 0; i < NumProtocols; i++) {
803 ObjcProtocolDecl *PDecl = Protocols[i];
804 // Output struct protocol_methods holder of method selector and type.
805 if (!objc_protocol_methods &&
806 (PDecl->getNumInstanceMethods() > 0
807 || PDecl->getNumClassMethods() > 0)) {
808 /* struct protocol_methods {
809 SEL _cmd;
810 char *method_types;
811 }
812 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000813 Result += "\nstruct protocol_methods {\n";
814 Result += "\tSEL _cmd;\n";
815 Result += "\tchar *method_types;\n";
816 Result += "};\n";
817
818 /* struct _objc_protocol_method_list {
819 int protocol_method_count;
820 struct protocol_methods protocols[];
821 }
822 */
823 Result += "\nstruct _objc_protocol_method_list {\n";
824 Result += "\tint protocol_method_count;\n";
825 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000826 objc_protocol_methods = true;
827 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000828
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000829 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000830 int NumMethods = PDecl->getNumInstanceMethods();
831 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000832 Result += "\nstatic struct _objc_protocol_method_list "
833 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
834 Result += PDecl->getName();
835 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
836 "{\n\t" + utostr(NumMethods) + "\n";
837
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000838 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000839 Result += "\t,{{(SEL)\"";
840 Result += Methods[0]->getSelector().getName().c_str();
841 Result += "\", \"\"}\n";
842
843 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000844 Result += "\t ,{(SEL)\"";
845 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000846 std::string MethodTypeString;
847 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
848 Result += "\", \"";
849 Result += MethodTypeString;
850 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000851 }
852 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000853 }
854
855 // Output class methods declared in this protocol.
856 NumMethods = PDecl->getNumClassMethods();
857 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000858 Result += "\nstatic struct _objc_protocol_method_list "
859 "_OBJC_PROTOCOL_CLASS_METHODS_";
860 Result += PDecl->getName();
861 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
862 "{\n\t";
863 Result += utostr(NumMethods);
864 Result += "\n";
865
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000866 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000867 Result += "\t,{{(SEL)\"";
868 Result += Methods[0]->getSelector().getName().c_str();
869 Result += "\", \"\"}\n";
870
871 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000872 Result += "\t ,{(SEL)\"";
873 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000874 std::string MethodTypeString;
875 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
876 Result += "\", \"";
877 Result += MethodTypeString;
878 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000879 }
880 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000881 }
882 // Output:
883 /* struct _objc_protocol {
884 // Objective-C 1.0 extensions
885 struct _objc_protocol_extension *isa;
886 char *protocol_name;
887 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000888 struct _objc_protocol_method_list *instance_methods;
889 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000890 };
891 */
892 static bool objc_protocol = false;
893 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000894 Result += "\nstruct _objc_protocol {\n";
895 Result += "\tstruct _objc_protocol_extension *isa;\n";
896 Result += "\tchar *protocol_name;\n";
897 Result += "\tstruct _objc_protocol **protocol_list;\n";
898 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
899 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
900 Result += "};\n";
901
902 /* struct _objc_protocol_list {
903 struct _objc_protocol_list *next;
904 int protocol_count;
905 struct _objc_protocol *class_protocols[];
906 }
907 */
908 Result += "\nstruct _objc_protocol_list {\n";
909 Result += "\tstruct _objc_protocol_list *next;\n";
910 Result += "\tint protocol_count;\n";
911 Result += "\tstruct _objc_protocol *class_protocols[];\n";
912 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000913 objc_protocol = true;
914 }
915
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000916 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
917 Result += PDecl->getName();
918 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
919 "{\n\t0, \"";
920 Result += PDecl->getName();
921 Result += "\", 0, ";
922 if (PDecl->getInstanceMethods() > 0) {
923 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
924 Result += PDecl->getName();
925 Result += ", ";
926 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000927 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000928 Result += "0, ";
929 if (PDecl->getClassMethods() > 0) {
930 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
931 Result += PDecl->getName();
932 Result += "\n";
933 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000934 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000935 Result += "0\n";
936 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000937 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000938 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000939 Result += "\nstatic struct _objc_protocol_list _OBJC_";
940 Result += prefix;
941 Result += "_PROTOCOLS_";
942 Result += ClassName;
943 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
944 "{\n\t0, ";
945 Result += utostr(NumProtocols);
946 Result += "\n";
947
948 Result += "\t,{&_OBJC_PROTOCOL_";
949 Result += Protocols[0]->getName();
950 Result += " \n";
951
952 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000953 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000954 Result += "\t ,&_OBJC_PROTOCOL_";
955 Result += PDecl->getName();
956 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000957 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000958 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000959 }
960}
961
962/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
963/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000964void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
965 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000966 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
967 // Find category declaration for this implementation.
968 ObjcCategoryDecl *CDecl;
969 for (CDecl = ClassDecl->getCategoryList(); CDecl;
970 CDecl = CDecl->getNextClassCategory())
971 if (CDecl->getIdentifier() == IDecl->getIdentifier())
972 break;
973 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
974
975 char *FullCategoryName = (char*)alloca(
976 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
977 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
978
979 // Build _objc_method_list for class's instance methods if needed
980 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
981 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000982 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000983 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000984
985 // Build _objc_method_list for class's class methods if needed
986 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
987 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000988 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000989 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000990
991 // Protocols referenced in class declaration?
992 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
993 CDecl->getNumReferencedProtocols(),
994 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000995 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000996
997 /* struct _objc_category {
998 char *category_name;
999 char *class_name;
1000 struct _objc_method_list *instance_methods;
1001 struct _objc_method_list *class_methods;
1002 struct _objc_protocol_list *protocols;
1003 // Objective-C 1.0 extensions
1004 uint32_t size; // sizeof (struct _objc_category)
1005 struct _objc_property_list *instance_properties; // category's own
1006 // @property decl.
1007 };
1008 */
1009
1010 static bool objc_category = false;
1011 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001012 Result += "\nstruct _objc_category {\n";
1013 Result += "\tchar *category_name;\n";
1014 Result += "\tchar *class_name;\n";
1015 Result += "\tstruct _objc_method_list *instance_methods;\n";
1016 Result += "\tstruct _objc_method_list *class_methods;\n";
1017 Result += "\tstruct _objc_protocol_list *protocols;\n";
1018 Result += "\tunsigned int size;\n";
1019 Result += "\tstruct _objc_property_list *instance_properties;\n";
1020 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001021 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001022 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001023 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1024 Result += FullCategoryName;
1025 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1026 Result += IDecl->getName();
1027 Result += "\"\n\t, \"";
1028 Result += ClassDecl->getName();
1029 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001030
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001031 if (IDecl->getNumInstanceMethods() > 0) {
1032 Result += "\t, (struct _objc_method_list *)"
1033 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1034 Result += FullCategoryName;
1035 Result += "\n";
1036 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001037 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001038 Result += "\t, 0\n";
1039 if (IDecl->getNumClassMethods() > 0) {
1040 Result += "\t, (struct _objc_method_list *)"
1041 "&_OBJC_CATEGORY_CLASS_METHODS_";
1042 Result += FullCategoryName;
1043 Result += "\n";
1044 }
1045 else
1046 Result += "\t, 0\n";
1047
1048 if (CDecl->getNumReferencedProtocols() > 0) {
1049 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1050 Result += FullCategoryName;
1051 Result += "\n";
1052 }
1053 else
1054 Result += "\t, 0\n";
1055 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001056}
1057
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001058/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1059/// ivar offset.
1060void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1061 ObjcIvarDecl *ivar,
1062 std::string &Result) {
1063 Result += "offsetof(struct _interface_";
1064 Result += IDecl->getName();
1065 Result += ", ";
1066 Result += ivar->getName();
1067 Result += ")";
1068}
1069
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001070//===----------------------------------------------------------------------===//
1071// Meta Data Emission
1072//===----------------------------------------------------------------------===//
1073
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001074void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1075 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001076 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1077
1078 // Build _objc_ivar_list metadata for classes ivars if needed
1079 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1080 ? IDecl->getImplDeclNumIvars()
1081 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1082
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001083 SynthesizeObjcInternalStruct(CDecl, Result);
1084
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001085 if (NumIvars > 0) {
1086 static bool objc_ivar = false;
1087 if (!objc_ivar) {
1088 /* struct _objc_ivar {
1089 char *ivar_name;
1090 char *ivar_type;
1091 int ivar_offset;
1092 };
1093 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001094 Result += "\nstruct _objc_ivar {\n";
1095 Result += "\tchar *ivar_name;\n";
1096 Result += "\tchar *ivar_type;\n";
1097 Result += "\tint ivar_offset;\n";
1098 Result += "};\n";
1099
1100 /* struct _objc_ivar_list {
1101 int ivar_count;
1102 struct _objc_ivar ivar_list[];
1103 };
1104 */
1105 Result += "\nstruct _objc_ivar_list {\n";
1106 Result += "\tint ivar_count;\n";
1107 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001108 objc_ivar = true;
1109 }
1110
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001111 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1112 Result += IDecl->getName();
1113 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1114 "{\n\t";
1115 Result += utostr(NumIvars);
1116 Result += "\n";
1117
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001118 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1119 ? IDecl->getImplDeclIVars()
1120 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001121 Result += "\t,{{\"";
1122 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001123 Result += "\", \"";
1124 std::string StrEncoding;
1125 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1126 Result += StrEncoding;
1127 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001128 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1129 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001130 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001131 Result += "\t ,{\"";
1132 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001133 Result += "\", \"";
1134 std::string StrEncoding;
1135 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1136 Result += StrEncoding;
1137 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001138 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1139 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001140 }
1141
1142 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001143 }
1144
1145 // Build _objc_method_list for class's instance methods if needed
1146 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1147 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001148 true,
1149 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001150
1151 // Build _objc_method_list for class's class methods if needed
1152 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001153 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001154 false,
1155 "", IDecl->getName(), Result);
1156
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001157 // Protocols referenced in class declaration?
1158 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1159 CDecl->getNumIntfRefProtocols(),
1160 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001161 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001162
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001163
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001164 // Declaration of class/meta-class metadata
1165 /* struct _objc_class {
1166 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001167 const char *super_class_name;
1168 char *name;
1169 long version;
1170 long info;
1171 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001172 struct _objc_ivar_list *ivars;
1173 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001174 struct objc_cache *cache;
1175 struct objc_protocol_list *protocols;
1176 const char *ivar_layout;
1177 struct _objc_class_ext *ext;
1178 };
1179 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001180 static bool objc_class = false;
1181 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001182 Result += "\nstruct _objc_class {\n";
1183 Result += "\tstruct _objc_class *isa;\n";
1184 Result += "\tconst char *super_class_name;\n";
1185 Result += "\tchar *name;\n";
1186 Result += "\tlong version;\n";
1187 Result += "\tlong info;\n";
1188 Result += "\tlong instance_size;\n";
1189 Result += "\tstruct _objc_ivar_list *ivars;\n";
1190 Result += "\tstruct _objc_method_list *methods;\n";
1191 Result += "\tstruct objc_cache *cache;\n";
1192 Result += "\tstruct _objc_protocol_list *protocols;\n";
1193 Result += "\tconst char *ivar_layout;\n";
1194 Result += "\tstruct _objc_class_ext *ext;\n";
1195 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001196 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001197 }
1198
1199 // Meta-class metadata generation.
1200 ObjcInterfaceDecl *RootClass = 0;
1201 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1202 while (SuperClass) {
1203 RootClass = SuperClass;
1204 SuperClass = SuperClass->getSuperClass();
1205 }
1206 SuperClass = CDecl->getSuperClass();
1207
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001208 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1209 Result += CDecl->getName();
1210 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1211 "{\n\t(struct _objc_class *)\"";
1212 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1213 Result += "\"";
1214
1215 if (SuperClass) {
1216 Result += ", \"";
1217 Result += SuperClass->getName();
1218 Result += "\", \"";
1219 Result += CDecl->getName();
1220 Result += "\"";
1221 }
1222 else {
1223 Result += ", 0, \"";
1224 Result += CDecl->getName();
1225 Result += "\"";
1226 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001227 // TODO: 'ivars' field for root class is currently set to 0.
1228 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001229 Result += ", 0,2, sizeof(struct _objc_class), 0";
1230 if (CDecl->getNumClassMethods() > 0) {
1231 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1232 Result += CDecl->getName();
1233 Result += "\n";
1234 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001235 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001236 Result += ", 0\n";
1237 if (CDecl->getNumIntfRefProtocols() > 0) {
1238 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1239 Result += CDecl->getName();
1240 Result += ",0,0\n";
1241 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001242 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001243 Result += "\t,0,0,0,0\n";
1244 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001245
1246 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001247 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1248 Result += CDecl->getName();
1249 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1250 "{\n\t&_OBJC_METACLASS_";
1251 Result += CDecl->getName();
1252 if (SuperClass) {
1253 Result += ", \"";
1254 Result += SuperClass->getName();
1255 Result += "\", \"";
1256 Result += CDecl->getName();
1257 Result += "\"";
1258 }
1259 else {
1260 Result += ", 0, \"";
1261 Result += CDecl->getName();
1262 Result += "\"";
1263 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001264 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001265 Result += ", 0,1";
1266 if (!ObjcSynthesizedStructs.count(CDecl))
1267 Result += ",0";
1268 else {
1269 // class has size. Must synthesize its size.
1270 Result += ",sizeof(struct _interface_";
1271 Result += CDecl->getName();
1272 Result += ")";
1273 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001274 if (NumIvars > 0) {
1275 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1276 Result += CDecl->getName();
1277 Result += "\n\t";
1278 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001279 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001280 Result += ",0";
1281 if (IDecl->getNumInstanceMethods() > 0) {
1282 Result += ", &_OBJC_INSTANCE_METHODS_";
1283 Result += CDecl->getName();
1284 Result += ", 0\n\t";
1285 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001286 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001287 Result += ",0,0";
1288 if (CDecl->getNumIntfRefProtocols() > 0) {
1289 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1290 Result += CDecl->getName();
1291 Result += ", 0,0\n";
1292 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001293 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001294 Result += ",0,0,0\n";
1295 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001296}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001297
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001298void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001299 int ClsDefCount = ClassImplementation.size();
1300 int CatDefCount = CategoryImplementation.size();
1301 if (ClsDefCount == 0 && CatDefCount == 0)
1302 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001303
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001304 // TODO: This is temporary until we decide how to access objc types in a
1305 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001306 Result += "#include <Objc/objc.h>\n";
1307 // This is needed for use of offsetof
1308 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001309
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001310 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001311 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001312 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001313
1314 // For each implemented category, write out all its meta data.
1315 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001316 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001317
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001318 // Write objc_symtab metadata
1319 /*
1320 struct _objc_symtab
1321 {
1322 long sel_ref_cnt;
1323 SEL *refs;
1324 short cls_def_cnt;
1325 short cat_def_cnt;
1326 void *defs[cls_def_cnt + cat_def_cnt];
1327 };
1328 */
1329
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001330 Result += "\nstruct _objc_symtab {\n";
1331 Result += "\tlong sel_ref_cnt;\n";
1332 Result += "\tSEL *refs;\n";
1333 Result += "\tshort cls_def_cnt;\n";
1334 Result += "\tshort cat_def_cnt;\n";
1335 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1336 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001337
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001338 Result += "static struct _objc_symtab "
1339 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1340 Result += "\t0, 0, " + utostr(ClsDefCount)
1341 + ", " + utostr(CatDefCount) + "\n";
1342 for (int i = 0; i < ClsDefCount; i++) {
1343 Result += "\t,&_OBJC_CLASS_";
1344 Result += ClassImplementation[i]->getName();
1345 Result += "\n";
1346 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001347
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001348 for (int i = 0; i < CatDefCount; i++) {
1349 Result += "\t,&_OBJC_CATEGORY_";
1350 Result += CategoryImplementation[i]->getClassInterface()->getName();
1351 Result += "_";
1352 Result += CategoryImplementation[i]->getName();
1353 Result += "\n";
1354 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001355
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001356 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001357
1358 // Write objc_module metadata
1359
1360 /*
1361 struct _objc_module {
1362 long version;
1363 long size;
1364 const char *name;
1365 struct _objc_symtab *symtab;
1366 }
1367 */
1368
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001369 Result += "\nstruct _objc_module {\n";
1370 Result += "\tlong version;\n";
1371 Result += "\tlong size;\n";
1372 Result += "\tconst char *name;\n";
1373 Result += "\tstruct _objc_symtab *symtab;\n";
1374 Result += "};\n\n";
1375 Result += "static struct _objc_module "
1376 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001377 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1378 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001379 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001380}
Chris Lattner311ff022007-10-16 22:36:42 +00001381