blob: fa4a369f1772601e1e9bf2b5f8066f9fe92fdebb [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 Naroffe3abbf52007-11-05 14:55:35 +000058 // declaring objc_selector outside the parameter list removes a silly
59 // scope related warning...
60 const char *s = "struct objc_selector;\n"
61 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000062 "(struct objc_object *, struct objc_selector *, ...);\n"
63 "extern struct objc_object *objc_getClass"
64 "(const char *);\n";
65 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
66 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000067 }
Chris Lattner8a12c272007-10-11 18:38:32 +000068
Chris Lattnerf04da132007-10-24 17:06:59 +000069 // Top Level Driver code.
70 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000071 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000072 ~RewriteTest();
73
74 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000075 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000076 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000077 void RewriteTabs();
78 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000079 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000080 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000081 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000082 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000083 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000084 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000085 void RewriteObjcQualifiedInterfaceTypes(
86 const FunctionTypeProto *proto, FunctionDecl *FD);
87 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000088
Chris Lattnerf04da132007-10-24 17:06:59 +000089 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000090 Stmt *RewriteFunctionBody(Stmt *S);
91 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +000092 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +000093 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +000094 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +000095 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
96 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
97 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +000098 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
99 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000100 void SynthMsgSendFunctionDecl();
101 void SynthGetClassFunctionDecl();
102
Chris Lattnerf04da132007-10-24 17:06:59 +0000103 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000104 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
105 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000106
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000107 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
108 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000109
110 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
111 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000112 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000113 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000114 const char *ClassName,
115 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000116
117 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
118 int NumProtocols,
119 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000120 const char *ClassName,
121 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000122 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
123 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000124 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
125 ObjcIvarDecl *ivar,
126 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000127 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000128 };
129}
130
Chris Lattner8a12c272007-10-11 18:38:32 +0000131ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000132
Chris Lattnerf04da132007-10-24 17:06:59 +0000133//===----------------------------------------------------------------------===//
134// Top Level Driver Code
135//===----------------------------------------------------------------------===//
136
Chris Lattner8a12c272007-10-11 18:38:32 +0000137void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000138 // Two cases: either the decl could be in the main file, or it could be in a
139 // #included file. If the former, rewrite it now. If the later, check to see
140 // if we rewrote the #include/#import.
141 SourceLocation Loc = D->getLocation();
142 Loc = SM->getLogicalLoc(Loc);
143
144 // If this is for a builtin, ignore it.
145 if (Loc.isInvalid()) return;
146
Steve Naroffebf2b562007-10-23 23:50:29 +0000147 // Look for built-in declarations that we need to refer during the rewrite.
148 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000149 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000150 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
151 // declared in <Foundation/NSString.h>
152 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
153 ConstantStringClassReference = FVD;
154 return;
155 }
Steve Naroffbef11852007-10-26 20:53:56 +0000156 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
157 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000158 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
159 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000160 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
161 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000162 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000163 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000164 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
165 return HandleDeclInMainFile(D);
166
Chris Lattnerf04da132007-10-24 17:06:59 +0000167 // Otherwise, see if there is a #import in the main file that should be
168 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000169 RewriteInclude(Loc);
170}
171
Chris Lattnerf04da132007-10-24 17:06:59 +0000172/// HandleDeclInMainFile - This is called for each top-level decl defined in the
173/// main file of the input.
174void RewriteTest::HandleDeclInMainFile(Decl *D) {
175 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
176 if (Stmt *Body = FD->getBody())
177 FD->setBody(RewriteFunctionBody(Body));
178
179 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
180 ClassImplementation.push_back(CI);
181 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
182 CategoryImplementation.push_back(CI);
183 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
184 RewriteForwardClassDecl(CD);
185 // Nothing yet.
186}
187
188RewriteTest::~RewriteTest() {
189 // Get the top-level buffer that this corresponds to.
190 RewriteTabs();
191
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000192 // Rewrite Objective-c meta data*
193 std::string ResultStr;
194 WriteObjcMetaData(ResultStr);
195 // For now just print the string out.
196 printf("%s", ResultStr.c_str());
197
Chris Lattnerf04da132007-10-24 17:06:59 +0000198 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
199 // we are done.
200 if (const RewriteBuffer *RewriteBuf =
201 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000202 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000203 std::string S(RewriteBuf->begin(), RewriteBuf->end());
204 printf("%s\n", S.c_str());
205 } else {
206 printf("No changes\n");
207 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000208
209}
210
Chris Lattnerf04da132007-10-24 17:06:59 +0000211//===----------------------------------------------------------------------===//
212// Syntactic (non-AST) Rewriting Code
213//===----------------------------------------------------------------------===//
214
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000215void RewriteTest::RewriteInclude(SourceLocation Loc) {
216 // Rip up the #include stack to the main file.
217 SourceLocation IncLoc = Loc, NextLoc = Loc;
218 do {
219 IncLoc = Loc;
220 Loc = SM->getLogicalLoc(NextLoc);
221 NextLoc = SM->getIncludeLoc(Loc);
222 } while (!NextLoc.isInvalid());
223
224 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
225 // IncLoc indicates the header that was included if it is useful.
226 IncLoc = SM->getLogicalLoc(IncLoc);
227 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
228 Loc == LastIncLoc)
229 return;
230 LastIncLoc = Loc;
231
232 unsigned IncCol = SM->getColumnNumber(Loc);
233 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
234
235 // Replace the #import with #include.
236 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
237}
238
Chris Lattnerf04da132007-10-24 17:06:59 +0000239void RewriteTest::RewriteTabs() {
240 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
241 const char *MainBufStart = MainBuf.first;
242 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000243
Chris Lattnerf04da132007-10-24 17:06:59 +0000244 // Loop over the whole file, looking for tabs.
245 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
246 if (*BufPtr != '\t')
247 continue;
248
249 // Okay, we found a tab. This tab will turn into at least one character,
250 // but it depends on which 'virtual column' it is in. Compute that now.
251 unsigned VCol = 0;
252 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
253 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
254 ++VCol;
255
256 // Okay, now that we know the virtual column, we know how many spaces to
257 // insert. We assume 8-character tab-stops.
258 unsigned Spaces = 8-(VCol & 7);
259
260 // Get the location of the tab.
261 SourceLocation TabLoc =
262 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
263
264 // Rewrite the single tab character into a sequence of spaces.
265 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
266 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000267}
268
269
Chris Lattnerf04da132007-10-24 17:06:59 +0000270void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
271 int numDecls = ClassDecl->getNumForwardDecls();
272 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
273
274 // Get the start location and compute the semi location.
275 SourceLocation startLoc = ClassDecl->getLocation();
276 const char *startBuf = SM->getCharacterData(startLoc);
277 const char *semiPtr = strchr(startBuf, ';');
278
279 // Translate to typedef's that forward reference structs with the same name
280 // as the class. As a convenience, we include the original declaration
281 // as a comment.
282 std::string typedefString;
283 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000284 typedefString.append(startBuf, semiPtr-startBuf+1);
285 typedefString += "\n";
286 for (int i = 0; i < numDecls; i++) {
287 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000288 if (ObjcForwardDecls.count(ForwardDecl))
289 continue;
Steve Naroff352336b2007-11-05 14:36:37 +0000290 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000291 typedefString += ForwardDecl->getName();
292 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000293
294 // Mark this typedef as having been generated.
295 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000296 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000297 }
298
299 // Replace the @class with typedefs corresponding to the classes.
300 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
301 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000302}
303
Steve Naroff423cb562007-10-30 13:30:57 +0000304void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
305 for (int i = 0; i < nMethods; i++) {
306 ObjcMethodDecl *Method = Methods[i];
307 SourceLocation Loc = Method->getLocStart();
308
309 Rewrite.ReplaceText(Loc, 0, "// ", 3);
310
311 // FIXME: handle methods that are declared across multiple lines.
312 }
313}
314
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000315void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
316{
317 for (int i = 0; i < nProperties; i++) {
318 ObjcPropertyDecl *Property = Properties[i];
319 SourceLocation Loc = Property->getLocation();
320
321 Rewrite.ReplaceText(Loc, 0, "// ", 3);
322
323 // FIXME: handle properties that are declared across multiple lines.
324 }
325}
326
Steve Naroff423cb562007-10-30 13:30:57 +0000327void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
328 SourceLocation LocStart = CatDecl->getLocStart();
329
330 // FIXME: handle category headers that are declared across multiple lines.
331 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
332
333 RewriteMethods(CatDecl->getNumInstanceMethods(),
334 CatDecl->getInstanceMethods());
335 RewriteMethods(CatDecl->getNumClassMethods(),
336 CatDecl->getClassMethods());
337 // Lastly, comment out the @end.
338 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
339}
340
Steve Naroff752d6ef2007-10-30 16:42:30 +0000341void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
342 SourceLocation LocStart = PDecl->getLocStart();
343
344 // FIXME: handle protocol headers that are declared across multiple lines.
345 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
346
347 RewriteMethods(PDecl->getNumInstanceMethods(),
348 PDecl->getInstanceMethods());
349 RewriteMethods(PDecl->getNumClassMethods(),
350 PDecl->getClassMethods());
351 // Lastly, comment out the @end.
352 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
353}
354
Steve Naroffbef11852007-10-26 20:53:56 +0000355void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000356
357 SourceLocation LocStart = ClassDecl->getLocStart();
358 SourceLocation LocEnd = ClassDecl->getLocEnd();
359
360 const char *startBuf = SM->getCharacterData(LocStart);
361 const char *endBuf = SM->getCharacterData(LocEnd);
362
Steve Naroff2feac5e2007-10-30 03:43:13 +0000363 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000364
365 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000366 if (!ObjcForwardDecls.count(ClassDecl)) {
367 // we haven't seen a forward decl - generate a typedef.
Steve Naroff352336b2007-11-05 14:36:37 +0000368 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000369 ResultStr += ClassDecl->getName();
370 ResultStr += ";";
371
372 // Mark this typedef as having been generated.
373 ObjcForwardDecls.insert(ClassDecl);
374 }
Steve Narofff908a872007-10-30 02:23:23 +0000375 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
376
Steve Naroff2feac5e2007-10-30 03:43:13 +0000377 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000378 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000379 RewriteProperties(ClassDecl->getNumPropertyDecl(),
380 ClassDecl->getPropertyDecl());
Steve Naroff423cb562007-10-30 13:30:57 +0000381 RewriteMethods(ClassDecl->getNumInstanceMethods(),
382 ClassDecl->getInstanceMethods());
383 RewriteMethods(ClassDecl->getNumClassMethods(),
384 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000385
Steve Naroff2feac5e2007-10-30 03:43:13 +0000386 // Lastly, comment out the @end.
387 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000388}
389
Chris Lattnerf04da132007-10-24 17:06:59 +0000390//===----------------------------------------------------------------------===//
391// Function Body / Expression rewriting
392//===----------------------------------------------------------------------===//
393
Chris Lattnere64b7772007-10-24 16:57:36 +0000394Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000395 // Otherwise, just rewrite all children.
396 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
397 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000398 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000399 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000400
401 // Handle specific things.
402 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
403 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000404
405 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
406 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000407
408 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
409 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000410
Steve Naroff934f2762007-10-24 22:48:43 +0000411 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
412 // Before we rewrite it, put the original message expression in a comment.
413 SourceLocation startLoc = MessExpr->getLocStart();
414 SourceLocation endLoc = MessExpr->getLocEnd();
415
416 const char *startBuf = SM->getCharacterData(startLoc);
417 const char *endBuf = SM->getCharacterData(endLoc);
418
419 std::string messString;
420 messString += "// ";
421 messString.append(startBuf, endBuf-startBuf+1);
422 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000423
Steve Naroff934f2762007-10-24 22:48:43 +0000424 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
425 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
426 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000427 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000428 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000429 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000430
431 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
432 return RewriteObjcTryStmt(StmtTry);
433
434 if (ObjcAtCatchStmt *StmtCatch = dyn_cast<ObjcAtCatchStmt>(S))
435 return RewriteObjcCatchStmt(StmtCatch);
436
437 if (ObjcAtFinallyStmt *StmtFinally = dyn_cast<ObjcAtFinallyStmt>(S))
438 return RewriteObjcFinallyStmt(StmtFinally);
439
Chris Lattnere64b7772007-10-24 16:57:36 +0000440 // Return this stmt unmodified.
441 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000442}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000443
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000444Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
445 return 0;
446}
447
448Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
449 return 0;
450}
451
452Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
453 return 0;
454}
455
456
Chris Lattnere64b7772007-10-24 16:57:36 +0000457Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000458 // Create a new string expression.
459 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000460 std::string StrEncoding;
461 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
462 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
463 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000464 SourceLocation(), SourceLocation());
465 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000466 delete Exp;
467 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000468}
469
Steve Naroffb42f8412007-11-05 14:50:49 +0000470Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
471 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
472 // Create a call to sel_registerName("selName").
473 llvm::SmallVector<Expr*, 8> SelExprs;
474 QualType argType = Context->getPointerType(Context->CharTy);
475 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
476 Exp->getSelector().getName().size(),
477 false, argType, SourceLocation(),
478 SourceLocation()));
479 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
480 &SelExprs[0], SelExprs.size());
481 Rewrite.ReplaceStmt(Exp, SelExp);
482 delete Exp;
483 return SelExp;
484}
485
Steve Naroff934f2762007-10-24 22:48:43 +0000486CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
487 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000488 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000489 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000490
491 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000492 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000493
494 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000495 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000496 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
497
498 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000499
Steve Naroff934f2762007-10-24 22:48:43 +0000500 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
501}
502
Steve Naroffd5255f52007-11-01 13:24:47 +0000503static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
504 const char *&startRef, const char *&endRef) {
505 while (startBuf < endBuf) {
506 if (*startBuf == '<')
507 startRef = startBuf; // mark the start.
508 if (*startBuf == '>') {
509 assert((startRef && *startRef == '<') && "rewrite scanning error");
510 endRef = startBuf; // mark the end.
511 return true;
512 }
513 startBuf++;
514 }
515 return false;
516}
517
518bool RewriteTest::needToScanForQualifiers(QualType T) {
519 // FIXME: we don't currently represent "id <Protocol>" in the type system.
520 if (T == Context->getObjcIdType())
521 return true;
522
523 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000524 Type *pointeeType = pType->getPointeeType().getTypePtr();
525 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
526 return true; // we have "Class <Protocol> *".
527 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000528 return false;
529}
530
531void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
532 const FunctionTypeProto *proto, FunctionDecl *FD) {
533
534 if (needToScanForQualifiers(proto->getResultType())) {
535 // Since types are unique, we need to scan the buffer.
536 SourceLocation Loc = FD->getLocation();
537
538 const char *endBuf = SM->getCharacterData(Loc);
539 const char *startBuf = endBuf;
540 while (*startBuf != ';')
541 startBuf--; // scan backward (from the decl location) for return type.
542 const char *startRef = 0, *endRef = 0;
543 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
544 // Get the locations of the startRef, endRef.
545 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
546 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
547 // Comment out the protocol references.
548 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
549 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000550 }
551 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000552 // Now check arguments.
553 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
554 if (needToScanForQualifiers(proto->getArgType(i))) {
555 // Since types are unique, we need to scan the buffer.
556 SourceLocation Loc = FD->getLocation();
557
558 const char *startBuf = SM->getCharacterData(Loc);
559 const char *endBuf = startBuf;
560 while (*endBuf != ';')
561 endBuf++; // scan forward (from the decl location) for argument types.
562 const char *startRef = 0, *endRef = 0;
563 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
564 // Get the locations of the startRef, endRef.
565 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
566 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
567 // Comment out the protocol references.
568 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
569 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
570 }
571 }
572 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000573}
574
Steve Naroff09b266e2007-10-30 23:14:51 +0000575void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
576 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000577 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000578 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000579 return;
580 }
581 // Check for ObjC 'id' and class types that have been adorned with protocol
582 // information (id<p>, C<p>*). The protocol references need to be rewritten!
583 const FunctionType *funcType = FD->getType()->getAsFunctionType();
584 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000585 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
586 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000587}
588
589// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
590void RewriteTest::SynthMsgSendFunctionDecl() {
591 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
592 llvm::SmallVector<QualType, 16> ArgTys;
593 QualType argT = Context->getObjcIdType();
594 assert(!argT.isNull() && "Can't find 'id' type");
595 ArgTys.push_back(argT);
596 argT = Context->getObjcSelType();
597 assert(!argT.isNull() && "Can't find 'SEL' type");
598 ArgTys.push_back(argT);
599 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
600 &ArgTys[0], ArgTys.size(),
601 true /*isVariadic*/);
602 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
603 msgSendIdent, msgSendType,
604 FunctionDecl::Extern, false, 0);
605}
606
607// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
608void RewriteTest::SynthGetClassFunctionDecl() {
609 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
610 llvm::SmallVector<QualType, 16> ArgTys;
611 ArgTys.push_back(Context->getPointerType(
612 Context->CharTy.getQualifiedType(QualType::Const)));
613 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
614 &ArgTys[0], ArgTys.size(),
615 false /*isVariadic*/);
616 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
617 getClassIdent, getClassType,
618 FunctionDecl::Extern, false, 0);
619}
620
Steve Naroffbeaf2992007-11-03 11:27:19 +0000621Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
622 assert(ConstantStringClassReference && "Can't find constant string reference");
623 llvm::SmallVector<Expr*, 4> InitExprs;
624
625 // Synthesize "(Class)&_NSConstantStringClassReference"
626 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
627 ConstantStringClassReference->getType(),
628 SourceLocation());
629 QualType expType = Context->getPointerType(ClsRef->getType());
630 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
631 expType, SourceLocation());
632 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
633 SourceLocation());
634 InitExprs.push_back(cast); // set the 'isa'.
635 InitExprs.push_back(Exp->getString()); // set "char *bytes".
636 unsigned IntSize = static_cast<unsigned>(
637 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
638 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
639 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
640 Exp->getLocStart());
641 InitExprs.push_back(len); // set "int numBytes".
642
643 // struct NSConstantString
644 QualType CFConstantStrType = Context->getCFConstantStringType();
645 // (struct NSConstantString) { <exprs from above> }
646 InitListExpr *ILE = new InitListExpr(SourceLocation(),
647 &InitExprs[0], InitExprs.size(),
648 SourceLocation());
649 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
650 // struct NSConstantString *
651 expType = Context->getPointerType(StrRep->getType());
652 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
653 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000654 // cast to NSConstantString *
655 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000656 Rewrite.ReplaceStmt(Exp, cast);
657 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000658 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +0000659}
660
Steve Naroff934f2762007-10-24 22:48:43 +0000661Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000662 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000663 if (!MsgSendFunctionDecl)
664 SynthMsgSendFunctionDecl();
665 if (!GetClassFunctionDecl)
666 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000667
668 // Synthesize a call to objc_msgSend().
669 llvm::SmallVector<Expr*, 8> MsgExprs;
670 IdentifierInfo *clsName = Exp->getClassName();
671
672 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
673 if (clsName) { // class message.
674 llvm::SmallVector<Expr*, 8> ClsExprs;
675 QualType argType = Context->getPointerType(Context->CharTy);
676 ClsExprs.push_back(new StringLiteral(clsName->getName(),
677 clsName->getLength(),
678 false, argType, SourceLocation(),
679 SourceLocation()));
680 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
681 &ClsExprs[0], ClsExprs.size());
682 MsgExprs.push_back(Cls);
683 } else // instance message.
684 MsgExprs.push_back(Exp->getReceiver());
685
Steve Naroffbeaf2992007-11-03 11:27:19 +0000686 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000687 llvm::SmallVector<Expr*, 8> SelExprs;
688 QualType argType = Context->getPointerType(Context->CharTy);
689 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
690 Exp->getSelector().getName().size(),
691 false, argType, SourceLocation(),
692 SourceLocation()));
693 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
694 &SelExprs[0], SelExprs.size());
695 MsgExprs.push_back(SelExp);
696
697 // Now push any user supplied arguments.
698 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
699 MsgExprs.push_back(Exp->getArg(i));
700 // We've transferred the ownership to MsgExprs. Null out the argument in
701 // the original expression, since we will delete it below.
702 Exp->setArg(i, 0);
703 }
Steve Naroffab972d32007-11-04 22:37:50 +0000704 // Generate the funky cast.
705 CastExpr *cast;
706 llvm::SmallVector<QualType, 8> ArgTypes;
707 QualType returnType;
708
709 // Push 'id' and 'SEL', the 2 implicit arguments.
710 ArgTypes.push_back(Context->getObjcIdType());
711 ArgTypes.push_back(Context->getObjcSelType());
712 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
713 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +0000714 for (int i = 0; i < mDecl->getNumParams(); i++) {
715 QualType t = mDecl->getParamDecl(i)->getType();
716 if (t == Context->getObjcClassType())
717 t = Context->getObjcIdType(); // Convert "Class"->"id"
718 ArgTypes.push_back(t);
719 }
Steve Naroffab972d32007-11-04 22:37:50 +0000720 returnType = mDecl->getResultType();
721 } else {
722 returnType = Context->getObjcIdType();
723 }
724 // Get the type, we will need to reference it in a couple spots.
725 QualType msgSendType = MsgSendFunctionDecl->getType();
726
727 // Create a reference to the objc_msgSend() declaration.
728 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
729
730 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
731 // If we don't do this cast, we get the following bizarre warning/note:
732 // xx.m:13: warning: function called through a non-compatible type
733 // xx.m:13: note: if this code is reached, the program will abort
734 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
735 SourceLocation());
736
737 // Now do the "normal" pointer to function cast.
738 QualType castType = Context->getFunctionType(returnType,
739 &ArgTypes[0], ArgTypes.size(),
740 false/*FIXME:variadic*/);
741 castType = Context->getPointerType(castType);
742 cast = new CastExpr(castType, cast, SourceLocation());
743
744 // Don't forget the parens to enforce the proper binding.
745 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
746
747 const FunctionType *FT = msgSendType->getAsFunctionType();
748 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
749 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000750 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000751 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000752
Chris Lattnere64b7772007-10-24 16:57:36 +0000753 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000754 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000755}
756
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000757/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
758/// an objective-c class with ivars.
759void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
760 std::string &Result) {
761 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
762 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000763 // Do not synthesize more than once.
764 if (ObjcSynthesizedStructs.count(CDecl))
765 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000766 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
767 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
768 // Do it for the root
769 SynthesizeObjcInternalStruct(RCDecl, Result);
770 }
771
772 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000773 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000774 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000775 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
776 return;
777
Steve Naroff04960052007-11-01 17:12:31 +0000778 Result += "\nstruct ";
779 Result += CDecl->getName();
780 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
781 Result += " {\n struct ";
782 Result += RCDecl->getName();
783 Result += " _";
784 Result += RCDecl->getName();
785 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000786 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000787 else
788 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000789
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000790 if (NumIvars > 0) {
791 SourceLocation LocStart = CDecl->getLocStart();
792 SourceLocation LocEnd = CDecl->getLocEnd();
793
794 const char *startBuf = SM->getCharacterData(LocStart);
795 const char *endBuf = SM->getCharacterData(LocEnd);
796 startBuf = strchr(startBuf, '{');
797 assert((startBuf && endBuf)
798 && "SynthesizeObjcInternalStruct - malformed @interface");
799 startBuf++; // past '{'
800 while (startBuf < endBuf) {
801 if (*startBuf == '@') {
802 startBuf = strchr(startBuf, 'p');
803 // FIXME: presence of @public, etc. inside comment results in
804 // this transformation as well, which is still correct c-code.
805 if (!strncmp(startBuf, "public", strlen("public"))) {
806 startBuf += strlen("public");
807 Result += "/* @public */";
808 }
809 else if (!strncmp(startBuf, "private", strlen("private"))) {
810 startBuf += strlen("private");
811 Result += "/* @private */";
812 }
813 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
814 startBuf += strlen("protected");
815 Result += "/* @protected */";
816 }
817 }
818 Result += *startBuf++;
819 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000820 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000821
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000822 Result += "};\n";
823 // Mark this struct as having been generated.
824 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000825 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000826}
827
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000828// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
829/// class methods.
830void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
831 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000832 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000833 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000834 const char *ClassName,
835 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000836 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000837 if (NumMethods > 0 && !objc_impl_method) {
838 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000839 SEL _cmd;
840 char *method_types;
841 void *_imp;
842 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000843 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000844 Result += "\nstruct _objc_method {\n";
845 Result += "\tSEL _cmd;\n";
846 Result += "\tchar *method_types;\n";
847 Result += "\tvoid *_imp;\n";
848 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000849
850 /* struct _objc_method_list {
851 struct _objc_method_list *next_method;
852 int method_count;
853 struct _objc_method method_list[];
854 }
855 */
856 Result += "\nstruct _objc_method_list {\n";
857 Result += "\tstruct _objc_method_list *next_method;\n";
858 Result += "\tint method_count;\n";
859 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000860 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000861 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000862 // Build _objc_method_list for class's methods if needed
863 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000864 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +0000865 Result += prefix;
866 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
867 Result += "_METHODS_";
868 Result += ClassName;
869 Result += " __attribute__ ((section (\"__OBJC, __";
870 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000871 Result += "_meth\")))= ";
872 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
873
874 Result += "\t,{{(SEL)\"";
875 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000876 std::string MethodTypeString;
877 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
878 Result += "\", \"";
879 Result += MethodTypeString;
880 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000881 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000882 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000883 Result += "\t ,{(SEL)\"";
884 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000885 std::string MethodTypeString;
886 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
887 Result += "\", \"";
888 Result += MethodTypeString;
889 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000890 }
891 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000892 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000893}
894
895/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
896void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
897 int NumProtocols,
898 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000899 const char *ClassName,
900 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000901 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000902 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000903 for (int i = 0; i < NumProtocols; i++) {
904 ObjcProtocolDecl *PDecl = Protocols[i];
905 // Output struct protocol_methods holder of method selector and type.
906 if (!objc_protocol_methods &&
907 (PDecl->getNumInstanceMethods() > 0
908 || PDecl->getNumClassMethods() > 0)) {
909 /* struct protocol_methods {
910 SEL _cmd;
911 char *method_types;
912 }
913 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000914 Result += "\nstruct protocol_methods {\n";
915 Result += "\tSEL _cmd;\n";
916 Result += "\tchar *method_types;\n";
917 Result += "};\n";
918
919 /* struct _objc_protocol_method_list {
920 int protocol_method_count;
921 struct protocol_methods protocols[];
922 }
923 */
924 Result += "\nstruct _objc_protocol_method_list {\n";
925 Result += "\tint protocol_method_count;\n";
926 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000927 objc_protocol_methods = true;
928 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000929
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000930 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000931 int NumMethods = PDecl->getNumInstanceMethods();
932 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000933 Result += "\nstatic struct _objc_protocol_method_list "
934 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
935 Result += PDecl->getName();
936 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
937 "{\n\t" + utostr(NumMethods) + "\n";
938
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000939 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000940 Result += "\t,{{(SEL)\"";
941 Result += Methods[0]->getSelector().getName().c_str();
942 Result += "\", \"\"}\n";
943
944 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000945 Result += "\t ,{(SEL)\"";
946 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000947 std::string MethodTypeString;
948 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
949 Result += "\", \"";
950 Result += MethodTypeString;
951 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000952 }
953 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000954 }
955
956 // Output class methods declared in this protocol.
957 NumMethods = PDecl->getNumClassMethods();
958 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000959 Result += "\nstatic struct _objc_protocol_method_list "
960 "_OBJC_PROTOCOL_CLASS_METHODS_";
961 Result += PDecl->getName();
962 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
963 "{\n\t";
964 Result += utostr(NumMethods);
965 Result += "\n";
966
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000967 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000968 Result += "\t,{{(SEL)\"";
969 Result += Methods[0]->getSelector().getName().c_str();
970 Result += "\", \"\"}\n";
971
972 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000973 Result += "\t ,{(SEL)\"";
974 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000975 std::string MethodTypeString;
976 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
977 Result += "\", \"";
978 Result += MethodTypeString;
979 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000980 }
981 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000982 }
983 // Output:
984 /* struct _objc_protocol {
985 // Objective-C 1.0 extensions
986 struct _objc_protocol_extension *isa;
987 char *protocol_name;
988 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000989 struct _objc_protocol_method_list *instance_methods;
990 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000991 };
992 */
993 static bool objc_protocol = false;
994 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000995 Result += "\nstruct _objc_protocol {\n";
996 Result += "\tstruct _objc_protocol_extension *isa;\n";
997 Result += "\tchar *protocol_name;\n";
998 Result += "\tstruct _objc_protocol **protocol_list;\n";
999 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1000 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1001 Result += "};\n";
1002
1003 /* struct _objc_protocol_list {
1004 struct _objc_protocol_list *next;
1005 int protocol_count;
1006 struct _objc_protocol *class_protocols[];
1007 }
1008 */
1009 Result += "\nstruct _objc_protocol_list {\n";
1010 Result += "\tstruct _objc_protocol_list *next;\n";
1011 Result += "\tint protocol_count;\n";
1012 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1013 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001014 objc_protocol = true;
1015 }
1016
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001017 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1018 Result += PDecl->getName();
1019 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1020 "{\n\t0, \"";
1021 Result += PDecl->getName();
1022 Result += "\", 0, ";
1023 if (PDecl->getInstanceMethods() > 0) {
1024 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1025 Result += PDecl->getName();
1026 Result += ", ";
1027 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001028 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001029 Result += "0, ";
1030 if (PDecl->getClassMethods() > 0) {
1031 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1032 Result += PDecl->getName();
1033 Result += "\n";
1034 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001035 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001036 Result += "0\n";
1037 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001038 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001039 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001040 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1041 Result += prefix;
1042 Result += "_PROTOCOLS_";
1043 Result += ClassName;
1044 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1045 "{\n\t0, ";
1046 Result += utostr(NumProtocols);
1047 Result += "\n";
1048
1049 Result += "\t,{&_OBJC_PROTOCOL_";
1050 Result += Protocols[0]->getName();
1051 Result += " \n";
1052
1053 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001054 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001055 Result += "\t ,&_OBJC_PROTOCOL_";
1056 Result += PDecl->getName();
1057 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001058 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001059 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001060 }
1061}
1062
1063/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1064/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001065void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1066 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001067 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1068 // Find category declaration for this implementation.
1069 ObjcCategoryDecl *CDecl;
1070 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1071 CDecl = CDecl->getNextClassCategory())
1072 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1073 break;
1074 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1075
1076 char *FullCategoryName = (char*)alloca(
1077 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1078 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1079
1080 // Build _objc_method_list for class's instance methods if needed
1081 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1082 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001083 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001084 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001085
1086 // Build _objc_method_list for class's class methods if needed
1087 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1088 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001089 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001090 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001091
1092 // Protocols referenced in class declaration?
1093 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1094 CDecl->getNumReferencedProtocols(),
1095 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001096 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001097
1098 /* struct _objc_category {
1099 char *category_name;
1100 char *class_name;
1101 struct _objc_method_list *instance_methods;
1102 struct _objc_method_list *class_methods;
1103 struct _objc_protocol_list *protocols;
1104 // Objective-C 1.0 extensions
1105 uint32_t size; // sizeof (struct _objc_category)
1106 struct _objc_property_list *instance_properties; // category's own
1107 // @property decl.
1108 };
1109 */
1110
1111 static bool objc_category = false;
1112 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001113 Result += "\nstruct _objc_category {\n";
1114 Result += "\tchar *category_name;\n";
1115 Result += "\tchar *class_name;\n";
1116 Result += "\tstruct _objc_method_list *instance_methods;\n";
1117 Result += "\tstruct _objc_method_list *class_methods;\n";
1118 Result += "\tstruct _objc_protocol_list *protocols;\n";
1119 Result += "\tunsigned int size;\n";
1120 Result += "\tstruct _objc_property_list *instance_properties;\n";
1121 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001122 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001123 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001124 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1125 Result += FullCategoryName;
1126 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1127 Result += IDecl->getName();
1128 Result += "\"\n\t, \"";
1129 Result += ClassDecl->getName();
1130 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001131
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001132 if (IDecl->getNumInstanceMethods() > 0) {
1133 Result += "\t, (struct _objc_method_list *)"
1134 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1135 Result += FullCategoryName;
1136 Result += "\n";
1137 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001138 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001139 Result += "\t, 0\n";
1140 if (IDecl->getNumClassMethods() > 0) {
1141 Result += "\t, (struct _objc_method_list *)"
1142 "&_OBJC_CATEGORY_CLASS_METHODS_";
1143 Result += FullCategoryName;
1144 Result += "\n";
1145 }
1146 else
1147 Result += "\t, 0\n";
1148
1149 if (CDecl->getNumReferencedProtocols() > 0) {
1150 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1151 Result += FullCategoryName;
1152 Result += "\n";
1153 }
1154 else
1155 Result += "\t, 0\n";
1156 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001157}
1158
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001159/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1160/// ivar offset.
1161void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1162 ObjcIvarDecl *ivar,
1163 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001164 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001165 Result += IDecl->getName();
1166 Result += ", ";
1167 Result += ivar->getName();
1168 Result += ")";
1169}
1170
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001171//===----------------------------------------------------------------------===//
1172// Meta Data Emission
1173//===----------------------------------------------------------------------===//
1174
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001175void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1176 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001177 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1178
1179 // Build _objc_ivar_list metadata for classes ivars if needed
1180 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1181 ? IDecl->getImplDeclNumIvars()
1182 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1183
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001184 SynthesizeObjcInternalStruct(CDecl, Result);
1185
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001186 if (NumIvars > 0) {
1187 static bool objc_ivar = false;
1188 if (!objc_ivar) {
1189 /* struct _objc_ivar {
1190 char *ivar_name;
1191 char *ivar_type;
1192 int ivar_offset;
1193 };
1194 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001195 Result += "\nstruct _objc_ivar {\n";
1196 Result += "\tchar *ivar_name;\n";
1197 Result += "\tchar *ivar_type;\n";
1198 Result += "\tint ivar_offset;\n";
1199 Result += "};\n";
1200
1201 /* struct _objc_ivar_list {
1202 int ivar_count;
1203 struct _objc_ivar ivar_list[];
1204 };
1205 */
1206 Result += "\nstruct _objc_ivar_list {\n";
1207 Result += "\tint ivar_count;\n";
1208 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001209 objc_ivar = true;
1210 }
1211
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001212 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1213 Result += IDecl->getName();
1214 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1215 "{\n\t";
1216 Result += utostr(NumIvars);
1217 Result += "\n";
1218
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001219 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1220 ? IDecl->getImplDeclIVars()
1221 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001222 Result += "\t,{{\"";
1223 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001224 Result += "\", \"";
1225 std::string StrEncoding;
1226 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1227 Result += StrEncoding;
1228 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001229 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1230 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001231 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001232 Result += "\t ,{\"";
1233 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001234 Result += "\", \"";
1235 std::string StrEncoding;
1236 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1237 Result += StrEncoding;
1238 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001239 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1240 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001241 }
1242
1243 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001244 }
1245
1246 // Build _objc_method_list for class's instance methods if needed
1247 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1248 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001249 true,
1250 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001251
1252 // Build _objc_method_list for class's class methods if needed
1253 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001254 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001255 false,
1256 "", IDecl->getName(), Result);
1257
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001258 // Protocols referenced in class declaration?
1259 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1260 CDecl->getNumIntfRefProtocols(),
1261 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001262 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001263
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001264
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001265 // Declaration of class/meta-class metadata
1266 /* struct _objc_class {
1267 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001268 const char *super_class_name;
1269 char *name;
1270 long version;
1271 long info;
1272 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001273 struct _objc_ivar_list *ivars;
1274 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001275 struct objc_cache *cache;
1276 struct objc_protocol_list *protocols;
1277 const char *ivar_layout;
1278 struct _objc_class_ext *ext;
1279 };
1280 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001281 static bool objc_class = false;
1282 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001283 Result += "\nstruct _objc_class {\n";
1284 Result += "\tstruct _objc_class *isa;\n";
1285 Result += "\tconst char *super_class_name;\n";
1286 Result += "\tchar *name;\n";
1287 Result += "\tlong version;\n";
1288 Result += "\tlong info;\n";
1289 Result += "\tlong instance_size;\n";
1290 Result += "\tstruct _objc_ivar_list *ivars;\n";
1291 Result += "\tstruct _objc_method_list *methods;\n";
1292 Result += "\tstruct objc_cache *cache;\n";
1293 Result += "\tstruct _objc_protocol_list *protocols;\n";
1294 Result += "\tconst char *ivar_layout;\n";
1295 Result += "\tstruct _objc_class_ext *ext;\n";
1296 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001297 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001298 }
1299
1300 // Meta-class metadata generation.
1301 ObjcInterfaceDecl *RootClass = 0;
1302 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1303 while (SuperClass) {
1304 RootClass = SuperClass;
1305 SuperClass = SuperClass->getSuperClass();
1306 }
1307 SuperClass = CDecl->getSuperClass();
1308
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001309 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1310 Result += CDecl->getName();
1311 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1312 "{\n\t(struct _objc_class *)\"";
1313 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1314 Result += "\"";
1315
1316 if (SuperClass) {
1317 Result += ", \"";
1318 Result += SuperClass->getName();
1319 Result += "\", \"";
1320 Result += CDecl->getName();
1321 Result += "\"";
1322 }
1323 else {
1324 Result += ", 0, \"";
1325 Result += CDecl->getName();
1326 Result += "\"";
1327 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001328 // TODO: 'ivars' field for root class is currently set to 0.
1329 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001330 Result += ", 0,2, sizeof(struct _objc_class), 0";
1331 if (CDecl->getNumClassMethods() > 0) {
1332 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1333 Result += CDecl->getName();
1334 Result += "\n";
1335 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001336 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001337 Result += ", 0\n";
1338 if (CDecl->getNumIntfRefProtocols() > 0) {
1339 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1340 Result += CDecl->getName();
1341 Result += ",0,0\n";
1342 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001343 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001344 Result += "\t,0,0,0,0\n";
1345 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001346
1347 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001348 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1349 Result += CDecl->getName();
1350 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1351 "{\n\t&_OBJC_METACLASS_";
1352 Result += CDecl->getName();
1353 if (SuperClass) {
1354 Result += ", \"";
1355 Result += SuperClass->getName();
1356 Result += "\", \"";
1357 Result += CDecl->getName();
1358 Result += "\"";
1359 }
1360 else {
1361 Result += ", 0, \"";
1362 Result += CDecl->getName();
1363 Result += "\"";
1364 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001365 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001366 Result += ", 0,1";
1367 if (!ObjcSynthesizedStructs.count(CDecl))
1368 Result += ",0";
1369 else {
1370 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001371 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001372 Result += CDecl->getName();
1373 Result += ")";
1374 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001375 if (NumIvars > 0) {
1376 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1377 Result += CDecl->getName();
1378 Result += "\n\t";
1379 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001380 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001381 Result += ",0";
1382 if (IDecl->getNumInstanceMethods() > 0) {
1383 Result += ", &_OBJC_INSTANCE_METHODS_";
1384 Result += CDecl->getName();
1385 Result += ", 0\n\t";
1386 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001387 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001388 Result += ",0,0";
1389 if (CDecl->getNumIntfRefProtocols() > 0) {
1390 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1391 Result += CDecl->getName();
1392 Result += ", 0,0\n";
1393 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001394 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001395 Result += ",0,0,0\n";
1396 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001397}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001398
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001399void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001400 int ClsDefCount = ClassImplementation.size();
1401 int CatDefCount = CategoryImplementation.size();
1402 if (ClsDefCount == 0 && CatDefCount == 0)
1403 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001404
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001405 // TODO: This is temporary until we decide how to access objc types in a
1406 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001407 Result += "#include <Objc/objc.h>\n";
1408 // This is needed for use of offsetof
1409 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001410
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001411 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001412 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001413 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001414
1415 // For each implemented category, write out all its meta data.
1416 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001417 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001418
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001419 // Write objc_symtab metadata
1420 /*
1421 struct _objc_symtab
1422 {
1423 long sel_ref_cnt;
1424 SEL *refs;
1425 short cls_def_cnt;
1426 short cat_def_cnt;
1427 void *defs[cls_def_cnt + cat_def_cnt];
1428 };
1429 */
1430
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001431 Result += "\nstruct _objc_symtab {\n";
1432 Result += "\tlong sel_ref_cnt;\n";
1433 Result += "\tSEL *refs;\n";
1434 Result += "\tshort cls_def_cnt;\n";
1435 Result += "\tshort cat_def_cnt;\n";
1436 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1437 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001438
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001439 Result += "static struct _objc_symtab "
1440 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1441 Result += "\t0, 0, " + utostr(ClsDefCount)
1442 + ", " + utostr(CatDefCount) + "\n";
1443 for (int i = 0; i < ClsDefCount; i++) {
1444 Result += "\t,&_OBJC_CLASS_";
1445 Result += ClassImplementation[i]->getName();
1446 Result += "\n";
1447 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001448
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001449 for (int i = 0; i < CatDefCount; i++) {
1450 Result += "\t,&_OBJC_CATEGORY_";
1451 Result += CategoryImplementation[i]->getClassInterface()->getName();
1452 Result += "_";
1453 Result += CategoryImplementation[i]->getName();
1454 Result += "\n";
1455 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001456
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001457 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001458
1459 // Write objc_module metadata
1460
1461 /*
1462 struct _objc_module {
1463 long version;
1464 long size;
1465 const char *name;
1466 struct _objc_symtab *symtab;
1467 }
1468 */
1469
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001470 Result += "\nstruct _objc_module {\n";
1471 Result += "\tlong version;\n";
1472 Result += "\tlong size;\n";
1473 Result += "\tconst char *name;\n";
1474 Result += "\tstruct _objc_symtab *symtab;\n";
1475 Result += "};\n\n";
1476 Result += "static struct _objc_module "
1477 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001478 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1479 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001480 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001481}
Chris Lattner311ff022007-10-16 22:36:42 +00001482