blob: 37d499df9c2dce1f6ac44b558e8700f1fd171792 [file] [log] [blame]
Chris Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff1ccf4632007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000023using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000025
Chris Lattnerb429ae42007-10-11 00:43:27 +000026namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner74db1682007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Steve Naroffe9780582007-10-23 23:50:29 +000037
38 FunctionDecl *MsgSendFunctionDecl;
39 FunctionDecl *GetClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000040 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000041 FunctionDecl *CFStringFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000042
Steve Naroff0add5d22007-11-03 11:27:19 +000043 // ObjC string constant support.
44 FileVarDecl *ConstantStringClassReference;
45 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000046
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000047 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000048 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000049 void Initialize(ASTContext &context, unsigned mainFileID) {
50 Context = &context;
51 SM = &Context->SourceMgr;
Chris Lattner569faa62007-10-11 18:38:32 +000052 MainFileID = mainFileID;
Steve Naroffe9780582007-10-23 23:50:29 +000053 MsgSendFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000054 GetClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000055 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000056 CFStringFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000057 ConstantStringClassReference = 0;
58 NSStringRecord = 0;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000059 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Narofffcab7932007-11-05 14:55:35 +000060 // declaring objc_selector outside the parameter list removes a silly
61 // scope related warning...
Steve Naroffd3287d82007-11-07 18:43:40 +000062 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Narofffcab7932007-11-05 14:55:35 +000063 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +000064 "(struct objc_object *, struct objc_selector *, ...);\n"
65 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +000066 "(const char *);\n"
67 "extern void objc_exception_throw(struct objc_object *);\n"
68 "extern void objc_exception_try_enter(void *);\n"
69 "extern void objc_exception_try_exit(void *);\n"
70 "extern struct objc_object *objc_exception_extract(void *);\n"
71 "extern int objc_exception_match"
72 "(struct objc_class *, struct objc_object *, ...);\n";
73
Steve Naroff0744c472007-11-04 22:37:50 +000074 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
75 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +000076 }
Chris Lattner569faa62007-10-11 18:38:32 +000077
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000078 // Top Level Driver code.
79 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +000080 void HandleDeclInMainFile(Decl *D);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000081 ~RewriteTest();
82
83 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +000084 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +000085 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +000086 void RewriteTabs();
87 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +000088 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +000089 void RewriteImplementationDecl(ObjcImplementationDecl *Dcl);
90 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +000091 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +000092 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff667f1682007-10-30 13:30:57 +000093 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +000094 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +000095 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffc8a92d12007-11-01 13:24:47 +000096 void RewriteObjcQualifiedInterfaceTypes(
97 const FunctionTypeProto *proto, FunctionDecl *FD);
98 bool needToScanForQualifiers(QualType T);
Chris Lattner6fe8b272007-10-16 22:36:42 +000099
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000100 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000101 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000102 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff296b74f2007-11-05 14:50:49 +0000103 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000104 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000105 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000106 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
107 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
108 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000109 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000110 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
111 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000112 void SynthMsgSendFunctionDecl();
113 void SynthGetClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000114 void SynthCFStringFunctionDecl();
115
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000116 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000117 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
118 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000119
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000120 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
121 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000122
Steve Naroffb82c50f2007-11-11 17:19:15 +0000123 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000124 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000125 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000126 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000127 const char *ClassName,
128 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000129
130 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
131 int NumProtocols,
132 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000133 const char *ClassName,
134 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000135 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
136 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000137 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
138 ObjcIvarDecl *ivar,
139 std::string &Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000140 void WriteObjcMetaData(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000141 };
142}
143
Chris Lattner569faa62007-10-11 18:38:32 +0000144ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000145
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000146//===----------------------------------------------------------------------===//
147// Top Level Driver Code
148//===----------------------------------------------------------------------===//
149
Chris Lattner569faa62007-10-11 18:38:32 +0000150void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000151 // Two cases: either the decl could be in the main file, or it could be in a
152 // #included file. If the former, rewrite it now. If the later, check to see
153 // if we rewrote the #include/#import.
154 SourceLocation Loc = D->getLocation();
155 Loc = SM->getLogicalLoc(Loc);
156
157 // If this is for a builtin, ignore it.
158 if (Loc.isInvalid()) return;
159
Steve Naroffe9780582007-10-23 23:50:29 +0000160 // Look for built-in declarations that we need to refer during the rewrite.
161 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000162 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000163 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
164 // declared in <Foundation/NSString.h>
165 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
166 ConstantStringClassReference = FVD;
167 return;
168 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000169 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
170 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000171 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
172 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000173 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
174 RewriteProtocolDecl(PD);
Steve Naroffe9780582007-10-23 23:50:29 +0000175 }
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000176 else if (ObjcImplementationDecl *MD = dyn_cast<ObjcImplementationDecl>(D)) {
177 RewriteImplementationDecl(MD);
178 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000179 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000180 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
181 return HandleDeclInMainFile(D);
182
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000183 // Otherwise, see if there is a #import in the main file that should be
184 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000185 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000186}
187
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000188/// HandleDeclInMainFile - This is called for each top-level decl defined in the
189/// main file of the input.
190void RewriteTest::HandleDeclInMainFile(Decl *D) {
191 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
192 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000193 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000194
195 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
196 ClassImplementation.push_back(CI);
197 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
198 CategoryImplementation.push_back(CI);
199 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
200 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000201 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
202 if (VD->getInit())
203 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
204 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000205 // Nothing yet.
206}
207
208RewriteTest::~RewriteTest() {
209 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000210
211 // Rewrite tabs if we care.
212 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000213
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000214 // Rewrite Objective-c meta data*
215 std::string ResultStr;
216 WriteObjcMetaData(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000217
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000218 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
219 // we are done.
220 if (const RewriteBuffer *RewriteBuf =
221 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000222 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000223 std::string S(RewriteBuf->begin(), RewriteBuf->end());
224 printf("%s\n", S.c_str());
225 } else {
226 printf("No changes\n");
227 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000228 // Emit metadata.
229 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000230}
231
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000232//===----------------------------------------------------------------------===//
233// Syntactic (non-AST) Rewriting Code
234//===----------------------------------------------------------------------===//
235
Chris Lattner74db1682007-10-16 21:07:07 +0000236void RewriteTest::RewriteInclude(SourceLocation Loc) {
237 // Rip up the #include stack to the main file.
238 SourceLocation IncLoc = Loc, NextLoc = Loc;
239 do {
240 IncLoc = Loc;
241 Loc = SM->getLogicalLoc(NextLoc);
242 NextLoc = SM->getIncludeLoc(Loc);
243 } while (!NextLoc.isInvalid());
244
245 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
246 // IncLoc indicates the header that was included if it is useful.
247 IncLoc = SM->getLogicalLoc(IncLoc);
248 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
249 Loc == LastIncLoc)
250 return;
251 LastIncLoc = Loc;
252
253 unsigned IncCol = SM->getColumnNumber(Loc);
254 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
255
256 // Replace the #import with #include.
257 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
258}
259
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000260void RewriteTest::RewriteTabs() {
261 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
262 const char *MainBufStart = MainBuf.first;
263 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000264
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000265 // Loop over the whole file, looking for tabs.
266 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
267 if (*BufPtr != '\t')
268 continue;
269
270 // Okay, we found a tab. This tab will turn into at least one character,
271 // but it depends on which 'virtual column' it is in. Compute that now.
272 unsigned VCol = 0;
273 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
274 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
275 ++VCol;
276
277 // Okay, now that we know the virtual column, we know how many spaces to
278 // insert. We assume 8-character tab-stops.
279 unsigned Spaces = 8-(VCol & 7);
280
281 // Get the location of the tab.
282 SourceLocation TabLoc =
283 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
284
285 // Rewrite the single tab character into a sequence of spaces.
286 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
287 }
Chris Lattner569faa62007-10-11 18:38:32 +0000288}
289
290
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000291void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
292 int numDecls = ClassDecl->getNumForwardDecls();
293 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
294
295 // Get the start location and compute the semi location.
296 SourceLocation startLoc = ClassDecl->getLocation();
297 const char *startBuf = SM->getCharacterData(startLoc);
298 const char *semiPtr = strchr(startBuf, ';');
299
300 // Translate to typedef's that forward reference structs with the same name
301 // as the class. As a convenience, we include the original declaration
302 // as a comment.
303 std::string typedefString;
304 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000305 typedefString.append(startBuf, semiPtr-startBuf+1);
306 typedefString += "\n";
307 for (int i = 0; i < numDecls; i++) {
308 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff809b4f02007-10-31 22:11:35 +0000309 if (ObjcForwardDecls.count(ForwardDecl))
310 continue;
Steve Naroff2aeae312007-11-09 12:50:28 +0000311 typedefString += "#ifndef _REWRITER_typedef_";
312 typedefString += ForwardDecl->getName();
313 typedefString += "\n";
314 typedefString += "#define _REWRITER_typedef_";
315 typedefString += ForwardDecl->getName();
316 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000317 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000318 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000319 typedefString += ";\n#endif\n";
Steve Naroff809b4f02007-10-31 22:11:35 +0000320 // Mark this typedef as having been generated.
321 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +0000322 assert(false && "typedef already output");
Steve Naroff71226032007-10-24 22:48:43 +0000323 }
324
325 // Replace the @class with typedefs corresponding to the classes.
326 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
327 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000328}
329
Steve Naroff667f1682007-10-30 13:30:57 +0000330void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
331 for (int i = 0; i < nMethods; i++) {
332 ObjcMethodDecl *Method = Methods[i];
333 SourceLocation Loc = Method->getLocStart();
334
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000335 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000336
337 // FIXME: handle methods that are declared across multiple lines.
338 }
339}
340
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000341void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
342{
343 for (int i = 0; i < nProperties; i++) {
344 ObjcPropertyDecl *Property = Properties[i];
345 SourceLocation Loc = Property->getLocation();
346
347 Rewrite.ReplaceText(Loc, 0, "// ", 3);
348
349 // FIXME: handle properties that are declared across multiple lines.
350 }
351}
352
Steve Naroff667f1682007-10-30 13:30:57 +0000353void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
354 SourceLocation LocStart = CatDecl->getLocStart();
355
356 // FIXME: handle category headers that are declared across multiple lines.
357 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
358
359 RewriteMethods(CatDecl->getNumInstanceMethods(),
360 CatDecl->getInstanceMethods());
361 RewriteMethods(CatDecl->getNumClassMethods(),
362 CatDecl->getClassMethods());
363 // Lastly, comment out the @end.
364 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
365}
366
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000367void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
368 SourceLocation LocStart = PDecl->getLocStart();
369
370 // FIXME: handle protocol headers that are declared across multiple lines.
371 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
372
373 RewriteMethods(PDecl->getNumInstanceMethods(),
374 PDecl->getInstanceMethods());
375 RewriteMethods(PDecl->getNumClassMethods(),
376 PDecl->getClassMethods());
377 // Lastly, comment out the @end.
378 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
379}
380
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000381void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
382 std::string &ResultStr) {
383 ResultStr += "\nstatic ";
384 ResultStr += OMD->getResultType().getAsString();
385 ResultStr += "\n_";
386
387 // Unique method name
388 if (OMD->isInstance())
389 ResultStr += "I_";
390 else
391 ResultStr += "C_";
392
393 ResultStr += OMD->getClassInterface()->getName();
394 ResultStr += "_";
395
396 NamedDecl *MethodContext = OMD->getMethodContext();
397 if (ObjcCategoryImplDecl *CID =
398 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
399 ResultStr += CID->getName();
400 ResultStr += "_";
401 }
402 // Append selector names, replacing ':' with '_'
403 const char *selName = OMD->getSelector().getName().c_str();
404 if (!strchr(selName, ':'))
405 ResultStr += OMD->getSelector().getName();
406 else {
407 std::string selString = OMD->getSelector().getName();
408 int len = selString.size();
409 for (int i = 0; i < len; i++)
410 if (selString[i] == ':')
411 selString[i] = '_';
412 ResultStr += selString;
413 }
414
415 // Rewrite arguments
416 ResultStr += "(";
417
418 // invisible arguments
419 if (OMD->isInstance()) {
420 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
421 selfTy = Context->getPointerType(selfTy);
422 ResultStr += selfTy.getAsString();
423 }
424 else
425 ResultStr += Context->getObjcIdType().getAsString();
426
427 ResultStr += " self, ";
428 ResultStr += Context->getObjcSelType().getAsString();
429 ResultStr += " _cmd";
430
431 // Method arguments.
432 for (int i = 0; i < OMD->getNumParams(); i++) {
433 ParmVarDecl *PDecl = OMD->getParamDecl(i);
434 ResultStr += ", ";
435 ResultStr += PDecl->getType().getAsString();
436 ResultStr += " ";
437 ResultStr += PDecl->getName();
438 }
439 ResultStr += ")";
440
441}
442void RewriteTest::RewriteImplementationDecl(ObjcImplementationDecl *OID) {
443
444 Rewrite.InsertText(OID->getLocStart(), "// ", 3);
445
446 for (int i = 0; i < OID->getNumInstanceMethods(); i++) {
447 std::string ResultStr;
448 ObjcMethodDecl *OMD = OID->getInstanceMethods()[i];
449 RewriteObjcMethodDecl(OMD, ResultStr);
450 SourceLocation LocStart = OMD->getLocStart();
451 SourceLocation LocEnd = OMD->getBody()->getLocStart();
452
453 const char *startBuf = SM->getCharacterData(LocStart);
454 const char *endBuf = SM->getCharacterData(LocEnd);
455 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
456 ResultStr.c_str(), ResultStr.size());
457 }
458
459 for (int i = 0; i < OID->getNumClassMethods(); i++) {
460 std::string ResultStr;
461 ObjcMethodDecl *OMD = OID->getClassMethods()[i];
462 RewriteObjcMethodDecl(OMD, ResultStr);
463 SourceLocation LocStart = OMD->getLocStart();
464 SourceLocation LocEnd = OMD->getBody()->getLocStart();
465
466 const char *startBuf = SM->getCharacterData(LocStart);
467 const char *endBuf = SM->getCharacterData(LocEnd);
468 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
469 ResultStr.c_str(), ResultStr.size());
470 }
471 Rewrite.InsertText(OID->getLocEnd(), "// ", 3);
472}
473
Steve Naroff3774dd92007-10-26 20:53:56 +0000474void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000475
476 SourceLocation LocStart = ClassDecl->getLocStart();
477 SourceLocation LocEnd = ClassDecl->getLocEnd();
478
479 const char *startBuf = SM->getCharacterData(LocStart);
480 const char *endBuf = SM->getCharacterData(LocEnd);
481
Steve Naroff1ccf4632007-10-30 03:43:13 +0000482 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Naroffef20ed32007-10-30 02:23:23 +0000483
484 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000485 if (!ObjcForwardDecls.count(ClassDecl)) {
486 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2aeae312007-11-09 12:50:28 +0000487 ResultStr += "#ifndef _REWRITER_typedef_";
488 ResultStr += ClassDecl->getName();
489 ResultStr += "\n";
490 ResultStr += "#define _REWRITER_typedef_";
491 ResultStr += ClassDecl->getName();
492 ResultStr += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000493 ResultStr += "typedef struct objc_object ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000494 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000495 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000496
497 // Mark this typedef as having been generated.
498 ObjcForwardDecls.insert(ClassDecl);
499 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000500 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
501
Steve Naroff1ccf4632007-10-30 03:43:13 +0000502 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Naroffef20ed32007-10-30 02:23:23 +0000503 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000504 RewriteProperties(ClassDecl->getNumPropertyDecl(),
505 ClassDecl->getPropertyDecl());
Steve Naroff667f1682007-10-30 13:30:57 +0000506 RewriteMethods(ClassDecl->getNumInstanceMethods(),
507 ClassDecl->getInstanceMethods());
508 RewriteMethods(ClassDecl->getNumClassMethods(),
509 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000510
Steve Naroff1ccf4632007-10-30 03:43:13 +0000511 // Lastly, comment out the @end.
512 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000513}
514
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000515//===----------------------------------------------------------------------===//
516// Function Body / Expression rewriting
517//===----------------------------------------------------------------------===//
518
Steve Naroff334fbc22007-11-09 15:20:18 +0000519Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000520 // Otherwise, just rewrite all children.
521 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
522 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000523 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000524 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000525 if (newStmt)
526 *CI = newStmt;
527 }
Steve Naroffe9780582007-10-23 23:50:29 +0000528
529 // Handle specific things.
530 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
531 return RewriteAtEncode(AtEncode);
Steve Naroff296b74f2007-11-05 14:50:49 +0000532
533 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
534 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000535
536 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
537 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000538
Steve Naroff71226032007-10-24 22:48:43 +0000539 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
540 // Before we rewrite it, put the original message expression in a comment.
541 SourceLocation startLoc = MessExpr->getLocStart();
542 SourceLocation endLoc = MessExpr->getLocEnd();
543
544 const char *startBuf = SM->getCharacterData(startLoc);
545 const char *endBuf = SM->getCharacterData(endLoc);
546
547 std::string messString;
548 messString += "// ";
549 messString.append(startBuf, endBuf-startBuf+1);
550 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000551
Steve Naroff71226032007-10-24 22:48:43 +0000552 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
553 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
554 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000555 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000556 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000557 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000558
559 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
560 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000561
562 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
563 return RewriteObjcThrowStmt(StmtThrow);
564
Chris Lattner0021f452007-10-24 16:57:36 +0000565 // Return this stmt unmodified.
566 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000567}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000568
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000569Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000570 // Get the start location and compute the semi location.
571 SourceLocation startLoc = S->getLocStart();
572 const char *startBuf = SM->getCharacterData(startLoc);
573
574 assert((*startBuf == '@') && "bogus @try location");
575
576 std::string buf;
577 // declare a new scope with two variables, _stack and _rethrow.
578 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
579 buf += "int buf[18/*32-bit i386*/];\n";
580 buf += "char *pointers[4];} _stack;\n";
581 buf += "id volatile _rethrow = 0;\n";
582 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000583 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000584
585 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
586
587 startLoc = S->getTryBody()->getLocEnd();
588 startBuf = SM->getCharacterData(startLoc);
589
590 assert((*startBuf == '}') && "bogus @try block");
591
592 SourceLocation lastCurlyLoc = startLoc;
593
594 startLoc = startLoc.getFileLocWithOffset(1);
595 buf = " /* @catch begin */ else {\n";
596 buf += " id _caught = objc_exception_extract(&_stack);\n";
597 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000598 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000599 buf += " _rethrow = objc_exception_extract(&_stack);\n";
600 buf += " else { /* @catch continue */";
601
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000602 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000603
604 bool sawIdTypedCatch = false;
605 Stmt *lastCatchBody = 0;
606 ObjcAtCatchStmt *catchList = S->getCatchStmts();
607 while (catchList) {
608 Stmt *catchStmt = catchList->getCatchParamStmt();
609
610 if (catchList == S->getCatchStmts())
611 buf = "if ("; // we are generating code for the first catch clause
612 else
613 buf = "else if (";
614 startLoc = catchList->getLocStart();
615 startBuf = SM->getCharacterData(startLoc);
616
617 assert((*startBuf == '@') && "bogus @catch location");
618
619 const char *lParenLoc = strchr(startBuf, '(');
620
621 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
622 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
623 if (t == Context->getObjcIdType()) {
624 buf += "1) { ";
625 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
626 buf.c_str(), buf.size());
627 sawIdTypedCatch = true;
628 } else if (const PointerType *pType = t->getAsPointerType()) {
629 ObjcInterfaceType *cls; // Should be a pointer to a class.
630
631 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
632 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000633 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000634 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000635 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000636 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
637 buf.c_str(), buf.size());
638 }
639 }
640 // Now rewrite the body...
641 lastCatchBody = catchList->getCatchBody();
642 SourceLocation rParenLoc = catchList->getRParenLoc();
643 SourceLocation bodyLoc = lastCatchBody->getLocStart();
644 const char *bodyBuf = SM->getCharacterData(bodyLoc);
645 const char *rParenBuf = SM->getCharacterData(rParenLoc);
646 assert((*rParenBuf == ')') && "bogus @catch paren location");
647 assert((*bodyBuf == '{') && "bogus @catch body location");
648
649 buf = " = _caught;";
650 // Here we replace ") {" with "= _caught;" (which initializes and
651 // declares the @catch parameter).
652 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
653 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000654 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000655 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000656 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000657 catchList = catchList->getNextCatchStmt();
658 }
659 // Complete the catch list...
660 if (lastCatchBody) {
661 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
662 const char *bodyBuf = SM->getCharacterData(bodyLoc);
663 assert((*bodyBuf == '}') && "bogus @catch body location");
664 bodyLoc = bodyLoc.getFileLocWithOffset(1);
665 buf = " } } /* @catch end */\n";
666
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000667 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000668
669 // Set lastCurlyLoc
670 lastCurlyLoc = lastCatchBody->getLocEnd();
671 }
672 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
673 startLoc = finalStmt->getLocStart();
674 startBuf = SM->getCharacterData(startLoc);
675 assert((*startBuf == '@') && "bogus @finally start");
676
677 buf = "/* @finally */";
678 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
679
680 Stmt *body = finalStmt->getFinallyBody();
681 SourceLocation startLoc = body->getLocStart();
682 SourceLocation endLoc = body->getLocEnd();
683 const char *startBuf = SM->getCharacterData(startLoc);
684 const char *endBuf = SM->getCharacterData(endLoc);
685 assert((*startBuf == '{') && "bogus @finally body location");
686 assert((*endBuf == '}') && "bogus @finally body location");
687
688 startLoc = startLoc.getFileLocWithOffset(1);
689 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000690 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000691 endLoc = endLoc.getFileLocWithOffset(-1);
692 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000693 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000694
695 // Set lastCurlyLoc
696 lastCurlyLoc = body->getLocEnd();
697 }
698 // Now emit the final closing curly brace...
699 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
700 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000701 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000702 return 0;
703}
704
705Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
706 return 0;
707}
708
709Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
710 return 0;
711}
712
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000713// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
714// the throw expression is typically a message expression that's already
715// been rewritten! (which implies the SourceLocation's are invalid).
716Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
717 // Get the start location and compute the semi location.
718 SourceLocation startLoc = S->getLocStart();
719 const char *startBuf = SM->getCharacterData(startLoc);
720
721 assert((*startBuf == '@') && "bogus @throw location");
722
723 std::string buf;
724 /* void objc_exception_throw(id) __attribute__((noreturn)); */
725 buf = "objc_exception_throw(";
726 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
727 const char *semiBuf = strchr(startBuf, ';');
728 assert((*semiBuf == ';') && "@throw: can't find ';'");
729 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
730 buf = ");";
731 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
732 return 0;
733}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000734
Chris Lattner0021f452007-10-24 16:57:36 +0000735Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000736 // Create a new string expression.
737 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000738 std::string StrEncoding;
739 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
740 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
741 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000742 SourceLocation(), SourceLocation());
743 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattner0021f452007-10-24 16:57:36 +0000744 delete Exp;
745 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000746}
747
Steve Naroff296b74f2007-11-05 14:50:49 +0000748Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
749 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
750 // Create a call to sel_registerName("selName").
751 llvm::SmallVector<Expr*, 8> SelExprs;
752 QualType argType = Context->getPointerType(Context->CharTy);
753 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
754 Exp->getSelector().getName().size(),
755 false, argType, SourceLocation(),
756 SourceLocation()));
757 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
758 &SelExprs[0], SelExprs.size());
759 Rewrite.ReplaceStmt(Exp, SelExp);
760 delete Exp;
761 return SelExp;
762}
763
Steve Naroff71226032007-10-24 22:48:43 +0000764CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
765 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000766 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000767 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000768
769 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000770 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000771
772 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000773 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000774 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
775
776 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000777
Steve Naroff71226032007-10-24 22:48:43 +0000778 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
779}
780
Steve Naroffc8a92d12007-11-01 13:24:47 +0000781static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
782 const char *&startRef, const char *&endRef) {
783 while (startBuf < endBuf) {
784 if (*startBuf == '<')
785 startRef = startBuf; // mark the start.
786 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000787 if (startRef && *startRef == '<') {
788 endRef = startBuf; // mark the end.
789 return true;
790 }
791 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000792 }
793 startBuf++;
794 }
795 return false;
796}
797
798bool RewriteTest::needToScanForQualifiers(QualType T) {
799 // FIXME: we don't currently represent "id <Protocol>" in the type system.
800 if (T == Context->getObjcIdType())
801 return true;
802
803 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000804 Type *pointeeType = pType->getPointeeType().getTypePtr();
805 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
806 return true; // we have "Class <Protocol> *".
807 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000808 return false;
809}
810
811void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
812 const FunctionTypeProto *proto, FunctionDecl *FD) {
813
814 if (needToScanForQualifiers(proto->getResultType())) {
815 // Since types are unique, we need to scan the buffer.
816 SourceLocation Loc = FD->getLocation();
817
818 const char *endBuf = SM->getCharacterData(Loc);
819 const char *startBuf = endBuf;
820 while (*startBuf != ';')
821 startBuf--; // scan backward (from the decl location) for return type.
822 const char *startRef = 0, *endRef = 0;
823 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
824 // Get the locations of the startRef, endRef.
825 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
826 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
827 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000828 Rewrite.InsertText(LessLoc, "/*", 2);
829 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +0000830 }
831 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000832 // Now check arguments.
833 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
834 if (needToScanForQualifiers(proto->getArgType(i))) {
835 // Since types are unique, we need to scan the buffer.
836 SourceLocation Loc = FD->getLocation();
837
838 const char *startBuf = SM->getCharacterData(Loc);
839 const char *endBuf = startBuf;
840 while (*endBuf != ';')
841 endBuf++; // scan forward (from the decl location) for argument types.
842 const char *startRef = 0, *endRef = 0;
843 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
844 // Get the locations of the startRef, endRef.
845 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
846 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
847 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000848 Rewrite.InsertText(LessLoc, "/*", 2);
849 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000850 }
851 }
852 }
Steve Naroff05d6ff52007-10-31 04:38:33 +0000853}
854
Steve Naroff02a82aa2007-10-30 23:14:51 +0000855void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
856 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +0000857 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000858 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +0000859 return;
860 }
861 // Check for ObjC 'id' and class types that have been adorned with protocol
862 // information (id<p>, C<p>*). The protocol references need to be rewritten!
863 const FunctionType *funcType = FD->getType()->getAsFunctionType();
864 assert(funcType && "missing function type");
Steve Naroffc8a92d12007-11-01 13:24:47 +0000865 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
866 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000867}
868
869// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
870void RewriteTest::SynthMsgSendFunctionDecl() {
871 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
872 llvm::SmallVector<QualType, 16> ArgTys;
873 QualType argT = Context->getObjcIdType();
874 assert(!argT.isNull() && "Can't find 'id' type");
875 ArgTys.push_back(argT);
876 argT = Context->getObjcSelType();
877 assert(!argT.isNull() && "Can't find 'SEL' type");
878 ArgTys.push_back(argT);
879 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
880 &ArgTys[0], ArgTys.size(),
881 true /*isVariadic*/);
882 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
883 msgSendIdent, msgSendType,
884 FunctionDecl::Extern, false, 0);
885}
886
887// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
888void RewriteTest::SynthGetClassFunctionDecl() {
889 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
890 llvm::SmallVector<QualType, 16> ArgTys;
891 ArgTys.push_back(Context->getPointerType(
892 Context->CharTy.getQualifiedType(QualType::Const)));
893 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
894 &ArgTys[0], ArgTys.size(),
895 false /*isVariadic*/);
896 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
897 getClassIdent, getClassType,
898 FunctionDecl::Extern, false, 0);
899}
900
Steve Naroffabb96362007-11-08 14:30:50 +0000901// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
902void RewriteTest::SynthCFStringFunctionDecl() {
903 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
904 llvm::SmallVector<QualType, 16> ArgTys;
905 ArgTys.push_back(Context->getPointerType(
906 Context->CharTy.getQualifiedType(QualType::Const)));
907 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
908 &ArgTys[0], ArgTys.size(),
909 false /*isVariadic*/);
910 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
911 getClassIdent, getClassType,
912 FunctionDecl::Extern, false, 0);
913}
914
Steve Naroff0add5d22007-11-03 11:27:19 +0000915Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +0000916#if 1
917 // This rewrite is specific to GCC, which has builtin support for CFString.
918 if (!CFStringFunctionDecl)
919 SynthCFStringFunctionDecl();
920 // Create a call to __builtin___CFStringMakeConstantString("cstr").
921 llvm::SmallVector<Expr*, 8> StrExpr;
922 StrExpr.push_back(Exp->getString());
923 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
924 &StrExpr[0], StrExpr.size());
925 // cast to NSConstantString *
926 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
927 Rewrite.ReplaceStmt(Exp, cast);
928 delete Exp;
929 return cast;
930#else
Steve Naroff0add5d22007-11-03 11:27:19 +0000931 assert(ConstantStringClassReference && "Can't find constant string reference");
932 llvm::SmallVector<Expr*, 4> InitExprs;
933
934 // Synthesize "(Class)&_NSConstantStringClassReference"
935 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
936 ConstantStringClassReference->getType(),
937 SourceLocation());
938 QualType expType = Context->getPointerType(ClsRef->getType());
939 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
940 expType, SourceLocation());
941 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
942 SourceLocation());
943 InitExprs.push_back(cast); // set the 'isa'.
944 InitExprs.push_back(Exp->getString()); // set "char *bytes".
945 unsigned IntSize = static_cast<unsigned>(
946 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
947 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
948 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
949 Exp->getLocStart());
950 InitExprs.push_back(len); // set "int numBytes".
951
952 // struct NSConstantString
953 QualType CFConstantStrType = Context->getCFConstantStringType();
954 // (struct NSConstantString) { <exprs from above> }
955 InitListExpr *ILE = new InitListExpr(SourceLocation(),
956 &InitExprs[0], InitExprs.size(),
957 SourceLocation());
958 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
959 // struct NSConstantString *
960 expType = Context->getPointerType(StrRep->getType());
961 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
962 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +0000963 // cast to NSConstantString *
964 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +0000965 Rewrite.ReplaceStmt(Exp, cast);
966 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +0000967 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +0000968#endif
Steve Naroff0add5d22007-11-03 11:27:19 +0000969}
970
Steve Naroff71226032007-10-24 22:48:43 +0000971Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000972 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff02a82aa2007-10-30 23:14:51 +0000973 if (!MsgSendFunctionDecl)
974 SynthMsgSendFunctionDecl();
975 if (!GetClassFunctionDecl)
976 SynthGetClassFunctionDecl();
Steve Naroff71226032007-10-24 22:48:43 +0000977
978 // Synthesize a call to objc_msgSend().
979 llvm::SmallVector<Expr*, 8> MsgExprs;
980 IdentifierInfo *clsName = Exp->getClassName();
981
982 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
983 if (clsName) { // class message.
984 llvm::SmallVector<Expr*, 8> ClsExprs;
985 QualType argType = Context->getPointerType(Context->CharTy);
986 ClsExprs.push_back(new StringLiteral(clsName->getName(),
987 clsName->getLength(),
988 false, argType, SourceLocation(),
989 SourceLocation()));
990 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
991 &ClsExprs[0], ClsExprs.size());
992 MsgExprs.push_back(Cls);
993 } else // instance message.
994 MsgExprs.push_back(Exp->getReceiver());
995
Steve Naroff0add5d22007-11-03 11:27:19 +0000996 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +0000997 llvm::SmallVector<Expr*, 8> SelExprs;
998 QualType argType = Context->getPointerType(Context->CharTy);
999 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1000 Exp->getSelector().getName().size(),
1001 false, argType, SourceLocation(),
1002 SourceLocation()));
1003 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1004 &SelExprs[0], SelExprs.size());
1005 MsgExprs.push_back(SelExp);
1006
1007 // Now push any user supplied arguments.
1008 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1009 MsgExprs.push_back(Exp->getArg(i));
1010 // We've transferred the ownership to MsgExprs. Null out the argument in
1011 // the original expression, since we will delete it below.
1012 Exp->setArg(i, 0);
1013 }
Steve Naroff0744c472007-11-04 22:37:50 +00001014 // Generate the funky cast.
1015 CastExpr *cast;
1016 llvm::SmallVector<QualType, 8> ArgTypes;
1017 QualType returnType;
1018
1019 // Push 'id' and 'SEL', the 2 implicit arguments.
1020 ArgTypes.push_back(Context->getObjcIdType());
1021 ArgTypes.push_back(Context->getObjcSelType());
1022 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1023 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001024 for (int i = 0; i < mDecl->getNumParams(); i++) {
1025 QualType t = mDecl->getParamDecl(i)->getType();
1026 if (t == Context->getObjcClassType())
1027 t = Context->getObjcIdType(); // Convert "Class"->"id"
1028 ArgTypes.push_back(t);
1029 }
Steve Naroff0744c472007-11-04 22:37:50 +00001030 returnType = mDecl->getResultType();
1031 } else {
1032 returnType = Context->getObjcIdType();
1033 }
1034 // Get the type, we will need to reference it in a couple spots.
1035 QualType msgSendType = MsgSendFunctionDecl->getType();
1036
1037 // Create a reference to the objc_msgSend() declaration.
1038 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1039
1040 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1041 // If we don't do this cast, we get the following bizarre warning/note:
1042 // xx.m:13: warning: function called through a non-compatible type
1043 // xx.m:13: note: if this code is reached, the program will abort
1044 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1045 SourceLocation());
1046
1047 // Now do the "normal" pointer to function cast.
1048 QualType castType = Context->getFunctionType(returnType,
1049 &ArgTypes[0], ArgTypes.size(),
1050 false/*FIXME:variadic*/);
1051 castType = Context->getPointerType(castType);
1052 cast = new CastExpr(castType, cast, SourceLocation());
1053
1054 // Don't forget the parens to enforce the proper binding.
1055 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1056
1057 const FunctionType *FT = msgSendType->getAsFunctionType();
1058 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1059 FT->getResultType(), SourceLocation());
Steve Naroff71226032007-10-24 22:48:43 +00001060 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001061 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001062
Chris Lattner0021f452007-10-24 16:57:36 +00001063 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001064 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001065}
1066
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001067/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1068/// an objective-c class with ivars.
1069void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1070 std::string &Result) {
1071 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1072 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001073 // Do not synthesize more than once.
1074 if (ObjcSynthesizedStructs.count(CDecl))
1075 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001076 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1077 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1078 // Do it for the root
1079 SynthesizeObjcInternalStruct(RCDecl, Result);
1080 }
1081
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001082 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001083 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanian2fd0daa2007-10-31 23:53:01 +00001084 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001085 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1086 return;
1087
Steve Naroffb1147382007-11-01 17:12:31 +00001088 Result += "\nstruct ";
1089 Result += CDecl->getName();
1090 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1091 Result += " {\n struct ";
1092 Result += RCDecl->getName();
1093 Result += " _";
1094 Result += RCDecl->getName();
1095 Result += ";\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001096 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001097 else
1098 Result += " {";
Steve Naroff809b4f02007-10-31 22:11:35 +00001099
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001100 if (NumIvars > 0) {
1101 SourceLocation LocStart = CDecl->getLocStart();
1102 SourceLocation LocEnd = CDecl->getLocEnd();
1103
1104 const char *startBuf = SM->getCharacterData(LocStart);
1105 const char *endBuf = SM->getCharacterData(LocEnd);
1106 startBuf = strchr(startBuf, '{');
1107 assert((startBuf && endBuf)
1108 && "SynthesizeObjcInternalStruct - malformed @interface");
1109 startBuf++; // past '{'
1110 while (startBuf < endBuf) {
1111 if (*startBuf == '@') {
1112 startBuf = strchr(startBuf, 'p');
1113 // FIXME: presence of @public, etc. inside comment results in
1114 // this transformation as well, which is still correct c-code.
1115 if (!strncmp(startBuf, "public", strlen("public"))) {
1116 startBuf += strlen("public");
1117 Result += "/* @public */";
1118 }
1119 else if (!strncmp(startBuf, "private", strlen("private"))) {
1120 startBuf += strlen("private");
1121 Result += "/* @private */";
1122 }
1123 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1124 startBuf += strlen("protected");
1125 Result += "/* @protected */";
1126 }
1127 }
1128 Result += *startBuf++;
1129 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001130 }
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001131
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001132 Result += "};\n";
1133 // Mark this struct as having been generated.
1134 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001135 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001136}
1137
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001138// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1139/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001140void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001141 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001142 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001143 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001144 const char *ClassName,
1145 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001146 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001147 if (NumMethods > 0 && !objc_impl_method) {
1148 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001149 SEL _cmd;
1150 char *method_types;
1151 void *_imp;
1152 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001153 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001154 Result += "\nstruct _objc_method {\n";
1155 Result += "\tSEL _cmd;\n";
1156 Result += "\tchar *method_types;\n";
1157 Result += "\tvoid *_imp;\n";
1158 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001159
1160 /* struct _objc_method_list {
1161 struct _objc_method_list *next_method;
1162 int method_count;
1163 struct _objc_method method_list[];
1164 }
1165 */
1166 Result += "\nstruct _objc_method_list {\n";
1167 Result += "\tstruct _objc_method_list *next_method;\n";
1168 Result += "\tint method_count;\n";
1169 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001170 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001171 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001172 // Build _objc_method_list for class's methods if needed
1173 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001174 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001175 Result += prefix;
1176 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1177 Result += "_METHODS_";
1178 Result += ClassName;
1179 Result += " __attribute__ ((section (\"__OBJC, __";
1180 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001181 Result += "_meth\")))= ";
1182 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1183
1184 Result += "\t,{{(SEL)\"";
1185 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001186 std::string MethodTypeString;
1187 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1188 Result += "\", \"";
1189 Result += MethodTypeString;
1190 Result += "\", 0}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001191 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001192 // TODO: Need method address as 3rd initializer.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001193 Result += "\t ,{(SEL)\"";
1194 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001195 std::string MethodTypeString;
1196 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1197 Result += "\", \"";
1198 Result += MethodTypeString;
1199 Result += "\", 0}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001200 }
1201 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001202 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001203}
1204
1205/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1206void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1207 int NumProtocols,
1208 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001209 const char *ClassName,
1210 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001211 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001212 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001213 for (int i = 0; i < NumProtocols; i++) {
1214 ObjcProtocolDecl *PDecl = Protocols[i];
1215 // Output struct protocol_methods holder of method selector and type.
1216 if (!objc_protocol_methods &&
1217 (PDecl->getNumInstanceMethods() > 0
1218 || PDecl->getNumClassMethods() > 0)) {
1219 /* struct protocol_methods {
1220 SEL _cmd;
1221 char *method_types;
1222 }
1223 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001224 Result += "\nstruct protocol_methods {\n";
1225 Result += "\tSEL _cmd;\n";
1226 Result += "\tchar *method_types;\n";
1227 Result += "};\n";
1228
1229 /* struct _objc_protocol_method_list {
1230 int protocol_method_count;
1231 struct protocol_methods protocols[];
1232 }
1233 */
1234 Result += "\nstruct _objc_protocol_method_list {\n";
1235 Result += "\tint protocol_method_count;\n";
1236 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001237 objc_protocol_methods = true;
1238 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001239
Fariborz Jahanian04455192007-10-22 21:41:37 +00001240 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001241 int NumMethods = PDecl->getNumInstanceMethods();
1242 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001243 Result += "\nstatic struct _objc_protocol_method_list "
1244 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1245 Result += PDecl->getName();
1246 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1247 "{\n\t" + utostr(NumMethods) + "\n";
1248
Fariborz Jahanian04455192007-10-22 21:41:37 +00001249 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001250 Result += "\t,{{(SEL)\"";
1251 Result += Methods[0]->getSelector().getName().c_str();
1252 Result += "\", \"\"}\n";
1253
1254 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001255 Result += "\t ,{(SEL)\"";
1256 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001257 std::string MethodTypeString;
1258 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1259 Result += "\", \"";
1260 Result += MethodTypeString;
1261 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001262 }
1263 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001264 }
1265
1266 // Output class methods declared in this protocol.
1267 NumMethods = PDecl->getNumClassMethods();
1268 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001269 Result += "\nstatic struct _objc_protocol_method_list "
1270 "_OBJC_PROTOCOL_CLASS_METHODS_";
1271 Result += PDecl->getName();
1272 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1273 "{\n\t";
1274 Result += utostr(NumMethods);
1275 Result += "\n";
1276
Fariborz Jahanian04455192007-10-22 21:41:37 +00001277 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001278 Result += "\t,{{(SEL)\"";
1279 Result += Methods[0]->getSelector().getName().c_str();
1280 Result += "\", \"\"}\n";
1281
1282 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001283 Result += "\t ,{(SEL)\"";
1284 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001285 std::string MethodTypeString;
1286 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1287 Result += "\", \"";
1288 Result += MethodTypeString;
1289 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001290 }
1291 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001292 }
1293 // Output:
1294 /* struct _objc_protocol {
1295 // Objective-C 1.0 extensions
1296 struct _objc_protocol_extension *isa;
1297 char *protocol_name;
1298 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001299 struct _objc_protocol_method_list *instance_methods;
1300 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001301 };
1302 */
1303 static bool objc_protocol = false;
1304 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001305 Result += "\nstruct _objc_protocol {\n";
1306 Result += "\tstruct _objc_protocol_extension *isa;\n";
1307 Result += "\tchar *protocol_name;\n";
1308 Result += "\tstruct _objc_protocol **protocol_list;\n";
1309 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1310 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1311 Result += "};\n";
1312
1313 /* struct _objc_protocol_list {
1314 struct _objc_protocol_list *next;
1315 int protocol_count;
1316 struct _objc_protocol *class_protocols[];
1317 }
1318 */
1319 Result += "\nstruct _objc_protocol_list {\n";
1320 Result += "\tstruct _objc_protocol_list *next;\n";
1321 Result += "\tint protocol_count;\n";
1322 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1323 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001324 objc_protocol = true;
1325 }
1326
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001327 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1328 Result += PDecl->getName();
1329 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1330 "{\n\t0, \"";
1331 Result += PDecl->getName();
1332 Result += "\", 0, ";
1333 if (PDecl->getInstanceMethods() > 0) {
1334 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1335 Result += PDecl->getName();
1336 Result += ", ";
1337 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001338 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001339 Result += "0, ";
1340 if (PDecl->getClassMethods() > 0) {
1341 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1342 Result += PDecl->getName();
1343 Result += "\n";
1344 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001345 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001346 Result += "0\n";
1347 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001348 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001349 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001350 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1351 Result += prefix;
1352 Result += "_PROTOCOLS_";
1353 Result += ClassName;
1354 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1355 "{\n\t0, ";
1356 Result += utostr(NumProtocols);
1357 Result += "\n";
1358
1359 Result += "\t,{&_OBJC_PROTOCOL_";
1360 Result += Protocols[0]->getName();
1361 Result += " \n";
1362
1363 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001364 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001365 Result += "\t ,&_OBJC_PROTOCOL_";
1366 Result += PDecl->getName();
1367 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001368 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001369 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001370 }
1371}
1372
1373/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1374/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001375void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1376 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001377 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1378 // Find category declaration for this implementation.
1379 ObjcCategoryDecl *CDecl;
1380 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1381 CDecl = CDecl->getNextClassCategory())
1382 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1383 break;
1384 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1385
1386 char *FullCategoryName = (char*)alloca(
1387 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1388 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1389
1390 // Build _objc_method_list for class's instance methods if needed
1391 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1392 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001393 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001394 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001395
1396 // Build _objc_method_list for class's class methods if needed
1397 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1398 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001399 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001400 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001401
1402 // Protocols referenced in class declaration?
1403 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1404 CDecl->getNumReferencedProtocols(),
1405 "CATEGORY",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001406 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001407
1408 /* struct _objc_category {
1409 char *category_name;
1410 char *class_name;
1411 struct _objc_method_list *instance_methods;
1412 struct _objc_method_list *class_methods;
1413 struct _objc_protocol_list *protocols;
1414 // Objective-C 1.0 extensions
1415 uint32_t size; // sizeof (struct _objc_category)
1416 struct _objc_property_list *instance_properties; // category's own
1417 // @property decl.
1418 };
1419 */
1420
1421 static bool objc_category = false;
1422 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001423 Result += "\nstruct _objc_category {\n";
1424 Result += "\tchar *category_name;\n";
1425 Result += "\tchar *class_name;\n";
1426 Result += "\tstruct _objc_method_list *instance_methods;\n";
1427 Result += "\tstruct _objc_method_list *class_methods;\n";
1428 Result += "\tstruct _objc_protocol_list *protocols;\n";
1429 Result += "\tunsigned int size;\n";
1430 Result += "\tstruct _objc_property_list *instance_properties;\n";
1431 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001432 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001433 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001434 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1435 Result += FullCategoryName;
1436 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1437 Result += IDecl->getName();
1438 Result += "\"\n\t, \"";
1439 Result += ClassDecl->getName();
1440 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001441
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001442 if (IDecl->getNumInstanceMethods() > 0) {
1443 Result += "\t, (struct _objc_method_list *)"
1444 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1445 Result += FullCategoryName;
1446 Result += "\n";
1447 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001448 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001449 Result += "\t, 0\n";
1450 if (IDecl->getNumClassMethods() > 0) {
1451 Result += "\t, (struct _objc_method_list *)"
1452 "&_OBJC_CATEGORY_CLASS_METHODS_";
1453 Result += FullCategoryName;
1454 Result += "\n";
1455 }
1456 else
1457 Result += "\t, 0\n";
1458
1459 if (CDecl->getNumReferencedProtocols() > 0) {
1460 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1461 Result += FullCategoryName;
1462 Result += "\n";
1463 }
1464 else
1465 Result += "\t, 0\n";
1466 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001467}
1468
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001469/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1470/// ivar offset.
1471void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1472 ObjcIvarDecl *ivar,
1473 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001474 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001475 Result += IDecl->getName();
1476 Result += ", ";
1477 Result += ivar->getName();
1478 Result += ")";
1479}
1480
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001481//===----------------------------------------------------------------------===//
1482// Meta Data Emission
1483//===----------------------------------------------------------------------===//
1484
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001485void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1486 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001487 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1488
1489 // Build _objc_ivar_list metadata for classes ivars if needed
1490 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1491 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001492 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001493
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001494 SynthesizeObjcInternalStruct(CDecl, Result);
1495
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001496 if (NumIvars > 0) {
1497 static bool objc_ivar = false;
1498 if (!objc_ivar) {
1499 /* struct _objc_ivar {
1500 char *ivar_name;
1501 char *ivar_type;
1502 int ivar_offset;
1503 };
1504 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001505 Result += "\nstruct _objc_ivar {\n";
1506 Result += "\tchar *ivar_name;\n";
1507 Result += "\tchar *ivar_type;\n";
1508 Result += "\tint ivar_offset;\n";
1509 Result += "};\n";
1510
1511 /* struct _objc_ivar_list {
1512 int ivar_count;
1513 struct _objc_ivar ivar_list[];
1514 };
1515 */
1516 Result += "\nstruct _objc_ivar_list {\n";
1517 Result += "\tint ivar_count;\n";
1518 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001519 objc_ivar = true;
1520 }
1521
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001522 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1523 Result += IDecl->getName();
1524 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1525 "{\n\t";
1526 Result += utostr(NumIvars);
1527 Result += "\n";
1528
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001529 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1530 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001531 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001532 Result += "\t,{{\"";
1533 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001534 Result += "\", \"";
1535 std::string StrEncoding;
1536 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1537 Result += StrEncoding;
1538 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001539 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1540 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001541 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001542 Result += "\t ,{\"";
1543 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00001544 Result += "\", \"";
1545 std::string StrEncoding;
1546 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1547 Result += StrEncoding;
1548 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001549 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1550 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001551 }
1552
1553 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001554 }
1555
1556 // Build _objc_method_list for class's instance methods if needed
1557 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1558 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001559 true,
1560 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001561
1562 // Build _objc_method_list for class's class methods if needed
1563 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001564 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001565 false,
1566 "", IDecl->getName(), Result);
1567
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001568 // Protocols referenced in class declaration?
1569 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1570 CDecl->getNumIntfRefProtocols(),
1571 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001572 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001573
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001574
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001575 // Declaration of class/meta-class metadata
1576 /* struct _objc_class {
1577 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001578 const char *super_class_name;
1579 char *name;
1580 long version;
1581 long info;
1582 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001583 struct _objc_ivar_list *ivars;
1584 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001585 struct objc_cache *cache;
1586 struct objc_protocol_list *protocols;
1587 const char *ivar_layout;
1588 struct _objc_class_ext *ext;
1589 };
1590 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001591 static bool objc_class = false;
1592 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001593 Result += "\nstruct _objc_class {\n";
1594 Result += "\tstruct _objc_class *isa;\n";
1595 Result += "\tconst char *super_class_name;\n";
1596 Result += "\tchar *name;\n";
1597 Result += "\tlong version;\n";
1598 Result += "\tlong info;\n";
1599 Result += "\tlong instance_size;\n";
1600 Result += "\tstruct _objc_ivar_list *ivars;\n";
1601 Result += "\tstruct _objc_method_list *methods;\n";
1602 Result += "\tstruct objc_cache *cache;\n";
1603 Result += "\tstruct _objc_protocol_list *protocols;\n";
1604 Result += "\tconst char *ivar_layout;\n";
1605 Result += "\tstruct _objc_class_ext *ext;\n";
1606 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001607 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001608 }
1609
1610 // Meta-class metadata generation.
1611 ObjcInterfaceDecl *RootClass = 0;
1612 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1613 while (SuperClass) {
1614 RootClass = SuperClass;
1615 SuperClass = SuperClass->getSuperClass();
1616 }
1617 SuperClass = CDecl->getSuperClass();
1618
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001619 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1620 Result += CDecl->getName();
1621 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1622 "{\n\t(struct _objc_class *)\"";
1623 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1624 Result += "\"";
1625
1626 if (SuperClass) {
1627 Result += ", \"";
1628 Result += SuperClass->getName();
1629 Result += "\", \"";
1630 Result += CDecl->getName();
1631 Result += "\"";
1632 }
1633 else {
1634 Result += ", 0, \"";
1635 Result += CDecl->getName();
1636 Result += "\"";
1637 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001638 // TODO: 'ivars' field for root class is currently set to 0.
1639 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001640 Result += ", 0,2, sizeof(struct _objc_class), 0";
1641 if (CDecl->getNumClassMethods() > 0) {
1642 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1643 Result += CDecl->getName();
1644 Result += "\n";
1645 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001646 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001647 Result += ", 0\n";
1648 if (CDecl->getNumIntfRefProtocols() > 0) {
1649 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1650 Result += CDecl->getName();
1651 Result += ",0,0\n";
1652 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001653 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001654 Result += "\t,0,0,0,0\n";
1655 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001656
1657 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001658 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1659 Result += CDecl->getName();
1660 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1661 "{\n\t&_OBJC_METACLASS_";
1662 Result += CDecl->getName();
1663 if (SuperClass) {
1664 Result += ", \"";
1665 Result += SuperClass->getName();
1666 Result += "\", \"";
1667 Result += CDecl->getName();
1668 Result += "\"";
1669 }
1670 else {
1671 Result += ", 0, \"";
1672 Result += CDecl->getName();
1673 Result += "\"";
1674 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001675 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001676 Result += ", 0,1";
1677 if (!ObjcSynthesizedStructs.count(CDecl))
1678 Result += ",0";
1679 else {
1680 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001681 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00001682 Result += CDecl->getName();
1683 Result += ")";
1684 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001685 if (NumIvars > 0) {
1686 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1687 Result += CDecl->getName();
1688 Result += "\n\t";
1689 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001690 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001691 Result += ",0";
1692 if (IDecl->getNumInstanceMethods() > 0) {
1693 Result += ", &_OBJC_INSTANCE_METHODS_";
1694 Result += CDecl->getName();
1695 Result += ", 0\n\t";
1696 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001697 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001698 Result += ",0,0";
1699 if (CDecl->getNumIntfRefProtocols() > 0) {
1700 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1701 Result += CDecl->getName();
1702 Result += ", 0,0\n";
1703 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00001704 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001705 Result += ",0,0,0\n";
1706 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00001707}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001708
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001709void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001710 int ClsDefCount = ClassImplementation.size();
1711 int CatDefCount = CategoryImplementation.size();
1712 if (ClsDefCount == 0 && CatDefCount == 0)
1713 return;
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001714
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001715 // TODO: This is temporary until we decide how to access objc types in a
1716 // c program
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001717 Result += "#include <Objc/objc.h>\n";
1718 // This is needed for use of offsetof
1719 Result += "#include <stddef.h>\n";
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00001720
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001721 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001722 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001723 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001724
1725 // For each implemented category, write out all its meta data.
1726 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001727 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00001728
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001729 // Write objc_symtab metadata
1730 /*
1731 struct _objc_symtab
1732 {
1733 long sel_ref_cnt;
1734 SEL *refs;
1735 short cls_def_cnt;
1736 short cat_def_cnt;
1737 void *defs[cls_def_cnt + cat_def_cnt];
1738 };
1739 */
1740
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001741 Result += "\nstruct _objc_symtab {\n";
1742 Result += "\tlong sel_ref_cnt;\n";
1743 Result += "\tSEL *refs;\n";
1744 Result += "\tshort cls_def_cnt;\n";
1745 Result += "\tshort cat_def_cnt;\n";
1746 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1747 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001748
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001749 Result += "static struct _objc_symtab "
1750 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1751 Result += "\t0, 0, " + utostr(ClsDefCount)
1752 + ", " + utostr(CatDefCount) + "\n";
1753 for (int i = 0; i < ClsDefCount; i++) {
1754 Result += "\t,&_OBJC_CLASS_";
1755 Result += ClassImplementation[i]->getName();
1756 Result += "\n";
1757 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001758
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001759 for (int i = 0; i < CatDefCount; i++) {
1760 Result += "\t,&_OBJC_CATEGORY_";
1761 Result += CategoryImplementation[i]->getClassInterface()->getName();
1762 Result += "_";
1763 Result += CategoryImplementation[i]->getName();
1764 Result += "\n";
1765 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001766
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001767 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001768
1769 // Write objc_module metadata
1770
1771 /*
1772 struct _objc_module {
1773 long version;
1774 long size;
1775 const char *name;
1776 struct _objc_symtab *symtab;
1777 }
1778 */
1779
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001780 Result += "\nstruct _objc_module {\n";
1781 Result += "\tlong version;\n";
1782 Result += "\tlong size;\n";
1783 Result += "\tconst char *name;\n";
1784 Result += "\tstruct _objc_symtab *symtab;\n";
1785 Result += "};\n\n";
1786 Result += "static struct _objc_module "
1787 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001788 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1789 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001790 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00001791}
Chris Lattner6fe8b272007-10-16 22:36:42 +00001792