blob: 6a5bb0fc3a4b74994be9ae34d89ba8ab5c40539f [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 Naroffebf2b562007-10-23 23:50:29 +000036
37 FunctionDecl *MsgSendFunctionDecl;
38 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000039 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000040
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000041 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000042 public:
Chris Lattner01c57482007-10-17 22:35:30 +000043 void Initialize(ASTContext &context, unsigned mainFileID) {
44 Context = &context;
45 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000046 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000047 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000048 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000049 SelGetUidFunctionDecl = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000050 Rewrite.setSourceMgr(Context->SourceMgr);
Chris Lattner77cd2a02007-10-11 00:43:27 +000051 }
Chris Lattner8a12c272007-10-11 18:38:32 +000052
Chris Lattnerf04da132007-10-24 17:06:59 +000053 // Top Level Driver code.
54 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000055 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000056 ~RewriteTest();
57
58 // Syntactic Rewriting.
Chris Lattner2c64b7b2007-10-16 21:07:07 +000059 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000060 void RewriteTabs();
61 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000062 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000063 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000064 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000065 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Steve Naroff09b266e2007-10-30 23:14:51 +000066 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroff9165ad32007-10-31 04:38:33 +000067 bool functionReferencesAnyObjcQualifiedInterfaceTypes(
68 const FunctionTypeProto *proto);
Chris Lattner311ff022007-10-16 22:36:42 +000069
Chris Lattnerf04da132007-10-24 17:06:59 +000070 // Expression Rewriting.
Chris Lattnere64b7772007-10-24 16:57:36 +000071 Stmt *RewriteFunctionBody(Stmt *S);
72 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
73 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff934f2762007-10-24 22:48:43 +000074 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
75 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +000076 void SynthMsgSendFunctionDecl();
77 void SynthGetClassFunctionDecl();
78
Chris Lattnerf04da132007-10-24 17:06:59 +000079 // Metadata emission.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000080 void HandleObjcMetaDataEmission();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000081 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
82 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000083
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000084 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
85 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000086
87 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
88 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +000089 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000090 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +000091 const char *ClassName,
92 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +000093
94 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
95 int NumProtocols,
96 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +000097 const char *ClassName,
98 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000099 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
100 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000101 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
102 ObjcIvarDecl *ivar,
103 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000104 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000105 };
106}
107
Chris Lattner8a12c272007-10-11 18:38:32 +0000108ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000109
Chris Lattnerf04da132007-10-24 17:06:59 +0000110//===----------------------------------------------------------------------===//
111// Top Level Driver Code
112//===----------------------------------------------------------------------===//
113
Chris Lattner8a12c272007-10-11 18:38:32 +0000114void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000115 // Two cases: either the decl could be in the main file, or it could be in a
116 // #included file. If the former, rewrite it now. If the later, check to see
117 // if we rewrote the #include/#import.
118 SourceLocation Loc = D->getLocation();
119 Loc = SM->getLogicalLoc(Loc);
120
121 // If this is for a builtin, ignore it.
122 if (Loc.isInvalid()) return;
123
Steve Naroffebf2b562007-10-23 23:50:29 +0000124 // Look for built-in declarations that we need to refer during the rewrite.
125 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000126 RewriteFunctionDecl(FD);
Steve Naroffbef11852007-10-26 20:53:56 +0000127 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
128 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000129 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
130 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000131 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
132 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000133 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000135 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
136 return HandleDeclInMainFile(D);
137
Chris Lattnerf04da132007-10-24 17:06:59 +0000138 // Otherwise, see if there is a #import in the main file that should be
139 // rewritten.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000140 RewriteInclude(Loc);
141}
142
Chris Lattnerf04da132007-10-24 17:06:59 +0000143/// HandleDeclInMainFile - This is called for each top-level decl defined in the
144/// main file of the input.
145void RewriteTest::HandleDeclInMainFile(Decl *D) {
146 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
147 if (Stmt *Body = FD->getBody())
148 FD->setBody(RewriteFunctionBody(Body));
149
150 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
151 ClassImplementation.push_back(CI);
152 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
153 CategoryImplementation.push_back(CI);
154 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
155 RewriteForwardClassDecl(CD);
156 // Nothing yet.
157}
158
159RewriteTest::~RewriteTest() {
160 // Get the top-level buffer that this corresponds to.
161 RewriteTabs();
162
163 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
164 // we are done.
165 if (const RewriteBuffer *RewriteBuf =
166 Rewrite.getRewriteBufferFor(MainFileID)) {
167 printf("Changed:\n");
168 std::string S(RewriteBuf->begin(), RewriteBuf->end());
169 printf("%s\n", S.c_str());
170 } else {
171 printf("No changes\n");
172 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000173
174}
175
176/// HandleObjcMetaDataEmission - main routine to generate objective-c's
177/// metadata.
178void RewriteTest::HandleObjcMetaDataEmission() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000179 // Rewrite Objective-c meta data*
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000180 std::string ResultStr;
181 WriteObjcMetaData(ResultStr);
182 // For now just print the string out.
183 printf("%s", ResultStr.c_str());
Chris Lattnerf04da132007-10-24 17:06:59 +0000184}
185
186//===----------------------------------------------------------------------===//
187// Syntactic (non-AST) Rewriting Code
188//===----------------------------------------------------------------------===//
189
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000190void RewriteTest::RewriteInclude(SourceLocation Loc) {
191 // Rip up the #include stack to the main file.
192 SourceLocation IncLoc = Loc, NextLoc = Loc;
193 do {
194 IncLoc = Loc;
195 Loc = SM->getLogicalLoc(NextLoc);
196 NextLoc = SM->getIncludeLoc(Loc);
197 } while (!NextLoc.isInvalid());
198
199 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
200 // IncLoc indicates the header that was included if it is useful.
201 IncLoc = SM->getLogicalLoc(IncLoc);
202 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
203 Loc == LastIncLoc)
204 return;
205 LastIncLoc = Loc;
206
207 unsigned IncCol = SM->getColumnNumber(Loc);
208 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
209
210 // Replace the #import with #include.
211 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
212}
213
Chris Lattnerf04da132007-10-24 17:06:59 +0000214void RewriteTest::RewriteTabs() {
215 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
216 const char *MainBufStart = MainBuf.first;
217 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000218
Chris Lattnerf04da132007-10-24 17:06:59 +0000219 // Loop over the whole file, looking for tabs.
220 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
221 if (*BufPtr != '\t')
222 continue;
223
224 // Okay, we found a tab. This tab will turn into at least one character,
225 // but it depends on which 'virtual column' it is in. Compute that now.
226 unsigned VCol = 0;
227 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
228 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
229 ++VCol;
230
231 // Okay, now that we know the virtual column, we know how many spaces to
232 // insert. We assume 8-character tab-stops.
233 unsigned Spaces = 8-(VCol & 7);
234
235 // Get the location of the tab.
236 SourceLocation TabLoc =
237 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
238
239 // Rewrite the single tab character into a sequence of spaces.
240 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
241 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000242}
243
244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
246 int numDecls = ClassDecl->getNumForwardDecls();
247 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
248
249 // Get the start location and compute the semi location.
250 SourceLocation startLoc = ClassDecl->getLocation();
251 const char *startBuf = SM->getCharacterData(startLoc);
252 const char *semiPtr = strchr(startBuf, ';');
253
254 // Translate to typedef's that forward reference structs with the same name
255 // as the class. As a convenience, we include the original declaration
256 // as a comment.
257 std::string typedefString;
258 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000259 typedefString.append(startBuf, semiPtr-startBuf+1);
260 typedefString += "\n";
261 for (int i = 0; i < numDecls; i++) {
262 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
263 typedefString += "typedef struct ";
264 typedefString += ForwardDecl->getName();
265 typedefString += " ";
266 typedefString += ForwardDecl->getName();
267 typedefString += ";\n";
268 }
269
270 // Replace the @class with typedefs corresponding to the classes.
271 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
272 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000273}
274
Steve Naroff423cb562007-10-30 13:30:57 +0000275void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
276 for (int i = 0; i < nMethods; i++) {
277 ObjcMethodDecl *Method = Methods[i];
278 SourceLocation Loc = Method->getLocStart();
279
280 Rewrite.ReplaceText(Loc, 0, "// ", 3);
281
282 // FIXME: handle methods that are declared across multiple lines.
283 }
284}
285
286void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
287 SourceLocation LocStart = CatDecl->getLocStart();
288
289 // FIXME: handle category headers that are declared across multiple lines.
290 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
291
292 RewriteMethods(CatDecl->getNumInstanceMethods(),
293 CatDecl->getInstanceMethods());
294 RewriteMethods(CatDecl->getNumClassMethods(),
295 CatDecl->getClassMethods());
296 // Lastly, comment out the @end.
297 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
298}
299
Steve Naroff752d6ef2007-10-30 16:42:30 +0000300void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
301 SourceLocation LocStart = PDecl->getLocStart();
302
303 // FIXME: handle protocol headers that are declared across multiple lines.
304 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
305
306 RewriteMethods(PDecl->getNumInstanceMethods(),
307 PDecl->getInstanceMethods());
308 RewriteMethods(PDecl->getNumClassMethods(),
309 PDecl->getClassMethods());
310 // Lastly, comment out the @end.
311 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
312}
313
Steve Naroffbef11852007-10-26 20:53:56 +0000314void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000315
316 SourceLocation LocStart = ClassDecl->getLocStart();
317 SourceLocation LocEnd = ClassDecl->getLocEnd();
318
319 const char *startBuf = SM->getCharacterData(LocStart);
320 const char *endBuf = SM->getCharacterData(LocEnd);
321
Steve Naroff2feac5e2007-10-30 03:43:13 +0000322 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000323
324 std::string ResultStr;
325 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
326
Steve Naroff2feac5e2007-10-30 03:43:13 +0000327 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000328 ResultStr.c_str(), ResultStr.size());
329
Steve Naroff423cb562007-10-30 13:30:57 +0000330 RewriteMethods(ClassDecl->getNumInstanceMethods(),
331 ClassDecl->getInstanceMethods());
332 RewriteMethods(ClassDecl->getNumClassMethods(),
333 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000334
Steve Naroff2feac5e2007-10-30 03:43:13 +0000335 // Lastly, comment out the @end.
336 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000337}
338
Chris Lattnerf04da132007-10-24 17:06:59 +0000339//===----------------------------------------------------------------------===//
340// Function Body / Expression rewriting
341//===----------------------------------------------------------------------===//
342
Chris Lattnere64b7772007-10-24 16:57:36 +0000343Stmt *RewriteTest::RewriteFunctionBody(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000344 // Otherwise, just rewrite all children.
345 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
346 CI != E; ++CI)
Chris Lattner50754772007-10-17 21:28:00 +0000347 if (*CI)
Chris Lattnere64b7772007-10-24 16:57:36 +0000348 *CI = RewriteFunctionBody(*CI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000349
350 // Handle specific things.
351 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
352 return RewriteAtEncode(AtEncode);
353
Steve Naroff934f2762007-10-24 22:48:43 +0000354 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
355 // Before we rewrite it, put the original message expression in a comment.
356 SourceLocation startLoc = MessExpr->getLocStart();
357 SourceLocation endLoc = MessExpr->getLocEnd();
358
359 const char *startBuf = SM->getCharacterData(startLoc);
360 const char *endBuf = SM->getCharacterData(endLoc);
361
362 std::string messString;
363 messString += "// ";
364 messString.append(startBuf, endBuf-startBuf+1);
365 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000366
Steve Naroff934f2762007-10-24 22:48:43 +0000367 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
368 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
369 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000370 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000371 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000372 }
Chris Lattnere64b7772007-10-24 16:57:36 +0000373 // Return this stmt unmodified.
374 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000375}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000376
Chris Lattnere64b7772007-10-24 16:57:36 +0000377Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000378 // Create a new string expression.
379 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000380 std::string StrEncoding;
381 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
382 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
383 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000384 SourceLocation(), SourceLocation());
385 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000386 delete Exp;
387 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000388}
389
Steve Naroff934f2762007-10-24 22:48:43 +0000390CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
391 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000392 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000393 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000394
395 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000396 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000397
398 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000399 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000400 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
401
402 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000403
Steve Naroff934f2762007-10-24 22:48:43 +0000404 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
405}
406
Steve Naroff9165ad32007-10-31 04:38:33 +0000407bool RewriteTest::functionReferencesAnyObjcQualifiedInterfaceTypes(
408 const FunctionTypeProto *proto) {
Steve Naroff498856c2007-10-31 16:03:04 +0000409 QualType resultType = proto->getResultType();
410
411 if (resultType == Context->getObjcIdType()) {
412 // FIXME: we don't currently represent "id <Protocol>" in the type system.
413 // Implement a heuristic here (until we do).
414 } else if (const PointerType *pType = resultType->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000415 Type *pointeeType = pType->getPointeeType().getTypePtr();
416 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
417 return true; // we have "Class <Protocol> *".
418 }
419 // Now check arguments.
420 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
Steve Naroff498856c2007-10-31 16:03:04 +0000421 QualType argType = proto->getArgType(i);
422 if (argType == Context->getObjcIdType()) {
423 // FIXME: we don't currently represent "id <Protocol>" in the type system.
424 // Implement a heuristic here (until we do).
425 } else if (const PointerType *pType = argType->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000426 Type *pointeeType = pType->getPointeeType().getTypePtr();
427 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
428 return true;
429 }
430 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000431 return false;
432}
433
Steve Naroff09b266e2007-10-30 23:14:51 +0000434void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
435 // declared in <objc/objc.h>
Steve Naroff9165ad32007-10-31 04:38:33 +0000436 if (strcmp(FD->getName(), "sel_getUid") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000437 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000438 return;
439 }
Steve Naroff498856c2007-10-31 16:03:04 +0000440 return; // FIXME: remove when the code below is ready.
Steve Naroff9165ad32007-10-31 04:38:33 +0000441 // Check for ObjC 'id' and class types that have been adorned with protocol
442 // information (id<p>, C<p>*). The protocol references need to be rewritten!
443 const FunctionType *funcType = FD->getType()->getAsFunctionType();
444 assert(funcType && "missing function type");
445 const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType);
446 if (proto && functionReferencesAnyObjcQualifiedInterfaceTypes(proto)) {
447 // FIXME: Rewrite function decl...
448 }
Steve Naroff09b266e2007-10-30 23:14:51 +0000449}
450
451// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
452void RewriteTest::SynthMsgSendFunctionDecl() {
453 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
454 llvm::SmallVector<QualType, 16> ArgTys;
455 QualType argT = Context->getObjcIdType();
456 assert(!argT.isNull() && "Can't find 'id' type");
457 ArgTys.push_back(argT);
458 argT = Context->getObjcSelType();
459 assert(!argT.isNull() && "Can't find 'SEL' type");
460 ArgTys.push_back(argT);
461 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
462 &ArgTys[0], ArgTys.size(),
463 true /*isVariadic*/);
464 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
465 msgSendIdent, msgSendType,
466 FunctionDecl::Extern, false, 0);
467}
468
469// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
470void RewriteTest::SynthGetClassFunctionDecl() {
471 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
472 llvm::SmallVector<QualType, 16> ArgTys;
473 ArgTys.push_back(Context->getPointerType(
474 Context->CharTy.getQualifiedType(QualType::Const)));
475 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
476 &ArgTys[0], ArgTys.size(),
477 false /*isVariadic*/);
478 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
479 getClassIdent, getClassType,
480 FunctionDecl::Extern, false, 0);
481}
482
Steve Naroff934f2762007-10-24 22:48:43 +0000483Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff934f2762007-10-24 22:48:43 +0000484 assert(SelGetUidFunctionDecl && "Can't find sel_getUid() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000485 if (!MsgSendFunctionDecl)
486 SynthMsgSendFunctionDecl();
487 if (!GetClassFunctionDecl)
488 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000489
490 // Synthesize a call to objc_msgSend().
491 llvm::SmallVector<Expr*, 8> MsgExprs;
492 IdentifierInfo *clsName = Exp->getClassName();
493
494 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
495 if (clsName) { // class message.
496 llvm::SmallVector<Expr*, 8> ClsExprs;
497 QualType argType = Context->getPointerType(Context->CharTy);
498 ClsExprs.push_back(new StringLiteral(clsName->getName(),
499 clsName->getLength(),
500 false, argType, SourceLocation(),
501 SourceLocation()));
502 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
503 &ClsExprs[0], ClsExprs.size());
504 MsgExprs.push_back(Cls);
505 } else // instance message.
506 MsgExprs.push_back(Exp->getReceiver());
507
508 // Create a call to sel_getUid("selName"), it will be the 2nd argument.
509 llvm::SmallVector<Expr*, 8> SelExprs;
510 QualType argType = Context->getPointerType(Context->CharTy);
511 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
512 Exp->getSelector().getName().size(),
513 false, argType, SourceLocation(),
514 SourceLocation()));
515 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
516 &SelExprs[0], SelExprs.size());
517 MsgExprs.push_back(SelExp);
518
519 // Now push any user supplied arguments.
520 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
521 MsgExprs.push_back(Exp->getArg(i));
522 // We've transferred the ownership to MsgExprs. Null out the argument in
523 // the original expression, since we will delete it below.
524 Exp->setArg(i, 0);
525 }
526 CallExpr *MessExp = SynthesizeCallToFunctionDecl(MsgSendFunctionDecl,
527 &MsgExprs[0], MsgExprs.size());
528 // Now do the actual rewrite.
529 Rewrite.ReplaceStmt(Exp, MessExp);
530
Chris Lattnere64b7772007-10-24 16:57:36 +0000531 delete Exp;
Steve Naroff934f2762007-10-24 22:48:43 +0000532 return MessExp;
Steve Naroffebf2b562007-10-23 23:50:29 +0000533}
534
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000535/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
536/// an objective-c class with ivars.
537void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
538 std::string &Result) {
539 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
540 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
541 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
542 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
543 // Do it for the root
544 SynthesizeObjcInternalStruct(RCDecl, Result);
545 }
546
547 int NumIvars = CDecl->getIntfDeclNumIvars();
548 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
549 return;
550
551 Result += "\nstruct _interface_";
552 Result += CDecl->getName();
553 Result += " {\n";
554 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
555 Result += "\tstruct _interface_";
556 Result += RCDecl->getName();
557 Result += " _";
558 Result += RCDecl->getName();
559 Result += ";\n";
560 }
561
562 ObjcIvarDecl **Ivars = CDecl->getIntfDeclIvars();
563 for (int i = 0; i < NumIvars; i++) {
564 Result += "\t";
565 std::string Name = Ivars[i]->getName();
566 Ivars[i]->getType().getAsStringInternal(Name);
567 Result += Name;
568 Result += ";\n";
569 }
570 Result += "};\n";
571 // Mark this struct as having been generated.
572 if (!ObjcSynthesizedStructs.insert(CDecl))
573 assert(true && "struct already synthesize- SynthesizeObjcInternalStruct");
574}
575
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000576// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
577/// class methods.
578void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
579 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000580 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000581 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000582 const char *ClassName,
583 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000584 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000585 if (NumMethods > 0 && !objc_impl_method) {
586 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000587 SEL _cmd;
588 char *method_types;
589 void *_imp;
590 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000591 */
Chris Lattner158ecb92007-10-25 17:07:24 +0000592 Result += "\nstruct _objc_method {\n";
593 Result += "\tSEL _cmd;\n";
594 Result += "\tchar *method_types;\n";
595 Result += "\tvoid *_imp;\n";
596 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000597
598 /* struct _objc_method_list {
599 struct _objc_method_list *next_method;
600 int method_count;
601 struct _objc_method method_list[];
602 }
603 */
604 Result += "\nstruct _objc_method_list {\n";
605 Result += "\tstruct _objc_method_list *next_method;\n";
606 Result += "\tint method_count;\n";
607 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000608 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +0000609 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000610 // Build _objc_method_list for class's methods if needed
611 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000612 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +0000613 Result += prefix;
614 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
615 Result += "_METHODS_";
616 Result += ClassName;
617 Result += " __attribute__ ((section (\"__OBJC, __";
618 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000619 Result += "_meth\")))= ";
620 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
621
622 Result += "\t,{{(SEL)\"";
623 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000624 std::string MethodTypeString;
625 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
626 Result += "\", \"";
627 Result += MethodTypeString;
628 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000629 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000630 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000631 Result += "\t ,{(SEL)\"";
632 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000633 std::string MethodTypeString;
634 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
635 Result += "\", \"";
636 Result += MethodTypeString;
637 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000638 }
639 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000640 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000641}
642
643/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
644void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
645 int NumProtocols,
646 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000647 const char *ClassName,
648 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000649 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000650 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000651 for (int i = 0; i < NumProtocols; i++) {
652 ObjcProtocolDecl *PDecl = Protocols[i];
653 // Output struct protocol_methods holder of method selector and type.
654 if (!objc_protocol_methods &&
655 (PDecl->getNumInstanceMethods() > 0
656 || PDecl->getNumClassMethods() > 0)) {
657 /* struct protocol_methods {
658 SEL _cmd;
659 char *method_types;
660 }
661 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000662 Result += "\nstruct protocol_methods {\n";
663 Result += "\tSEL _cmd;\n";
664 Result += "\tchar *method_types;\n";
665 Result += "};\n";
666
667 /* struct _objc_protocol_method_list {
668 int protocol_method_count;
669 struct protocol_methods protocols[];
670 }
671 */
672 Result += "\nstruct _objc_protocol_method_list {\n";
673 Result += "\tint protocol_method_count;\n";
674 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000675 objc_protocol_methods = true;
676 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000677
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000678 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000679 int NumMethods = PDecl->getNumInstanceMethods();
680 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000681 Result += "\nstatic struct _objc_protocol_method_list "
682 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
683 Result += PDecl->getName();
684 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
685 "{\n\t" + utostr(NumMethods) + "\n";
686
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000687 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000688 Result += "\t,{{(SEL)\"";
689 Result += Methods[0]->getSelector().getName().c_str();
690 Result += "\", \"\"}\n";
691
692 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000693 Result += "\t ,{(SEL)\"";
694 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000695 std::string MethodTypeString;
696 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
697 Result += "\", \"";
698 Result += MethodTypeString;
699 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000700 }
701 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000702 }
703
704 // Output class methods declared in this protocol.
705 NumMethods = PDecl->getNumClassMethods();
706 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000707 Result += "\nstatic struct _objc_protocol_method_list "
708 "_OBJC_PROTOCOL_CLASS_METHODS_";
709 Result += PDecl->getName();
710 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
711 "{\n\t";
712 Result += utostr(NumMethods);
713 Result += "\n";
714
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000715 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000716 Result += "\t,{{(SEL)\"";
717 Result += Methods[0]->getSelector().getName().c_str();
718 Result += "\", \"\"}\n";
719
720 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000721 Result += "\t ,{(SEL)\"";
722 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +0000723 std::string MethodTypeString;
724 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
725 Result += "\", \"";
726 Result += MethodTypeString;
727 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000728 }
729 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000730 }
731 // Output:
732 /* struct _objc_protocol {
733 // Objective-C 1.0 extensions
734 struct _objc_protocol_extension *isa;
735 char *protocol_name;
736 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000737 struct _objc_protocol_method_list *instance_methods;
738 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000739 };
740 */
741 static bool objc_protocol = false;
742 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000743 Result += "\nstruct _objc_protocol {\n";
744 Result += "\tstruct _objc_protocol_extension *isa;\n";
745 Result += "\tchar *protocol_name;\n";
746 Result += "\tstruct _objc_protocol **protocol_list;\n";
747 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
748 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
749 Result += "};\n";
750
751 /* struct _objc_protocol_list {
752 struct _objc_protocol_list *next;
753 int protocol_count;
754 struct _objc_protocol *class_protocols[];
755 }
756 */
757 Result += "\nstruct _objc_protocol_list {\n";
758 Result += "\tstruct _objc_protocol_list *next;\n";
759 Result += "\tint protocol_count;\n";
760 Result += "\tstruct _objc_protocol *class_protocols[];\n";
761 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000762 objc_protocol = true;
763 }
764
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000765 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
766 Result += PDecl->getName();
767 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
768 "{\n\t0, \"";
769 Result += PDecl->getName();
770 Result += "\", 0, ";
771 if (PDecl->getInstanceMethods() > 0) {
772 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
773 Result += PDecl->getName();
774 Result += ", ";
775 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000776 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000777 Result += "0, ";
778 if (PDecl->getClassMethods() > 0) {
779 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
780 Result += PDecl->getName();
781 Result += "\n";
782 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000783 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000784 Result += "0\n";
785 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000786 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000787 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000788 Result += "\nstatic struct _objc_protocol_list _OBJC_";
789 Result += prefix;
790 Result += "_PROTOCOLS_";
791 Result += ClassName;
792 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
793 "{\n\t0, ";
794 Result += utostr(NumProtocols);
795 Result += "\n";
796
797 Result += "\t,{&_OBJC_PROTOCOL_";
798 Result += Protocols[0]->getName();
799 Result += " \n";
800
801 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000802 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000803 Result += "\t ,&_OBJC_PROTOCOL_";
804 Result += PDecl->getName();
805 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000806 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000807 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000808 }
809}
810
811/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
812/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000813void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
814 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000815 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
816 // Find category declaration for this implementation.
817 ObjcCategoryDecl *CDecl;
818 for (CDecl = ClassDecl->getCategoryList(); CDecl;
819 CDecl = CDecl->getNextClassCategory())
820 if (CDecl->getIdentifier() == IDecl->getIdentifier())
821 break;
822 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
823
824 char *FullCategoryName = (char*)alloca(
825 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
826 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
827
828 // Build _objc_method_list for class's instance methods if needed
829 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
830 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000831 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000832 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000833
834 // Build _objc_method_list for class's class methods if needed
835 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
836 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000837 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000838 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000839
840 // Protocols referenced in class declaration?
841 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
842 CDecl->getNumReferencedProtocols(),
843 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000844 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000845
846 /* struct _objc_category {
847 char *category_name;
848 char *class_name;
849 struct _objc_method_list *instance_methods;
850 struct _objc_method_list *class_methods;
851 struct _objc_protocol_list *protocols;
852 // Objective-C 1.0 extensions
853 uint32_t size; // sizeof (struct _objc_category)
854 struct _objc_property_list *instance_properties; // category's own
855 // @property decl.
856 };
857 */
858
859 static bool objc_category = false;
860 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000861 Result += "\nstruct _objc_category {\n";
862 Result += "\tchar *category_name;\n";
863 Result += "\tchar *class_name;\n";
864 Result += "\tstruct _objc_method_list *instance_methods;\n";
865 Result += "\tstruct _objc_method_list *class_methods;\n";
866 Result += "\tstruct _objc_protocol_list *protocols;\n";
867 Result += "\tunsigned int size;\n";
868 Result += "\tstruct _objc_property_list *instance_properties;\n";
869 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000870 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +0000871 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000872 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
873 Result += FullCategoryName;
874 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
875 Result += IDecl->getName();
876 Result += "\"\n\t, \"";
877 Result += ClassDecl->getName();
878 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000879
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000880 if (IDecl->getNumInstanceMethods() > 0) {
881 Result += "\t, (struct _objc_method_list *)"
882 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
883 Result += FullCategoryName;
884 Result += "\n";
885 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000886 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000887 Result += "\t, 0\n";
888 if (IDecl->getNumClassMethods() > 0) {
889 Result += "\t, (struct _objc_method_list *)"
890 "&_OBJC_CATEGORY_CLASS_METHODS_";
891 Result += FullCategoryName;
892 Result += "\n";
893 }
894 else
895 Result += "\t, 0\n";
896
897 if (CDecl->getNumReferencedProtocols() > 0) {
898 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
899 Result += FullCategoryName;
900 Result += "\n";
901 }
902 else
903 Result += "\t, 0\n";
904 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000905}
906
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000907/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
908/// ivar offset.
909void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
910 ObjcIvarDecl *ivar,
911 std::string &Result) {
912 Result += "offsetof(struct _interface_";
913 Result += IDecl->getName();
914 Result += ", ";
915 Result += ivar->getName();
916 Result += ")";
917}
918
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000919//===----------------------------------------------------------------------===//
920// Meta Data Emission
921//===----------------------------------------------------------------------===//
922
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000923void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
924 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000925 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
926
927 // Build _objc_ivar_list metadata for classes ivars if needed
928 int NumIvars = IDecl->getImplDeclNumIvars() > 0
929 ? IDecl->getImplDeclNumIvars()
930 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
931
Fariborz Jahanian4d733d32007-10-26 23:09:28 +0000932 SynthesizeObjcInternalStruct(CDecl, Result);
933
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000934 if (NumIvars > 0) {
935 static bool objc_ivar = false;
936 if (!objc_ivar) {
937 /* struct _objc_ivar {
938 char *ivar_name;
939 char *ivar_type;
940 int ivar_offset;
941 };
942 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000943 Result += "\nstruct _objc_ivar {\n";
944 Result += "\tchar *ivar_name;\n";
945 Result += "\tchar *ivar_type;\n";
946 Result += "\tint ivar_offset;\n";
947 Result += "};\n";
948
949 /* struct _objc_ivar_list {
950 int ivar_count;
951 struct _objc_ivar ivar_list[];
952 };
953 */
954 Result += "\nstruct _objc_ivar_list {\n";
955 Result += "\tint ivar_count;\n";
956 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000957 objc_ivar = true;
958 }
959
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000960 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
961 Result += IDecl->getName();
962 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
963 "{\n\t";
964 Result += utostr(NumIvars);
965 Result += "\n";
966
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000967 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
968 ? IDecl->getImplDeclIVars()
969 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000970 Result += "\t,{{\"";
971 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +0000972 Result += "\", \"";
973 std::string StrEncoding;
974 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
975 Result += StrEncoding;
976 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000977 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
978 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000979 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000980 Result += "\t ,{\"";
981 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +0000982 Result += "\", \"";
983 std::string StrEncoding;
984 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
985 Result += StrEncoding;
986 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000987 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
988 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000989 }
990
991 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000992 }
993
994 // Build _objc_method_list for class's instance methods if needed
995 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
996 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000997 true,
998 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000999
1000 // Build _objc_method_list for class's class methods if needed
1001 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001002 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001003 false,
1004 "", IDecl->getName(), Result);
1005
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001006 // Protocols referenced in class declaration?
1007 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1008 CDecl->getNumIntfRefProtocols(),
1009 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001010 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001011
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001012
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001013 // Declaration of class/meta-class metadata
1014 /* struct _objc_class {
1015 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001016 const char *super_class_name;
1017 char *name;
1018 long version;
1019 long info;
1020 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001021 struct _objc_ivar_list *ivars;
1022 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001023 struct objc_cache *cache;
1024 struct objc_protocol_list *protocols;
1025 const char *ivar_layout;
1026 struct _objc_class_ext *ext;
1027 };
1028 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001029 static bool objc_class = false;
1030 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001031 Result += "\nstruct _objc_class {\n";
1032 Result += "\tstruct _objc_class *isa;\n";
1033 Result += "\tconst char *super_class_name;\n";
1034 Result += "\tchar *name;\n";
1035 Result += "\tlong version;\n";
1036 Result += "\tlong info;\n";
1037 Result += "\tlong instance_size;\n";
1038 Result += "\tstruct _objc_ivar_list *ivars;\n";
1039 Result += "\tstruct _objc_method_list *methods;\n";
1040 Result += "\tstruct objc_cache *cache;\n";
1041 Result += "\tstruct _objc_protocol_list *protocols;\n";
1042 Result += "\tconst char *ivar_layout;\n";
1043 Result += "\tstruct _objc_class_ext *ext;\n";
1044 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001045 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001046 }
1047
1048 // Meta-class metadata generation.
1049 ObjcInterfaceDecl *RootClass = 0;
1050 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1051 while (SuperClass) {
1052 RootClass = SuperClass;
1053 SuperClass = SuperClass->getSuperClass();
1054 }
1055 SuperClass = CDecl->getSuperClass();
1056
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001057 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1058 Result += CDecl->getName();
1059 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1060 "{\n\t(struct _objc_class *)\"";
1061 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1062 Result += "\"";
1063
1064 if (SuperClass) {
1065 Result += ", \"";
1066 Result += SuperClass->getName();
1067 Result += "\", \"";
1068 Result += CDecl->getName();
1069 Result += "\"";
1070 }
1071 else {
1072 Result += ", 0, \"";
1073 Result += CDecl->getName();
1074 Result += "\"";
1075 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001076 // TODO: 'ivars' field for root class is currently set to 0.
1077 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001078 Result += ", 0,2, sizeof(struct _objc_class), 0";
1079 if (CDecl->getNumClassMethods() > 0) {
1080 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1081 Result += CDecl->getName();
1082 Result += "\n";
1083 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001084 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001085 Result += ", 0\n";
1086 if (CDecl->getNumIntfRefProtocols() > 0) {
1087 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1088 Result += CDecl->getName();
1089 Result += ",0,0\n";
1090 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001091 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001092 Result += "\t,0,0,0,0\n";
1093 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001094
1095 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001096 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1097 Result += CDecl->getName();
1098 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1099 "{\n\t&_OBJC_METACLASS_";
1100 Result += CDecl->getName();
1101 if (SuperClass) {
1102 Result += ", \"";
1103 Result += SuperClass->getName();
1104 Result += "\", \"";
1105 Result += CDecl->getName();
1106 Result += "\"";
1107 }
1108 else {
1109 Result += ", 0, \"";
1110 Result += CDecl->getName();
1111 Result += "\"";
1112 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001113 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001114 Result += ", 0,1";
1115 if (!ObjcSynthesizedStructs.count(CDecl))
1116 Result += ",0";
1117 else {
1118 // class has size. Must synthesize its size.
1119 Result += ",sizeof(struct _interface_";
1120 Result += CDecl->getName();
1121 Result += ")";
1122 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001123 if (NumIvars > 0) {
1124 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1125 Result += CDecl->getName();
1126 Result += "\n\t";
1127 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001128 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001129 Result += ",0";
1130 if (IDecl->getNumInstanceMethods() > 0) {
1131 Result += ", &_OBJC_INSTANCE_METHODS_";
1132 Result += CDecl->getName();
1133 Result += ", 0\n\t";
1134 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001135 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001136 Result += ",0,0";
1137 if (CDecl->getNumIntfRefProtocols() > 0) {
1138 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1139 Result += CDecl->getName();
1140 Result += ", 0,0\n";
1141 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001142 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001143 Result += ",0,0,0\n";
1144 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001145}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001146
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001147void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001148 int ClsDefCount = ClassImplementation.size();
1149 int CatDefCount = CategoryImplementation.size();
1150 if (ClsDefCount == 0 && CatDefCount == 0)
1151 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001152
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001153 // TODO: This is temporary until we decide how to access objc types in a
1154 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001155 Result += "#include <Objc/objc.h>\n";
1156 // This is needed for use of offsetof
1157 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001158
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001159 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001160 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001161 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001162
1163 // For each implemented category, write out all its meta data.
1164 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001165 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001166
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001167 // Write objc_symtab metadata
1168 /*
1169 struct _objc_symtab
1170 {
1171 long sel_ref_cnt;
1172 SEL *refs;
1173 short cls_def_cnt;
1174 short cat_def_cnt;
1175 void *defs[cls_def_cnt + cat_def_cnt];
1176 };
1177 */
1178
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001179 Result += "\nstruct _objc_symtab {\n";
1180 Result += "\tlong sel_ref_cnt;\n";
1181 Result += "\tSEL *refs;\n";
1182 Result += "\tshort cls_def_cnt;\n";
1183 Result += "\tshort cat_def_cnt;\n";
1184 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1185 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001186
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001187 Result += "static struct _objc_symtab "
1188 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1189 Result += "\t0, 0, " + utostr(ClsDefCount)
1190 + ", " + utostr(CatDefCount) + "\n";
1191 for (int i = 0; i < ClsDefCount; i++) {
1192 Result += "\t,&_OBJC_CLASS_";
1193 Result += ClassImplementation[i]->getName();
1194 Result += "\n";
1195 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001196
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001197 for (int i = 0; i < CatDefCount; i++) {
1198 Result += "\t,&_OBJC_CATEGORY_";
1199 Result += CategoryImplementation[i]->getClassInterface()->getName();
1200 Result += "_";
1201 Result += CategoryImplementation[i]->getName();
1202 Result += "\n";
1203 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001204
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001205 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001206
1207 // Write objc_module metadata
1208
1209 /*
1210 struct _objc_module {
1211 long version;
1212 long size;
1213 const char *name;
1214 struct _objc_symtab *symtab;
1215 }
1216 */
1217
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001218 Result += "\nstruct _objc_module {\n";
1219 Result += "\tlong version;\n";
1220 Result += "\tlong size;\n";
1221 Result += "\tconst char *name;\n";
1222 Result += "\tstruct _objc_symtab *symtab;\n";
1223 Result += "};\n\n";
1224 Result += "static struct _objc_module "
1225 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001226 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1227 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001228 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001229}
Chris Lattner311ff022007-10-16 22:36:42 +00001230