blob: e253ae8242527560896609eaa02370ab1ca6a364 [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);
Steve Naroff09b266e2007-10-30 23:14:51 +000083 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000084 void RewriteObjcQualifiedInterfaceTypes(
85 const FunctionTypeProto *proto, FunctionDecl *FD);
86 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000087
Chris Lattnerf04da132007-10-24 17:06:59 +000088 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000089 Stmt *RewriteFunctionBody(Stmt *S);
90 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +000091 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +000092 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +000093 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Steve Naroff934f2762007-10-24 22:48:43 +000094 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
95 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +000096 void SynthMsgSendFunctionDecl();
97 void SynthGetClassFunctionDecl();
98
Chris Lattnerf04da132007-10-24 17:06:59 +000099 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000100 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
101 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000102
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000103 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
104 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000105
106 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
107 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000108 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000109 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000110 const char *ClassName,
111 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000112
113 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
114 int NumProtocols,
115 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000116 const char *ClassName,
117 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000118 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
119 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000120 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
121 ObjcIvarDecl *ivar,
122 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000123 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000124 };
125}
126
Chris Lattner8a12c272007-10-11 18:38:32 +0000127ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000128
Chris Lattnerf04da132007-10-24 17:06:59 +0000129//===----------------------------------------------------------------------===//
130// Top Level Driver Code
131//===----------------------------------------------------------------------===//
132
Chris Lattner8a12c272007-10-11 18:38:32 +0000133void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000134 // Two cases: either the decl could be in the main file, or it could be in a
135 // #included file. If the former, rewrite it now. If the later, check to see
136 // if we rewrote the #include/#import.
137 SourceLocation Loc = D->getLocation();
138 Loc = SM->getLogicalLoc(Loc);
139
140 // If this is for a builtin, ignore it.
141 if (Loc.isInvalid()) return;
142
Steve Naroffebf2b562007-10-23 23:50:29 +0000143 // Look for built-in declarations that we need to refer during the rewrite.
144 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000145 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000146 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
147 // declared in <Foundation/NSString.h>
148 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
149 ConstantStringClassReference = FVD;
150 return;
151 }
Steve Naroffbef11852007-10-26 20:53:56 +0000152 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
153 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000154 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
155 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000156 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
157 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000158 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000159 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000160 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
161 return HandleDeclInMainFile(D);
162
Chris Lattnerf04da132007-10-24 17:06:59 +0000163 // Otherwise, see if there is a #import in the main file that should be
164 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000165 RewriteInclude(Loc);
166}
167
Chris Lattnerf04da132007-10-24 17:06:59 +0000168/// HandleDeclInMainFile - This is called for each top-level decl defined in the
169/// main file of the input.
170void RewriteTest::HandleDeclInMainFile(Decl *D) {
171 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
172 if (Stmt *Body = FD->getBody())
173 FD->setBody(RewriteFunctionBody(Body));
174
175 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
176 ClassImplementation.push_back(CI);
177 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
178 CategoryImplementation.push_back(CI);
179 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
180 RewriteForwardClassDecl(CD);
181 // Nothing yet.
182}
183
184RewriteTest::~RewriteTest() {
185 // Get the top-level buffer that this corresponds to.
186 RewriteTabs();
187
188 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
189 // we are done.
190 if (const RewriteBuffer *RewriteBuf =
191 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000192 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000193 std::string S(RewriteBuf->begin(), RewriteBuf->end());
194 printf("%s\n", S.c_str());
195 } else {
196 printf("No changes\n");
197 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000198
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 Naroff352336b2007-11-05 14:36:37 +0000280 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000281 typedefString += ForwardDecl->getName();
282 typedefString += ";\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000283
284 // Mark this typedef as having been generated.
285 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000286 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000287 }
288
289 // Replace the @class with typedefs corresponding to the classes.
290 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
291 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000292}
293
Steve Naroff423cb562007-10-30 13:30:57 +0000294void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
295 for (int i = 0; i < nMethods; i++) {
296 ObjcMethodDecl *Method = Methods[i];
297 SourceLocation Loc = Method->getLocStart();
298
299 Rewrite.ReplaceText(Loc, 0, "// ", 3);
300
301 // FIXME: handle methods that are declared across multiple lines.
302 }
303}
304
305void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
306 SourceLocation LocStart = CatDecl->getLocStart();
307
308 // FIXME: handle category headers that are declared across multiple lines.
309 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
310
311 RewriteMethods(CatDecl->getNumInstanceMethods(),
312 CatDecl->getInstanceMethods());
313 RewriteMethods(CatDecl->getNumClassMethods(),
314 CatDecl->getClassMethods());
315 // Lastly, comment out the @end.
316 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
317}
318
Steve Naroff752d6ef2007-10-30 16:42:30 +0000319void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
320 SourceLocation LocStart = PDecl->getLocStart();
321
322 // FIXME: handle protocol headers that are declared across multiple lines.
323 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
324
325 RewriteMethods(PDecl->getNumInstanceMethods(),
326 PDecl->getInstanceMethods());
327 RewriteMethods(PDecl->getNumClassMethods(),
328 PDecl->getClassMethods());
329 // Lastly, comment out the @end.
330 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
331}
332
Steve Naroffbef11852007-10-26 20:53:56 +0000333void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000334
335 SourceLocation LocStart = ClassDecl->getLocStart();
336 SourceLocation LocEnd = ClassDecl->getLocEnd();
337
338 const char *startBuf = SM->getCharacterData(LocStart);
339 const char *endBuf = SM->getCharacterData(LocEnd);
340
Steve Naroff2feac5e2007-10-30 03:43:13 +0000341 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000342
343 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000344 if (!ObjcForwardDecls.count(ClassDecl)) {
345 // we haven't seen a forward decl - generate a typedef.
Steve Naroff352336b2007-11-05 14:36:37 +0000346 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000347 ResultStr += ClassDecl->getName();
348 ResultStr += ";";
349
350 // Mark this typedef as having been generated.
351 ObjcForwardDecls.insert(ClassDecl);
352 }
Steve Narofff908a872007-10-30 02:23:23 +0000353 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
354
Steve Naroff2feac5e2007-10-30 03:43:13 +0000355 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000356 ResultStr.c_str(), ResultStr.size());
357
Steve Naroff423cb562007-10-30 13:30:57 +0000358 RewriteMethods(ClassDecl->getNumInstanceMethods(),
359 ClassDecl->getInstanceMethods());
360 RewriteMethods(ClassDecl->getNumClassMethods(),
361 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000362
Steve Naroff2feac5e2007-10-30 03:43:13 +0000363 // Lastly, comment out the @end.
364 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000365}
366
Chris Lattnerf04da132007-10-24 17:06:59 +0000367//===----------------------------------------------------------------------===//
368// Function Body / Expression rewriting
369//===----------------------------------------------------------------------===//
370
Chris Lattnere64b7772007-10-24 16:57:36 +0000371Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000372 // Otherwise, just rewrite all children.
373 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
374 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000375 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000376 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000377
378 // Handle specific things.
379 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
380 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000381
382 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
383 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000384
385 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
386 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000387
Steve Naroff934f2762007-10-24 22:48:43 +0000388 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
389 // Before we rewrite it, put the original message expression in a comment.
390 SourceLocation startLoc = MessExpr->getLocStart();
391 SourceLocation endLoc = MessExpr->getLocEnd();
392
393 const char *startBuf = SM->getCharacterData(startLoc);
394 const char *endBuf = SM->getCharacterData(endLoc);
395
396 std::string messString;
397 messString += "// ";
398 messString.append(startBuf, endBuf-startBuf+1);
399 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000400
Steve Naroff934f2762007-10-24 22:48:43 +0000401 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
402 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
403 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000404 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000405 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000406 }
Chris Lattnere64b7772007-10-24 16:57:36 +0000407 // Return this stmt unmodified.
408 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000409}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000410
Chris Lattnere64b7772007-10-24 16:57:36 +0000411Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000412 // Create a new string expression.
413 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000414 std::string StrEncoding;
415 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
416 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
417 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000418 SourceLocation(), SourceLocation());
419 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000420 delete Exp;
421 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000422}
423
Steve Naroffb42f8412007-11-05 14:50:49 +0000424Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
425 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
426 // Create a call to sel_registerName("selName").
427 llvm::SmallVector<Expr*, 8> SelExprs;
428 QualType argType = Context->getPointerType(Context->CharTy);
429 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
430 Exp->getSelector().getName().size(),
431 false, argType, SourceLocation(),
432 SourceLocation()));
433 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
434 &SelExprs[0], SelExprs.size());
435 Rewrite.ReplaceStmt(Exp, SelExp);
436 delete Exp;
437 return SelExp;
438}
439
Steve Naroff934f2762007-10-24 22:48:43 +0000440CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
441 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000442 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000443 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000444
445 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000446 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000447
448 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000449 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000450 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
451
452 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000453
Steve Naroff934f2762007-10-24 22:48:43 +0000454 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
455}
456
Steve Naroffd5255f52007-11-01 13:24:47 +0000457static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
458 const char *&startRef, const char *&endRef) {
459 while (startBuf < endBuf) {
460 if (*startBuf == '<')
461 startRef = startBuf; // mark the start.
462 if (*startBuf == '>') {
463 assert((startRef && *startRef == '<') && "rewrite scanning error");
464 endRef = startBuf; // mark the end.
465 return true;
466 }
467 startBuf++;
468 }
469 return false;
470}
471
472bool RewriteTest::needToScanForQualifiers(QualType T) {
473 // FIXME: we don't currently represent "id <Protocol>" in the type system.
474 if (T == Context->getObjcIdType())
475 return true;
476
477 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000478 Type *pointeeType = pType->getPointeeType().getTypePtr();
479 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
480 return true; // we have "Class <Protocol> *".
481 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000482 return false;
483}
484
485void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
486 const FunctionTypeProto *proto, FunctionDecl *FD) {
487
488 if (needToScanForQualifiers(proto->getResultType())) {
489 // Since types are unique, we need to scan the buffer.
490 SourceLocation Loc = FD->getLocation();
491
492 const char *endBuf = SM->getCharacterData(Loc);
493 const char *startBuf = endBuf;
494 while (*startBuf != ';')
495 startBuf--; // scan backward (from the decl location) for return type.
496 const char *startRef = 0, *endRef = 0;
497 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
498 // Get the locations of the startRef, endRef.
499 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
500 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
501 // Comment out the protocol references.
502 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
503 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000504 }
505 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000506 // Now check arguments.
507 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
508 if (needToScanForQualifiers(proto->getArgType(i))) {
509 // Since types are unique, we need to scan the buffer.
510 SourceLocation Loc = FD->getLocation();
511
512 const char *startBuf = SM->getCharacterData(Loc);
513 const char *endBuf = startBuf;
514 while (*endBuf != ';')
515 endBuf++; // scan forward (from the decl location) for argument types.
516 const char *startRef = 0, *endRef = 0;
517 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
518 // Get the locations of the startRef, endRef.
519 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
520 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
521 // Comment out the protocol references.
522 Rewrite.ReplaceText(LessLoc, 0, "/*", 2);
523 Rewrite.ReplaceText(GreaterLoc, 0, "*/", 2);
524 }
525 }
526 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000527}
528
Steve Naroff09b266e2007-10-30 23:14:51 +0000529void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
530 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000531 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000532 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000533 return;
534 }
535 // Check for ObjC 'id' and class types that have been adorned with protocol
536 // information (id<p>, C<p>*). The protocol references need to be rewritten!
537 const FunctionType *funcType = FD->getType()->getAsFunctionType();
538 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000539 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
540 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000541}
542
543// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
544void RewriteTest::SynthMsgSendFunctionDecl() {
545 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
546 llvm::SmallVector<QualType, 16> ArgTys;
547 QualType argT = Context->getObjcIdType();
548 assert(!argT.isNull() && "Can't find 'id' type");
549 ArgTys.push_back(argT);
550 argT = Context->getObjcSelType();
551 assert(!argT.isNull() && "Can't find 'SEL' type");
552 ArgTys.push_back(argT);
553 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
554 &ArgTys[0], ArgTys.size(),
555 true /*isVariadic*/);
556 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
557 msgSendIdent, msgSendType,
558 FunctionDecl::Extern, false, 0);
559}
560
561// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
562void RewriteTest::SynthGetClassFunctionDecl() {
563 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
564 llvm::SmallVector<QualType, 16> ArgTys;
565 ArgTys.push_back(Context->getPointerType(
566 Context->CharTy.getQualifiedType(QualType::Const)));
567 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
568 &ArgTys[0], ArgTys.size(),
569 false /*isVariadic*/);
570 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
571 getClassIdent, getClassType,
572 FunctionDecl::Extern, false, 0);
573}
574
Steve Naroffbeaf2992007-11-03 11:27:19 +0000575Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
576 assert(ConstantStringClassReference && "Can't find constant string reference");
577 llvm::SmallVector<Expr*, 4> InitExprs;
578
579 // Synthesize "(Class)&_NSConstantStringClassReference"
580 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
581 ConstantStringClassReference->getType(),
582 SourceLocation());
583 QualType expType = Context->getPointerType(ClsRef->getType());
584 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
585 expType, SourceLocation());
586 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
587 SourceLocation());
588 InitExprs.push_back(cast); // set the 'isa'.
589 InitExprs.push_back(Exp->getString()); // set "char *bytes".
590 unsigned IntSize = static_cast<unsigned>(
591 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
592 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
593 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
594 Exp->getLocStart());
595 InitExprs.push_back(len); // set "int numBytes".
596
597 // struct NSConstantString
598 QualType CFConstantStrType = Context->getCFConstantStringType();
599 // (struct NSConstantString) { <exprs from above> }
600 InitListExpr *ILE = new InitListExpr(SourceLocation(),
601 &InitExprs[0], InitExprs.size(),
602 SourceLocation());
603 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
604 // struct NSConstantString *
605 expType = Context->getPointerType(StrRep->getType());
606 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
607 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000608 // cast to NSConstantString *
609 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000610 Rewrite.ReplaceStmt(Exp, cast);
611 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000612 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +0000613}
614
Steve Naroff934f2762007-10-24 22:48:43 +0000615Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000616 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000617 if (!MsgSendFunctionDecl)
618 SynthMsgSendFunctionDecl();
619 if (!GetClassFunctionDecl)
620 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000621
622 // Synthesize a call to objc_msgSend().
623 llvm::SmallVector<Expr*, 8> MsgExprs;
624 IdentifierInfo *clsName = Exp->getClassName();
625
626 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
627 if (clsName) { // class message.
628 llvm::SmallVector<Expr*, 8> ClsExprs;
629 QualType argType = Context->getPointerType(Context->CharTy);
630 ClsExprs.push_back(new StringLiteral(clsName->getName(),
631 clsName->getLength(),
632 false, argType, SourceLocation(),
633 SourceLocation()));
634 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
635 &ClsExprs[0], ClsExprs.size());
636 MsgExprs.push_back(Cls);
637 } else // instance message.
638 MsgExprs.push_back(Exp->getReceiver());
639
Steve Naroffbeaf2992007-11-03 11:27:19 +0000640 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000641 llvm::SmallVector<Expr*, 8> SelExprs;
642 QualType argType = Context->getPointerType(Context->CharTy);
643 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
644 Exp->getSelector().getName().size(),
645 false, argType, SourceLocation(),
646 SourceLocation()));
647 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
648 &SelExprs[0], SelExprs.size());
649 MsgExprs.push_back(SelExp);
650
651 // Now push any user supplied arguments.
652 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
653 MsgExprs.push_back(Exp->getArg(i));
654 // We've transferred the ownership to MsgExprs. Null out the argument in
655 // the original expression, since we will delete it below.
656 Exp->setArg(i, 0);
657 }
Steve Naroffab972d32007-11-04 22:37:50 +0000658 // Generate the funky cast.
659 CastExpr *cast;
660 llvm::SmallVector<QualType, 8> ArgTypes;
661 QualType returnType;
662
663 // Push 'id' and 'SEL', the 2 implicit arguments.
664 ArgTypes.push_back(Context->getObjcIdType());
665 ArgTypes.push_back(Context->getObjcSelType());
666 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
667 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +0000668 for (int i = 0; i < mDecl->getNumParams(); i++) {
669 QualType t = mDecl->getParamDecl(i)->getType();
670 if (t == Context->getObjcClassType())
671 t = Context->getObjcIdType(); // Convert "Class"->"id"
672 ArgTypes.push_back(t);
673 }
Steve Naroffab972d32007-11-04 22:37:50 +0000674 returnType = mDecl->getResultType();
675 } else {
676 returnType = Context->getObjcIdType();
677 }
678 // Get the type, we will need to reference it in a couple spots.
679 QualType msgSendType = MsgSendFunctionDecl->getType();
680
681 // Create a reference to the objc_msgSend() declaration.
682 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
683
684 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
685 // If we don't do this cast, we get the following bizarre warning/note:
686 // xx.m:13: warning: function called through a non-compatible type
687 // xx.m:13: note: if this code is reached, the program will abort
688 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
689 SourceLocation());
690
691 // Now do the "normal" pointer to function cast.
692 QualType castType = Context->getFunctionType(returnType,
693 &ArgTypes[0], ArgTypes.size(),
694 false/*FIXME:variadic*/);
695 castType = Context->getPointerType(castType);
696 cast = new CastExpr(castType, cast, SourceLocation());
697
698 // Don't forget the parens to enforce the proper binding.
699 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
700
701 const FunctionType *FT = msgSendType->getAsFunctionType();
702 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
703 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000704 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000705 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000706
Chris Lattnere64b7772007-10-24 16:57:36 +0000707 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000708 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000709}
710
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000711/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
712/// an objective-c class with ivars.
713void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
714 std::string &Result) {
715 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
716 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000717 // Do not synthesize more than once.
718 if (ObjcSynthesizedStructs.count(CDecl))
719 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000720 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
721 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
722 // Do it for the root
723 SynthesizeObjcInternalStruct(RCDecl, Result);
724 }
725
726 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000727 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000728 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000729 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
730 return;
731
Steve Naroff04960052007-11-01 17:12:31 +0000732 Result += "\nstruct ";
733 Result += CDecl->getName();
734 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
735 Result += " {\n struct ";
736 Result += RCDecl->getName();
737 Result += " _";
738 Result += RCDecl->getName();
739 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000740 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000741 else
742 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +0000743
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000744 if (NumIvars > 0) {
745 SourceLocation LocStart = CDecl->getLocStart();
746 SourceLocation LocEnd = CDecl->getLocEnd();
747
748 const char *startBuf = SM->getCharacterData(LocStart);
749 const char *endBuf = SM->getCharacterData(LocEnd);
750 startBuf = strchr(startBuf, '{');
751 assert((startBuf && endBuf)
752 && "SynthesizeObjcInternalStruct - malformed @interface");
753 startBuf++; // past '{'
754 while (startBuf < endBuf) {
755 if (*startBuf == '@') {
756 startBuf = strchr(startBuf, 'p');
757 // FIXME: presence of @public, etc. inside comment results in
758 // this transformation as well, which is still correct c-code.
759 if (!strncmp(startBuf, "public", strlen("public"))) {
760 startBuf += strlen("public");
761 Result += "/* @public */";
762 }
763 else if (!strncmp(startBuf, "private", strlen("private"))) {
764 startBuf += strlen("private");
765 Result += "/* @private */";
766 }
767 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
768 startBuf += strlen("protected");
769 Result += "/* @protected */";
770 }
771 }
772 Result += *startBuf++;
773 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000774 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000775
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000776 Result += "};\n";
777 // Mark this struct as having been generated.
778 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000779 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000780}
781
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000782// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
783/// class methods.
784void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
785 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000786 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000787 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000788 const char *ClassName,
789 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000790 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000791 if (NumMethods > 0 && !objc_impl_method) {
792 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000793 SEL _cmd;
794 char *method_types;
795 void *_imp;
796 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000797 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000798 Result += "\nstruct _objc_method {\n";
799 Result += "\tSEL _cmd;\n";
800 Result += "\tchar *method_types;\n";
801 Result += "\tvoid *_imp;\n";
802 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000803
804 /* struct _objc_method_list {
805 struct _objc_method_list *next_method;
806 int method_count;
807 struct _objc_method method_list[];
808 }
809 */
810 Result += "\nstruct _objc_method_list {\n";
811 Result += "\tstruct _objc_method_list *next_method;\n";
812 Result += "\tint method_count;\n";
813 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000814 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000815 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000816 // Build _objc_method_list for class's methods if needed
817 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000818 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +0000819 Result += prefix;
820 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
821 Result += "_METHODS_";
822 Result += ClassName;
823 Result += " __attribute__ ((section (\"__OBJC, __";
824 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000825 Result += "_meth\")))= ";
826 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
827
828 Result += "\t,{{(SEL)\"";
829 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000830 std::string MethodTypeString;
831 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
832 Result += "\", \"";
833 Result += MethodTypeString;
834 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000835 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000836 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000837 Result += "\t ,{(SEL)\"";
838 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000839 std::string MethodTypeString;
840 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
841 Result += "\", \"";
842 Result += MethodTypeString;
843 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000844 }
845 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000846 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000847}
848
849/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
850void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
851 int NumProtocols,
852 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000853 const char *ClassName,
854 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000855 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000856 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000857 for (int i = 0; i < NumProtocols; i++) {
858 ObjcProtocolDecl *PDecl = Protocols[i];
859 // Output struct protocol_methods holder of method selector and type.
860 if (!objc_protocol_methods &&
861 (PDecl->getNumInstanceMethods() > 0
862 || PDecl->getNumClassMethods() > 0)) {
863 /* struct protocol_methods {
864 SEL _cmd;
865 char *method_types;
866 }
867 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000868 Result += "\nstruct protocol_methods {\n";
869 Result += "\tSEL _cmd;\n";
870 Result += "\tchar *method_types;\n";
871 Result += "};\n";
872
873 /* struct _objc_protocol_method_list {
874 int protocol_method_count;
875 struct protocol_methods protocols[];
876 }
877 */
878 Result += "\nstruct _objc_protocol_method_list {\n";
879 Result += "\tint protocol_method_count;\n";
880 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000881 objc_protocol_methods = true;
882 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000883
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000884 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000885 int NumMethods = PDecl->getNumInstanceMethods();
886 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000887 Result += "\nstatic struct _objc_protocol_method_list "
888 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
889 Result += PDecl->getName();
890 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
891 "{\n\t" + utostr(NumMethods) + "\n";
892
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000893 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000894 Result += "\t,{{(SEL)\"";
895 Result += Methods[0]->getSelector().getName().c_str();
896 Result += "\", \"\"}\n";
897
898 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000899 Result += "\t ,{(SEL)\"";
900 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000901 std::string MethodTypeString;
902 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
903 Result += "\", \"";
904 Result += MethodTypeString;
905 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000906 }
907 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000908 }
909
910 // Output class methods declared in this protocol.
911 NumMethods = PDecl->getNumClassMethods();
912 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000913 Result += "\nstatic struct _objc_protocol_method_list "
914 "_OBJC_PROTOCOL_CLASS_METHODS_";
915 Result += PDecl->getName();
916 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
917 "{\n\t";
918 Result += utostr(NumMethods);
919 Result += "\n";
920
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000921 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000922 Result += "\t,{{(SEL)\"";
923 Result += Methods[0]->getSelector().getName().c_str();
924 Result += "\", \"\"}\n";
925
926 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000927 Result += "\t ,{(SEL)\"";
928 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000929 std::string MethodTypeString;
930 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
931 Result += "\", \"";
932 Result += MethodTypeString;
933 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000934 }
935 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000936 }
937 // Output:
938 /* struct _objc_protocol {
939 // Objective-C 1.0 extensions
940 struct _objc_protocol_extension *isa;
941 char *protocol_name;
942 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000943 struct _objc_protocol_method_list *instance_methods;
944 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000945 };
946 */
947 static bool objc_protocol = false;
948 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000949 Result += "\nstruct _objc_protocol {\n";
950 Result += "\tstruct _objc_protocol_extension *isa;\n";
951 Result += "\tchar *protocol_name;\n";
952 Result += "\tstruct _objc_protocol **protocol_list;\n";
953 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
954 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
955 Result += "};\n";
956
957 /* struct _objc_protocol_list {
958 struct _objc_protocol_list *next;
959 int protocol_count;
960 struct _objc_protocol *class_protocols[];
961 }
962 */
963 Result += "\nstruct _objc_protocol_list {\n";
964 Result += "\tstruct _objc_protocol_list *next;\n";
965 Result += "\tint protocol_count;\n";
966 Result += "\tstruct _objc_protocol *class_protocols[];\n";
967 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000968 objc_protocol = true;
969 }
970
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000971 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
972 Result += PDecl->getName();
973 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
974 "{\n\t0, \"";
975 Result += PDecl->getName();
976 Result += "\", 0, ";
977 if (PDecl->getInstanceMethods() > 0) {
978 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
979 Result += PDecl->getName();
980 Result += ", ";
981 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000982 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000983 Result += "0, ";
984 if (PDecl->getClassMethods() > 0) {
985 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
986 Result += PDecl->getName();
987 Result += "\n";
988 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000989 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000990 Result += "0\n";
991 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000992 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000993 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000994 Result += "\nstatic struct _objc_protocol_list _OBJC_";
995 Result += prefix;
996 Result += "_PROTOCOLS_";
997 Result += ClassName;
998 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
999 "{\n\t0, ";
1000 Result += utostr(NumProtocols);
1001 Result += "\n";
1002
1003 Result += "\t,{&_OBJC_PROTOCOL_";
1004 Result += Protocols[0]->getName();
1005 Result += " \n";
1006
1007 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001008 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001009 Result += "\t ,&_OBJC_PROTOCOL_";
1010 Result += PDecl->getName();
1011 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001012 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001013 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001014 }
1015}
1016
1017/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1018/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001019void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1020 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001021 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1022 // Find category declaration for this implementation.
1023 ObjcCategoryDecl *CDecl;
1024 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1025 CDecl = CDecl->getNextClassCategory())
1026 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1027 break;
1028 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1029
1030 char *FullCategoryName = (char*)alloca(
1031 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1032 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1033
1034 // Build _objc_method_list for class's instance methods if needed
1035 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1036 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001037 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001038 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001039
1040 // Build _objc_method_list for class's class methods if needed
1041 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1042 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001043 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001044 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001045
1046 // Protocols referenced in class declaration?
1047 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1048 CDecl->getNumReferencedProtocols(),
1049 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001050 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001051
1052 /* struct _objc_category {
1053 char *category_name;
1054 char *class_name;
1055 struct _objc_method_list *instance_methods;
1056 struct _objc_method_list *class_methods;
1057 struct _objc_protocol_list *protocols;
1058 // Objective-C 1.0 extensions
1059 uint32_t size; // sizeof (struct _objc_category)
1060 struct _objc_property_list *instance_properties; // category's own
1061 // @property decl.
1062 };
1063 */
1064
1065 static bool objc_category = false;
1066 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001067 Result += "\nstruct _objc_category {\n";
1068 Result += "\tchar *category_name;\n";
1069 Result += "\tchar *class_name;\n";
1070 Result += "\tstruct _objc_method_list *instance_methods;\n";
1071 Result += "\tstruct _objc_method_list *class_methods;\n";
1072 Result += "\tstruct _objc_protocol_list *protocols;\n";
1073 Result += "\tunsigned int size;\n";
1074 Result += "\tstruct _objc_property_list *instance_properties;\n";
1075 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001076 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001077 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001078 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1079 Result += FullCategoryName;
1080 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1081 Result += IDecl->getName();
1082 Result += "\"\n\t, \"";
1083 Result += ClassDecl->getName();
1084 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001085
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001086 if (IDecl->getNumInstanceMethods() > 0) {
1087 Result += "\t, (struct _objc_method_list *)"
1088 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1089 Result += FullCategoryName;
1090 Result += "\n";
1091 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001092 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001093 Result += "\t, 0\n";
1094 if (IDecl->getNumClassMethods() > 0) {
1095 Result += "\t, (struct _objc_method_list *)"
1096 "&_OBJC_CATEGORY_CLASS_METHODS_";
1097 Result += FullCategoryName;
1098 Result += "\n";
1099 }
1100 else
1101 Result += "\t, 0\n";
1102
1103 if (CDecl->getNumReferencedProtocols() > 0) {
1104 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1105 Result += FullCategoryName;
1106 Result += "\n";
1107 }
1108 else
1109 Result += "\t, 0\n";
1110 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001111}
1112
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001113/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1114/// ivar offset.
1115void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1116 ObjcIvarDecl *ivar,
1117 std::string &Result) {
1118 Result += "offsetof(struct _interface_";
1119 Result += IDecl->getName();
1120 Result += ", ";
1121 Result += ivar->getName();
1122 Result += ")";
1123}
1124
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001125//===----------------------------------------------------------------------===//
1126// Meta Data Emission
1127//===----------------------------------------------------------------------===//
1128
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001129void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1130 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001131 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1132
1133 // Build _objc_ivar_list metadata for classes ivars if needed
1134 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1135 ? IDecl->getImplDeclNumIvars()
1136 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1137
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001138 SynthesizeObjcInternalStruct(CDecl, Result);
1139
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001140 if (NumIvars > 0) {
1141 static bool objc_ivar = false;
1142 if (!objc_ivar) {
1143 /* struct _objc_ivar {
1144 char *ivar_name;
1145 char *ivar_type;
1146 int ivar_offset;
1147 };
1148 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001149 Result += "\nstruct _objc_ivar {\n";
1150 Result += "\tchar *ivar_name;\n";
1151 Result += "\tchar *ivar_type;\n";
1152 Result += "\tint ivar_offset;\n";
1153 Result += "};\n";
1154
1155 /* struct _objc_ivar_list {
1156 int ivar_count;
1157 struct _objc_ivar ivar_list[];
1158 };
1159 */
1160 Result += "\nstruct _objc_ivar_list {\n";
1161 Result += "\tint ivar_count;\n";
1162 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001163 objc_ivar = true;
1164 }
1165
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001166 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1167 Result += IDecl->getName();
1168 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1169 "{\n\t";
1170 Result += utostr(NumIvars);
1171 Result += "\n";
1172
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001173 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1174 ? IDecl->getImplDeclIVars()
1175 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001176 Result += "\t,{{\"";
1177 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001178 Result += "\", \"";
1179 std::string StrEncoding;
1180 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1181 Result += StrEncoding;
1182 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001183 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1184 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001185 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001186 Result += "\t ,{\"";
1187 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001188 Result += "\", \"";
1189 std::string StrEncoding;
1190 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1191 Result += StrEncoding;
1192 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001193 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1194 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001195 }
1196
1197 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001198 }
1199
1200 // Build _objc_method_list for class's instance methods if needed
1201 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1202 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001203 true,
1204 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001205
1206 // Build _objc_method_list for class's class methods if needed
1207 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001208 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001209 false,
1210 "", IDecl->getName(), Result);
1211
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001212 // Protocols referenced in class declaration?
1213 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1214 CDecl->getNumIntfRefProtocols(),
1215 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001216 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001217
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001218
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001219 // Declaration of class/meta-class metadata
1220 /* struct _objc_class {
1221 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001222 const char *super_class_name;
1223 char *name;
1224 long version;
1225 long info;
1226 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001227 struct _objc_ivar_list *ivars;
1228 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001229 struct objc_cache *cache;
1230 struct objc_protocol_list *protocols;
1231 const char *ivar_layout;
1232 struct _objc_class_ext *ext;
1233 };
1234 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001235 static bool objc_class = false;
1236 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001237 Result += "\nstruct _objc_class {\n";
1238 Result += "\tstruct _objc_class *isa;\n";
1239 Result += "\tconst char *super_class_name;\n";
1240 Result += "\tchar *name;\n";
1241 Result += "\tlong version;\n";
1242 Result += "\tlong info;\n";
1243 Result += "\tlong instance_size;\n";
1244 Result += "\tstruct _objc_ivar_list *ivars;\n";
1245 Result += "\tstruct _objc_method_list *methods;\n";
1246 Result += "\tstruct objc_cache *cache;\n";
1247 Result += "\tstruct _objc_protocol_list *protocols;\n";
1248 Result += "\tconst char *ivar_layout;\n";
1249 Result += "\tstruct _objc_class_ext *ext;\n";
1250 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001251 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001252 }
1253
1254 // Meta-class metadata generation.
1255 ObjcInterfaceDecl *RootClass = 0;
1256 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1257 while (SuperClass) {
1258 RootClass = SuperClass;
1259 SuperClass = SuperClass->getSuperClass();
1260 }
1261 SuperClass = CDecl->getSuperClass();
1262
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001263 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1264 Result += CDecl->getName();
1265 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1266 "{\n\t(struct _objc_class *)\"";
1267 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1268 Result += "\"";
1269
1270 if (SuperClass) {
1271 Result += ", \"";
1272 Result += SuperClass->getName();
1273 Result += "\", \"";
1274 Result += CDecl->getName();
1275 Result += "\"";
1276 }
1277 else {
1278 Result += ", 0, \"";
1279 Result += CDecl->getName();
1280 Result += "\"";
1281 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001282 // TODO: 'ivars' field for root class is currently set to 0.
1283 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001284 Result += ", 0,2, sizeof(struct _objc_class), 0";
1285 if (CDecl->getNumClassMethods() > 0) {
1286 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1287 Result += CDecl->getName();
1288 Result += "\n";
1289 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001290 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001291 Result += ", 0\n";
1292 if (CDecl->getNumIntfRefProtocols() > 0) {
1293 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1294 Result += CDecl->getName();
1295 Result += ",0,0\n";
1296 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001297 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001298 Result += "\t,0,0,0,0\n";
1299 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001300
1301 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001302 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1303 Result += CDecl->getName();
1304 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1305 "{\n\t&_OBJC_METACLASS_";
1306 Result += CDecl->getName();
1307 if (SuperClass) {
1308 Result += ", \"";
1309 Result += SuperClass->getName();
1310 Result += "\", \"";
1311 Result += CDecl->getName();
1312 Result += "\"";
1313 }
1314 else {
1315 Result += ", 0, \"";
1316 Result += CDecl->getName();
1317 Result += "\"";
1318 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001319 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001320 Result += ", 0,1";
1321 if (!ObjcSynthesizedStructs.count(CDecl))
1322 Result += ",0";
1323 else {
1324 // class has size. Must synthesize its size.
1325 Result += ",sizeof(struct _interface_";
1326 Result += CDecl->getName();
1327 Result += ")";
1328 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001329 if (NumIvars > 0) {
1330 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1331 Result += CDecl->getName();
1332 Result += "\n\t";
1333 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001334 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001335 Result += ",0";
1336 if (IDecl->getNumInstanceMethods() > 0) {
1337 Result += ", &_OBJC_INSTANCE_METHODS_";
1338 Result += CDecl->getName();
1339 Result += ", 0\n\t";
1340 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001341 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001342 Result += ",0,0";
1343 if (CDecl->getNumIntfRefProtocols() > 0) {
1344 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1345 Result += CDecl->getName();
1346 Result += ", 0,0\n";
1347 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001348 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001349 Result += ",0,0,0\n";
1350 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001351}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001352
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001353void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001354 int ClsDefCount = ClassImplementation.size();
1355 int CatDefCount = CategoryImplementation.size();
1356 if (ClsDefCount == 0 && CatDefCount == 0)
1357 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001358
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001359 // TODO: This is temporary until we decide how to access objc types in a
1360 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001361 Result += "#include <Objc/objc.h>\n";
1362 // This is needed for use of offsetof
1363 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001364
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001365 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001366 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001367 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001368
1369 // For each implemented category, write out all its meta data.
1370 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001371 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001372
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001373 // Write objc_symtab metadata
1374 /*
1375 struct _objc_symtab
1376 {
1377 long sel_ref_cnt;
1378 SEL *refs;
1379 short cls_def_cnt;
1380 short cat_def_cnt;
1381 void *defs[cls_def_cnt + cat_def_cnt];
1382 };
1383 */
1384
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001385 Result += "\nstruct _objc_symtab {\n";
1386 Result += "\tlong sel_ref_cnt;\n";
1387 Result += "\tSEL *refs;\n";
1388 Result += "\tshort cls_def_cnt;\n";
1389 Result += "\tshort cat_def_cnt;\n";
1390 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1391 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001392
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001393 Result += "static struct _objc_symtab "
1394 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1395 Result += "\t0, 0, " + utostr(ClsDefCount)
1396 + ", " + utostr(CatDefCount) + "\n";
1397 for (int i = 0; i < ClsDefCount; i++) {
1398 Result += "\t,&_OBJC_CLASS_";
1399 Result += ClassImplementation[i]->getName();
1400 Result += "\n";
1401 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001402
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001403 for (int i = 0; i < CatDefCount; i++) {
1404 Result += "\t,&_OBJC_CATEGORY_";
1405 Result += CategoryImplementation[i]->getClassInterface()->getName();
1406 Result += "_";
1407 Result += CategoryImplementation[i]->getName();
1408 Result += "\n";
1409 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001410
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001411 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001412
1413 // Write objc_module metadata
1414
1415 /*
1416 struct _objc_module {
1417 long version;
1418 long size;
1419 const char *name;
1420 struct _objc_symtab *symtab;
1421 }
1422 */
1423
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001424 Result += "\nstruct _objc_module {\n";
1425 Result += "\tlong version;\n";
1426 Result += "\tlong size;\n";
1427 Result += "\tconst char *name;\n";
1428 Result += "\tstruct _objc_symtab *symtab;\n";
1429 Result += "};\n\n";
1430 Result += "static struct _objc_module "
1431 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001432 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1433 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001434 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001435}
Chris Lattner311ff022007-10-16 22:36:42 +00001436