blob: 09d58f2f60e8c737a7217fb5f9948371dc189a5e [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000020#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000021#include "llvm/ADT/SmallPtrSet.h"
Steve Naroff2feac5e2007-10-30 03:43:13 +000022#include "clang/Lex/Lexer.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000023using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000024using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000025
Chris Lattner77cd2a02007-10-11 00:43:27 +000026namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000027 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000028 Rewriter Rewrite;
Chris Lattner01c57482007-10-17 22:35:30 +000029 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000030 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000031 unsigned MainFileID;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000032 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000033 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
34 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000035 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000036 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Steve Naroffebf2b562007-10-23 23:50:29 +000037
38 FunctionDecl *MsgSendFunctionDecl;
39 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000040 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000041 FunctionDecl *CFStringFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000042
Steve Naroffbeaf2992007-11-03 11:27:19 +000043 // ObjC string constant support.
44 FileVarDecl *ConstantStringClassReference;
45 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000046
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000047 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000048 public:
Chris Lattner01c57482007-10-17 22:35:30 +000049 void Initialize(ASTContext &context, unsigned mainFileID) {
50 Context = &context;
51 SM = &Context->SourceMgr;
Chris Lattner8a12c272007-10-11 18:38:32 +000052 MainFileID = mainFileID;
Steve Naroffebf2b562007-10-23 23:50:29 +000053 MsgSendFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000054 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000055 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000056 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000057 ConstantStringClassReference = 0;
58 NSStringRecord = 0;
Chris Lattner01c57482007-10-17 22:35:30 +000059 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000060 // declaring objc_selector outside the parameter list removes a silly
61 // scope related warning...
Steve Naroff21867b12007-11-07 18:43:40 +000062 const char *s = "struct objc_selector; struct objc_class;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000063 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000064 "(struct objc_object *, struct objc_selector *, ...);\n"
65 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-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 Naroffab972d32007-11-04 22:37:50 +000074 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
75 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +000076 }
Chris Lattner8a12c272007-10-11 18:38:32 +000077
Chris Lattnerf04da132007-10-24 17:06:59 +000078 // Top Level Driver code.
79 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000080 void HandleDeclInMainFile(Decl *D);
Chris Lattnerf04da132007-10-24 17:06:59 +000081 ~RewriteTest();
82
83 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +000084 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000085 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +000086 void RewriteTabs();
87 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +000088 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +000089 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +000090 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +000091 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000092 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000093 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000094 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000095 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000096 void RewriteObjcQualifiedInterfaceTypes(
97 const FunctionTypeProto *proto, FunctionDecl *FD);
98 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000099
Chris Lattnerf04da132007-10-24 17:06:59 +0000100 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000101 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000102 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000103 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000104 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000105 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000106 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
107 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
108 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000109 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000110 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
111 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000112 void SynthMsgSendFunctionDecl();
113 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000114 void SynthCFStringFunctionDecl();
115
Chris Lattnerf04da132007-10-24 17:06:59 +0000116 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000117 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
118 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000119
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000120 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
121 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000122
Steve Naroff0416fb92007-11-11 17:19:15 +0000123 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000124 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000125 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000126 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000127 const char *ClassName,
128 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000129
130 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
131 int NumProtocols,
132 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000133 const char *ClassName,
134 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000135 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
136 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000137 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
138 ObjcIvarDecl *ivar,
139 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000140 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000141 };
142}
143
Chris Lattner8a12c272007-10-11 18:38:32 +0000144ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000145
Chris Lattnerf04da132007-10-24 17:06:59 +0000146//===----------------------------------------------------------------------===//
147// Top Level Driver Code
148//===----------------------------------------------------------------------===//
149
Chris Lattner8a12c272007-10-11 18:38:32 +0000150void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-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 Naroffebf2b562007-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 Naroff09b266e2007-10-30 23:14:51 +0000162 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-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 Naroffbef11852007-10-26 20:53:56 +0000169 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
170 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000171 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
172 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000173 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
174 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000175 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000176 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000177 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
178 return HandleDeclInMainFile(D);
179
Chris Lattnerf04da132007-10-24 17:06:59 +0000180 // Otherwise, see if there is a #import in the main file that should be
181 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000182 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000183}
184
Chris Lattnerf04da132007-10-24 17:06:59 +0000185/// HandleDeclInMainFile - This is called for each top-level decl defined in the
186/// main file of the input.
187void RewriteTest::HandleDeclInMainFile(Decl *D) {
188 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
189 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000190 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Chris Lattnerf04da132007-10-24 17:06:59 +0000191
192 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
193 ClassImplementation.push_back(CI);
194 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
195 CategoryImplementation.push_back(CI);
196 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
197 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000198 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
199 if (VD->getInit())
200 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
201 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000202 // Nothing yet.
203}
204
205RewriteTest::~RewriteTest() {
206 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000207
208 // Rewrite tabs if we care.
209 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000210
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000211 // Rewrite Objective-c meta data*
212 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000213 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000214
Chris Lattnerf04da132007-10-24 17:06:59 +0000215 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
216 // we are done.
217 if (const RewriteBuffer *RewriteBuf =
218 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000219 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000220 std::string S(RewriteBuf->begin(), RewriteBuf->end());
221 printf("%s\n", S.c_str());
222 } else {
223 printf("No changes\n");
224 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000225 // Emit metadata.
226 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000227}
228
Chris Lattnerf04da132007-10-24 17:06:59 +0000229//===----------------------------------------------------------------------===//
230// Syntactic (non-AST) Rewriting Code
231//===----------------------------------------------------------------------===//
232
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000233void RewriteTest::RewriteInclude(SourceLocation Loc) {
234 // Rip up the #include stack to the main file.
235 SourceLocation IncLoc = Loc, NextLoc = Loc;
236 do {
237 IncLoc = Loc;
238 Loc = SM->getLogicalLoc(NextLoc);
239 NextLoc = SM->getIncludeLoc(Loc);
240 } while (!NextLoc.isInvalid());
241
242 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
243 // IncLoc indicates the header that was included if it is useful.
244 IncLoc = SM->getLogicalLoc(IncLoc);
245 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
246 Loc == LastIncLoc)
247 return;
248 LastIncLoc = Loc;
249
250 unsigned IncCol = SM->getColumnNumber(Loc);
251 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
252
253 // Replace the #import with #include.
254 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
255}
256
Chris Lattnerf04da132007-10-24 17:06:59 +0000257void RewriteTest::RewriteTabs() {
258 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
259 const char *MainBufStart = MainBuf.first;
260 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000261
Chris Lattnerf04da132007-10-24 17:06:59 +0000262 // Loop over the whole file, looking for tabs.
263 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
264 if (*BufPtr != '\t')
265 continue;
266
267 // Okay, we found a tab. This tab will turn into at least one character,
268 // but it depends on which 'virtual column' it is in. Compute that now.
269 unsigned VCol = 0;
270 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
271 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
272 ++VCol;
273
274 // Okay, now that we know the virtual column, we know how many spaces to
275 // insert. We assume 8-character tab-stops.
276 unsigned Spaces = 8-(VCol & 7);
277
278 // Get the location of the tab.
279 SourceLocation TabLoc =
280 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
281
282 // Rewrite the single tab character into a sequence of spaces.
283 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
284 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000285}
286
287
Chris Lattnerf04da132007-10-24 17:06:59 +0000288void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
289 int numDecls = ClassDecl->getNumForwardDecls();
290 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
291
292 // Get the start location and compute the semi location.
293 SourceLocation startLoc = ClassDecl->getLocation();
294 const char *startBuf = SM->getCharacterData(startLoc);
295 const char *semiPtr = strchr(startBuf, ';');
296
297 // Translate to typedef's that forward reference structs with the same name
298 // as the class. As a convenience, we include the original declaration
299 // as a comment.
300 std::string typedefString;
301 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000302 typedefString.append(startBuf, semiPtr-startBuf+1);
303 typedefString += "\n";
304 for (int i = 0; i < numDecls; i++) {
305 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000306 if (ObjcForwardDecls.count(ForwardDecl))
307 continue;
Steve Naroff32174822007-11-09 12:50:28 +0000308 typedefString += "#ifndef _REWRITER_typedef_";
309 typedefString += ForwardDecl->getName();
310 typedefString += "\n";
311 typedefString += "#define _REWRITER_typedef_";
312 typedefString += ForwardDecl->getName();
313 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000314 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000315 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000316 typedefString += ";\n#endif\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000317 // Mark this typedef as having been generated.
318 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000319 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000320 }
321
322 // Replace the @class with typedefs corresponding to the classes.
323 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
324 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000325}
326
Steve Naroff423cb562007-10-30 13:30:57 +0000327void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
328 for (int i = 0; i < nMethods; i++) {
329 ObjcMethodDecl *Method = Methods[i];
330 SourceLocation Loc = Method->getLocStart();
331
Chris Lattner28d1fe82007-11-08 04:41:51 +0000332 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000333
334 // FIXME: handle methods that are declared across multiple lines.
335 }
336}
337
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000338void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
339{
340 for (int i = 0; i < nProperties; i++) {
341 ObjcPropertyDecl *Property = Properties[i];
342 SourceLocation Loc = Property->getLocation();
343
344 Rewrite.ReplaceText(Loc, 0, "// ", 3);
345
346 // FIXME: handle properties that are declared across multiple lines.
347 }
348}
349
Steve Naroff423cb562007-10-30 13:30:57 +0000350void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
351 SourceLocation LocStart = CatDecl->getLocStart();
352
353 // FIXME: handle category headers that are declared across multiple lines.
354 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
355
356 RewriteMethods(CatDecl->getNumInstanceMethods(),
357 CatDecl->getInstanceMethods());
358 RewriteMethods(CatDecl->getNumClassMethods(),
359 CatDecl->getClassMethods());
360 // Lastly, comment out the @end.
361 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
362}
363
Steve Naroff752d6ef2007-10-30 16:42:30 +0000364void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
365 SourceLocation LocStart = PDecl->getLocStart();
366
367 // FIXME: handle protocol headers that are declared across multiple lines.
368 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
369
370 RewriteMethods(PDecl->getNumInstanceMethods(),
371 PDecl->getInstanceMethods());
372 RewriteMethods(PDecl->getNumClassMethods(),
373 PDecl->getClassMethods());
374 // Lastly, comment out the @end.
375 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
376}
377
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000378void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
379 std::string &ResultStr) {
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000380 static bool includeObjc = false;
381 if (!includeObjc) {
382 ResultStr += "#include <Objc/objc.h>\n";
383 includeObjc = true;
384 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000385 ResultStr += "\nstatic ";
386 ResultStr += OMD->getResultType().getAsString();
387 ResultStr += "\n_";
388
389 // Unique method name
390 if (OMD->isInstance())
391 ResultStr += "I_";
392 else
393 ResultStr += "C_";
394
395 ResultStr += OMD->getClassInterface()->getName();
396 ResultStr += "_";
397
398 NamedDecl *MethodContext = OMD->getMethodContext();
399 if (ObjcCategoryImplDecl *CID =
400 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
401 ResultStr += CID->getName();
402 ResultStr += "_";
403 }
404 // Append selector names, replacing ':' with '_'
405 const char *selName = OMD->getSelector().getName().c_str();
406 if (!strchr(selName, ':'))
407 ResultStr += OMD->getSelector().getName();
408 else {
409 std::string selString = OMD->getSelector().getName();
410 int len = selString.size();
411 for (int i = 0; i < len; i++)
412 if (selString[i] == ':')
413 selString[i] = '_';
414 ResultStr += selString;
415 }
416
417 // Rewrite arguments
418 ResultStr += "(";
419
420 // invisible arguments
421 if (OMD->isInstance()) {
422 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
423 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000424 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
425 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000426 ResultStr += selfTy.getAsString();
427 }
428 else
429 ResultStr += Context->getObjcIdType().getAsString();
430
431 ResultStr += " self, ";
432 ResultStr += Context->getObjcSelType().getAsString();
433 ResultStr += " _cmd";
434
435 // Method arguments.
436 for (int i = 0; i < OMD->getNumParams(); i++) {
437 ParmVarDecl *PDecl = OMD->getParamDecl(i);
438 ResultStr += ", ";
439 ResultStr += PDecl->getType().getAsString();
440 ResultStr += " ";
441 ResultStr += PDecl->getName();
442 }
443 ResultStr += ")";
444
445}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000446void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
447 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
448 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000449
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000450 if (IMD)
451 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
452 else
453 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000454
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000455 int numMethods = IMD ? IMD->getNumInstanceMethods()
456 : CID->getNumInstanceMethods();
457
458 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000459 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000460 ObjcMethodDecl *OMD;
461 if (IMD)
462 OMD = IMD->getInstanceMethods()[i];
463 else
464 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000465 RewriteObjcMethodDecl(OMD, ResultStr);
466 SourceLocation LocStart = OMD->getLocStart();
467 SourceLocation LocEnd = OMD->getBody()->getLocStart();
468
469 const char *startBuf = SM->getCharacterData(LocStart);
470 const char *endBuf = SM->getCharacterData(LocEnd);
471 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
472 ResultStr.c_str(), ResultStr.size());
473 }
474
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000475 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
476 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000477 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000478 ObjcMethodDecl *OMD;
479 if (IMD)
480 OMD = IMD->getClassMethods()[i];
481 else
482 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000483 RewriteObjcMethodDecl(OMD, ResultStr);
484 SourceLocation LocStart = OMD->getLocStart();
485 SourceLocation LocEnd = OMD->getBody()->getLocStart();
486
487 const char *startBuf = SM->getCharacterData(LocStart);
488 const char *endBuf = SM->getCharacterData(LocEnd);
489 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
490 ResultStr.c_str(), ResultStr.size());
491 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000492 if (IMD)
493 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
494 else
495 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000496}
497
Steve Naroffbef11852007-10-26 20:53:56 +0000498void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000499
500 SourceLocation LocStart = ClassDecl->getLocStart();
501 SourceLocation LocEnd = ClassDecl->getLocEnd();
502
503 const char *startBuf = SM->getCharacterData(LocStart);
504 const char *endBuf = SM->getCharacterData(LocEnd);
505
Steve Naroff2feac5e2007-10-30 03:43:13 +0000506 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000507
508 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000509 if (!ObjcForwardDecls.count(ClassDecl)) {
510 // we haven't seen a forward decl - generate a typedef.
Steve Naroff32174822007-11-09 12:50:28 +0000511 ResultStr += "#ifndef _REWRITER_typedef_";
512 ResultStr += ClassDecl->getName();
513 ResultStr += "\n";
514 ResultStr += "#define _REWRITER_typedef_";
515 ResultStr += ClassDecl->getName();
516 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000517 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000518 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000519 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000520
521 // Mark this typedef as having been generated.
522 ObjcForwardDecls.insert(ClassDecl);
523 }
Steve Narofff908a872007-10-30 02:23:23 +0000524 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
525
Steve Naroff2feac5e2007-10-30 03:43:13 +0000526 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000527 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000528 RewriteProperties(ClassDecl->getNumPropertyDecl(),
529 ClassDecl->getPropertyDecl());
Steve Naroff423cb562007-10-30 13:30:57 +0000530 RewriteMethods(ClassDecl->getNumInstanceMethods(),
531 ClassDecl->getInstanceMethods());
532 RewriteMethods(ClassDecl->getNumClassMethods(),
533 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000534
Steve Naroff2feac5e2007-10-30 03:43:13 +0000535 // Lastly, comment out the @end.
536 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000537}
538
Chris Lattnerf04da132007-10-24 17:06:59 +0000539//===----------------------------------------------------------------------===//
540// Function Body / Expression rewriting
541//===----------------------------------------------------------------------===//
542
Steve Narofff3473a72007-11-09 15:20:18 +0000543Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000544 // Otherwise, just rewrite all children.
545 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
546 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000547 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000548 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000549 if (newStmt)
550 *CI = newStmt;
551 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000552
553 // Handle specific things.
554 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
555 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000556
557 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
558 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000559
560 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
561 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000562
Steve Naroff934f2762007-10-24 22:48:43 +0000563 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
564 // Before we rewrite it, put the original message expression in a comment.
565 SourceLocation startLoc = MessExpr->getLocStart();
566 SourceLocation endLoc = MessExpr->getLocEnd();
567
568 const char *startBuf = SM->getCharacterData(startLoc);
569 const char *endBuf = SM->getCharacterData(endLoc);
570
571 std::string messString;
572 messString += "// ";
573 messString.append(startBuf, endBuf-startBuf+1);
574 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000575
Steve Naroff934f2762007-10-24 22:48:43 +0000576 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
577 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
578 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000579 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000580 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000581 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000582
583 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
584 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000585
586 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
587 return RewriteObjcThrowStmt(StmtThrow);
588
Chris Lattnere64b7772007-10-24 16:57:36 +0000589 // Return this stmt unmodified.
590 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000591}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000592
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000593Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000594 // Get the start location and compute the semi location.
595 SourceLocation startLoc = S->getLocStart();
596 const char *startBuf = SM->getCharacterData(startLoc);
597
598 assert((*startBuf == '@') && "bogus @try location");
599
600 std::string buf;
601 // declare a new scope with two variables, _stack and _rethrow.
602 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
603 buf += "int buf[18/*32-bit i386*/];\n";
604 buf += "char *pointers[4];} _stack;\n";
605 buf += "id volatile _rethrow = 0;\n";
606 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000607 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000608
609 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
610
611 startLoc = S->getTryBody()->getLocEnd();
612 startBuf = SM->getCharacterData(startLoc);
613
614 assert((*startBuf == '}') && "bogus @try block");
615
616 SourceLocation lastCurlyLoc = startLoc;
617
618 startLoc = startLoc.getFileLocWithOffset(1);
619 buf = " /* @catch begin */ else {\n";
620 buf += " id _caught = objc_exception_extract(&_stack);\n";
621 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000622 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000623 buf += " _rethrow = objc_exception_extract(&_stack);\n";
624 buf += " else { /* @catch continue */";
625
Chris Lattner28d1fe82007-11-08 04:41:51 +0000626 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000627
628 bool sawIdTypedCatch = false;
629 Stmt *lastCatchBody = 0;
630 ObjcAtCatchStmt *catchList = S->getCatchStmts();
631 while (catchList) {
632 Stmt *catchStmt = catchList->getCatchParamStmt();
633
634 if (catchList == S->getCatchStmts())
635 buf = "if ("; // we are generating code for the first catch clause
636 else
637 buf = "else if (";
638 startLoc = catchList->getLocStart();
639 startBuf = SM->getCharacterData(startLoc);
640
641 assert((*startBuf == '@') && "bogus @catch location");
642
643 const char *lParenLoc = strchr(startBuf, '(');
644
645 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
646 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
647 if (t == Context->getObjcIdType()) {
648 buf += "1) { ";
649 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
650 buf.c_str(), buf.size());
651 sawIdTypedCatch = true;
652 } else if (const PointerType *pType = t->getAsPointerType()) {
653 ObjcInterfaceType *cls; // Should be a pointer to a class.
654
655 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
656 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000657 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000658 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000659 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000660 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
661 buf.c_str(), buf.size());
662 }
663 }
664 // Now rewrite the body...
665 lastCatchBody = catchList->getCatchBody();
666 SourceLocation rParenLoc = catchList->getRParenLoc();
667 SourceLocation bodyLoc = lastCatchBody->getLocStart();
668 const char *bodyBuf = SM->getCharacterData(bodyLoc);
669 const char *rParenBuf = SM->getCharacterData(rParenLoc);
670 assert((*rParenBuf == ')') && "bogus @catch paren location");
671 assert((*bodyBuf == '{') && "bogus @catch body location");
672
673 buf = " = _caught;";
674 // Here we replace ") {" with "= _caught;" (which initializes and
675 // declares the @catch parameter).
676 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
677 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000678 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000679 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000680 }
Steve Naroff75730982007-11-07 04:08:17 +0000681 catchList = catchList->getNextCatchStmt();
682 }
683 // Complete the catch list...
684 if (lastCatchBody) {
685 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
686 const char *bodyBuf = SM->getCharacterData(bodyLoc);
687 assert((*bodyBuf == '}') && "bogus @catch body location");
688 bodyLoc = bodyLoc.getFileLocWithOffset(1);
689 buf = " } } /* @catch end */\n";
690
Chris Lattner28d1fe82007-11-08 04:41:51 +0000691 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000692
693 // Set lastCurlyLoc
694 lastCurlyLoc = lastCatchBody->getLocEnd();
695 }
696 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
697 startLoc = finalStmt->getLocStart();
698 startBuf = SM->getCharacterData(startLoc);
699 assert((*startBuf == '@') && "bogus @finally start");
700
701 buf = "/* @finally */";
702 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
703
704 Stmt *body = finalStmt->getFinallyBody();
705 SourceLocation startLoc = body->getLocStart();
706 SourceLocation endLoc = body->getLocEnd();
707 const char *startBuf = SM->getCharacterData(startLoc);
708 const char *endBuf = SM->getCharacterData(endLoc);
709 assert((*startBuf == '{') && "bogus @finally body location");
710 assert((*endBuf == '}') && "bogus @finally body location");
711
712 startLoc = startLoc.getFileLocWithOffset(1);
713 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000714 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000715 endLoc = endLoc.getFileLocWithOffset(-1);
716 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000717 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000718
719 // Set lastCurlyLoc
720 lastCurlyLoc = body->getLocEnd();
721 }
722 // Now emit the final closing curly brace...
723 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
724 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000725 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000726 return 0;
727}
728
729Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
730 return 0;
731}
732
733Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
734 return 0;
735}
736
Steve Naroff2bd03922007-11-07 15:32:26 +0000737// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
738// the throw expression is typically a message expression that's already
739// been rewritten! (which implies the SourceLocation's are invalid).
740Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
741 // Get the start location and compute the semi location.
742 SourceLocation startLoc = S->getLocStart();
743 const char *startBuf = SM->getCharacterData(startLoc);
744
745 assert((*startBuf == '@') && "bogus @throw location");
746
747 std::string buf;
748 /* void objc_exception_throw(id) __attribute__((noreturn)); */
749 buf = "objc_exception_throw(";
750 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
751 const char *semiBuf = strchr(startBuf, ';');
752 assert((*semiBuf == ';') && "@throw: can't find ';'");
753 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
754 buf = ");";
755 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
756 return 0;
757}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000758
Chris Lattnere64b7772007-10-24 16:57:36 +0000759Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000760 // Create a new string expression.
761 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000762 std::string StrEncoding;
763 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
764 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
765 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000766 SourceLocation(), SourceLocation());
767 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000768 delete Exp;
769 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000770}
771
Steve Naroffb42f8412007-11-05 14:50:49 +0000772Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
773 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
774 // Create a call to sel_registerName("selName").
775 llvm::SmallVector<Expr*, 8> SelExprs;
776 QualType argType = Context->getPointerType(Context->CharTy);
777 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
778 Exp->getSelector().getName().size(),
779 false, argType, SourceLocation(),
780 SourceLocation()));
781 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
782 &SelExprs[0], SelExprs.size());
783 Rewrite.ReplaceStmt(Exp, SelExp);
784 delete Exp;
785 return SelExp;
786}
787
Steve Naroff934f2762007-10-24 22:48:43 +0000788CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
789 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000790 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000791 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000792
793 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000794 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000795
796 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000797 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000798 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
799
800 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000801
Steve Naroff934f2762007-10-24 22:48:43 +0000802 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
803}
804
Steve Naroffd5255f52007-11-01 13:24:47 +0000805static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
806 const char *&startRef, const char *&endRef) {
807 while (startBuf < endBuf) {
808 if (*startBuf == '<')
809 startRef = startBuf; // mark the start.
810 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000811 if (startRef && *startRef == '<') {
812 endRef = startBuf; // mark the end.
813 return true;
814 }
815 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000816 }
817 startBuf++;
818 }
819 return false;
820}
821
822bool RewriteTest::needToScanForQualifiers(QualType T) {
823 // FIXME: we don't currently represent "id <Protocol>" in the type system.
824 if (T == Context->getObjcIdType())
825 return true;
826
827 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000828 Type *pointeeType = pType->getPointeeType().getTypePtr();
829 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
830 return true; // we have "Class <Protocol> *".
831 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000832 return false;
833}
834
835void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
836 const FunctionTypeProto *proto, FunctionDecl *FD) {
837
838 if (needToScanForQualifiers(proto->getResultType())) {
839 // Since types are unique, we need to scan the buffer.
840 SourceLocation Loc = FD->getLocation();
841
842 const char *endBuf = SM->getCharacterData(Loc);
843 const char *startBuf = endBuf;
844 while (*startBuf != ';')
845 startBuf--; // scan backward (from the decl location) for return type.
846 const char *startRef = 0, *endRef = 0;
847 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
848 // Get the locations of the startRef, endRef.
849 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
850 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
851 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000852 Rewrite.InsertText(LessLoc, "/*", 2);
853 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000854 }
855 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000856 // Now check arguments.
857 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
858 if (needToScanForQualifiers(proto->getArgType(i))) {
859 // Since types are unique, we need to scan the buffer.
860 SourceLocation Loc = FD->getLocation();
861
862 const char *startBuf = SM->getCharacterData(Loc);
863 const char *endBuf = startBuf;
864 while (*endBuf != ';')
865 endBuf++; // scan forward (from the decl location) for argument types.
866 const char *startRef = 0, *endRef = 0;
867 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
868 // Get the locations of the startRef, endRef.
869 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
870 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
871 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000872 Rewrite.InsertText(LessLoc, "/*", 2);
873 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000874 }
875 }
876 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000877}
878
Steve Naroff09b266e2007-10-30 23:14:51 +0000879void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
880 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000881 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000882 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000883 return;
884 }
885 // Check for ObjC 'id' and class types that have been adorned with protocol
886 // information (id<p>, C<p>*). The protocol references need to be rewritten!
887 const FunctionType *funcType = FD->getType()->getAsFunctionType();
888 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000889 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
890 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000891}
892
893// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
894void RewriteTest::SynthMsgSendFunctionDecl() {
895 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
896 llvm::SmallVector<QualType, 16> ArgTys;
897 QualType argT = Context->getObjcIdType();
898 assert(!argT.isNull() && "Can't find 'id' type");
899 ArgTys.push_back(argT);
900 argT = Context->getObjcSelType();
901 assert(!argT.isNull() && "Can't find 'SEL' type");
902 ArgTys.push_back(argT);
903 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
904 &ArgTys[0], ArgTys.size(),
905 true /*isVariadic*/);
906 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
907 msgSendIdent, msgSendType,
908 FunctionDecl::Extern, false, 0);
909}
910
911// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
912void RewriteTest::SynthGetClassFunctionDecl() {
913 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
914 llvm::SmallVector<QualType, 16> ArgTys;
915 ArgTys.push_back(Context->getPointerType(
916 Context->CharTy.getQualifiedType(QualType::Const)));
917 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
918 &ArgTys[0], ArgTys.size(),
919 false /*isVariadic*/);
920 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
921 getClassIdent, getClassType,
922 FunctionDecl::Extern, false, 0);
923}
924
Steve Naroff96984642007-11-08 14:30:50 +0000925// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
926void RewriteTest::SynthCFStringFunctionDecl() {
927 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
928 llvm::SmallVector<QualType, 16> ArgTys;
929 ArgTys.push_back(Context->getPointerType(
930 Context->CharTy.getQualifiedType(QualType::Const)));
931 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
932 &ArgTys[0], ArgTys.size(),
933 false /*isVariadic*/);
934 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
935 getClassIdent, getClassType,
936 FunctionDecl::Extern, false, 0);
937}
938
Steve Naroffbeaf2992007-11-03 11:27:19 +0000939Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000940#if 1
941 // This rewrite is specific to GCC, which has builtin support for CFString.
942 if (!CFStringFunctionDecl)
943 SynthCFStringFunctionDecl();
944 // Create a call to __builtin___CFStringMakeConstantString("cstr").
945 llvm::SmallVector<Expr*, 8> StrExpr;
946 StrExpr.push_back(Exp->getString());
947 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
948 &StrExpr[0], StrExpr.size());
949 // cast to NSConstantString *
950 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
951 Rewrite.ReplaceStmt(Exp, cast);
952 delete Exp;
953 return cast;
954#else
Steve Naroffbeaf2992007-11-03 11:27:19 +0000955 assert(ConstantStringClassReference && "Can't find constant string reference");
956 llvm::SmallVector<Expr*, 4> InitExprs;
957
958 // Synthesize "(Class)&_NSConstantStringClassReference"
959 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
960 ConstantStringClassReference->getType(),
961 SourceLocation());
962 QualType expType = Context->getPointerType(ClsRef->getType());
963 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
964 expType, SourceLocation());
965 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
966 SourceLocation());
967 InitExprs.push_back(cast); // set the 'isa'.
968 InitExprs.push_back(Exp->getString()); // set "char *bytes".
969 unsigned IntSize = static_cast<unsigned>(
970 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
971 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
972 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
973 Exp->getLocStart());
974 InitExprs.push_back(len); // set "int numBytes".
975
976 // struct NSConstantString
977 QualType CFConstantStrType = Context->getCFConstantStringType();
978 // (struct NSConstantString) { <exprs from above> }
979 InitListExpr *ILE = new InitListExpr(SourceLocation(),
980 &InitExprs[0], InitExprs.size(),
981 SourceLocation());
982 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
983 // struct NSConstantString *
984 expType = Context->getPointerType(StrRep->getType());
985 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
986 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000987 // cast to NSConstantString *
988 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000989 Rewrite.ReplaceStmt(Exp, cast);
990 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000991 return cast;
Steve Naroff96984642007-11-08 14:30:50 +0000992#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +0000993}
994
Steve Naroff934f2762007-10-24 22:48:43 +0000995Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000996 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000997 if (!MsgSendFunctionDecl)
998 SynthMsgSendFunctionDecl();
999 if (!GetClassFunctionDecl)
1000 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +00001001
1002 // Synthesize a call to objc_msgSend().
1003 llvm::SmallVector<Expr*, 8> MsgExprs;
1004 IdentifierInfo *clsName = Exp->getClassName();
1005
1006 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1007 if (clsName) { // class message.
1008 llvm::SmallVector<Expr*, 8> ClsExprs;
1009 QualType argType = Context->getPointerType(Context->CharTy);
1010 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1011 clsName->getLength(),
1012 false, argType, SourceLocation(),
1013 SourceLocation()));
1014 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1015 &ClsExprs[0], ClsExprs.size());
1016 MsgExprs.push_back(Cls);
1017 } else // instance message.
1018 MsgExprs.push_back(Exp->getReceiver());
1019
Steve Naroffbeaf2992007-11-03 11:27:19 +00001020 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001021 llvm::SmallVector<Expr*, 8> SelExprs;
1022 QualType argType = Context->getPointerType(Context->CharTy);
1023 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1024 Exp->getSelector().getName().size(),
1025 false, argType, SourceLocation(),
1026 SourceLocation()));
1027 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1028 &SelExprs[0], SelExprs.size());
1029 MsgExprs.push_back(SelExp);
1030
1031 // Now push any user supplied arguments.
1032 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
1033 MsgExprs.push_back(Exp->getArg(i));
1034 // We've transferred the ownership to MsgExprs. Null out the argument in
1035 // the original expression, since we will delete it below.
1036 Exp->setArg(i, 0);
1037 }
Steve Naroffab972d32007-11-04 22:37:50 +00001038 // Generate the funky cast.
1039 CastExpr *cast;
1040 llvm::SmallVector<QualType, 8> ArgTypes;
1041 QualType returnType;
1042
1043 // Push 'id' and 'SEL', the 2 implicit arguments.
1044 ArgTypes.push_back(Context->getObjcIdType());
1045 ArgTypes.push_back(Context->getObjcSelType());
1046 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1047 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001048 for (int i = 0; i < mDecl->getNumParams(); i++) {
1049 QualType t = mDecl->getParamDecl(i)->getType();
1050 if (t == Context->getObjcClassType())
1051 t = Context->getObjcIdType(); // Convert "Class"->"id"
1052 ArgTypes.push_back(t);
1053 }
Steve Naroffab972d32007-11-04 22:37:50 +00001054 returnType = mDecl->getResultType();
1055 } else {
1056 returnType = Context->getObjcIdType();
1057 }
1058 // Get the type, we will need to reference it in a couple spots.
1059 QualType msgSendType = MsgSendFunctionDecl->getType();
1060
1061 // Create a reference to the objc_msgSend() declaration.
1062 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
1063
1064 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1065 // If we don't do this cast, we get the following bizarre warning/note:
1066 // xx.m:13: warning: function called through a non-compatible type
1067 // xx.m:13: note: if this code is reached, the program will abort
1068 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1069 SourceLocation());
1070
1071 // Now do the "normal" pointer to function cast.
1072 QualType castType = Context->getFunctionType(returnType,
1073 &ArgTypes[0], ArgTypes.size(),
1074 false/*FIXME:variadic*/);
1075 castType = Context->getPointerType(castType);
1076 cast = new CastExpr(castType, cast, SourceLocation());
1077
1078 // Don't forget the parens to enforce the proper binding.
1079 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1080
1081 const FunctionType *FT = msgSendType->getAsFunctionType();
1082 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1083 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001084 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001085 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001086
Chris Lattnere64b7772007-10-24 16:57:36 +00001087 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001088 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001089}
1090
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001091/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1092/// an objective-c class with ivars.
1093void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1094 std::string &Result) {
1095 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1096 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001097 // Do not synthesize more than once.
1098 if (ObjcSynthesizedStructs.count(CDecl))
1099 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001100 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
1101 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
1102 // Do it for the root
1103 SynthesizeObjcInternalStruct(RCDecl, Result);
1104 }
1105
Steve Naroff03300712007-11-12 13:56:41 +00001106 int NumIvars = CDecl->getNumInstanceVariables();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001107 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +00001108 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001109 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
1110 return;
1111
Steve Naroff04960052007-11-01 17:12:31 +00001112 Result += "\nstruct ";
1113 Result += CDecl->getName();
1114 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1115 Result += " {\n struct ";
1116 Result += RCDecl->getName();
1117 Result += " _";
1118 Result += RCDecl->getName();
1119 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001120 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001121 else
1122 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +00001123
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001124 if (NumIvars > 0) {
1125 SourceLocation LocStart = CDecl->getLocStart();
1126 SourceLocation LocEnd = CDecl->getLocEnd();
1127
1128 const char *startBuf = SM->getCharacterData(LocStart);
1129 const char *endBuf = SM->getCharacterData(LocEnd);
1130 startBuf = strchr(startBuf, '{');
1131 assert((startBuf && endBuf)
1132 && "SynthesizeObjcInternalStruct - malformed @interface");
1133 startBuf++; // past '{'
1134 while (startBuf < endBuf) {
1135 if (*startBuf == '@') {
1136 startBuf = strchr(startBuf, 'p');
1137 // FIXME: presence of @public, etc. inside comment results in
1138 // this transformation as well, which is still correct c-code.
1139 if (!strncmp(startBuf, "public", strlen("public"))) {
1140 startBuf += strlen("public");
1141 Result += "/* @public */";
1142 }
1143 else if (!strncmp(startBuf, "private", strlen("private"))) {
1144 startBuf += strlen("private");
1145 Result += "/* @private */";
1146 }
1147 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1148 startBuf += strlen("protected");
1149 Result += "/* @protected */";
1150 }
1151 }
1152 Result += *startBuf++;
1153 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001154 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001155
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001156 Result += "};\n";
1157 // Mark this struct as having been generated.
1158 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001159 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001160}
1161
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001162// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1163/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001164void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001165 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001166 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001167 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001168 const char *ClassName,
1169 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001170 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001171 if (NumMethods > 0 && !objc_impl_method) {
1172 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001173 SEL _cmd;
1174 char *method_types;
1175 void *_imp;
1176 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001177 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001178 Result += "\nstruct _objc_method {\n";
1179 Result += "\tSEL _cmd;\n";
1180 Result += "\tchar *method_types;\n";
1181 Result += "\tvoid *_imp;\n";
1182 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001183
1184 /* struct _objc_method_list {
1185 struct _objc_method_list *next_method;
1186 int method_count;
1187 struct _objc_method method_list[];
1188 }
1189 */
1190 Result += "\nstruct _objc_method_list {\n";
1191 Result += "\tstruct _objc_method_list *next_method;\n";
1192 Result += "\tint method_count;\n";
1193 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001194 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001195 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001196 // Build _objc_method_list for class's methods if needed
1197 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001198 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001199 Result += prefix;
1200 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1201 Result += "_METHODS_";
1202 Result += ClassName;
1203 Result += " __attribute__ ((section (\"__OBJC, __";
1204 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001205 Result += "_meth\")))= ";
1206 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1207
1208 Result += "\t,{{(SEL)\"";
1209 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001210 std::string MethodTypeString;
1211 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1212 Result += "\", \"";
1213 Result += MethodTypeString;
1214 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001215 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001216 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001217 Result += "\t ,{(SEL)\"";
1218 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001219 std::string MethodTypeString;
1220 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1221 Result += "\", \"";
1222 Result += MethodTypeString;
1223 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001224 }
1225 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001226 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001227}
1228
1229/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1230void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1231 int NumProtocols,
1232 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001233 const char *ClassName,
1234 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001235 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001236 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001237 for (int i = 0; i < NumProtocols; i++) {
1238 ObjcProtocolDecl *PDecl = Protocols[i];
1239 // Output struct protocol_methods holder of method selector and type.
1240 if (!objc_protocol_methods &&
1241 (PDecl->getNumInstanceMethods() > 0
1242 || PDecl->getNumClassMethods() > 0)) {
1243 /* struct protocol_methods {
1244 SEL _cmd;
1245 char *method_types;
1246 }
1247 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001248 Result += "\nstruct protocol_methods {\n";
1249 Result += "\tSEL _cmd;\n";
1250 Result += "\tchar *method_types;\n";
1251 Result += "};\n";
1252
1253 /* struct _objc_protocol_method_list {
1254 int protocol_method_count;
1255 struct protocol_methods protocols[];
1256 }
1257 */
1258 Result += "\nstruct _objc_protocol_method_list {\n";
1259 Result += "\tint protocol_method_count;\n";
1260 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001261 objc_protocol_methods = true;
1262 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001263
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001264 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001265 int NumMethods = PDecl->getNumInstanceMethods();
1266 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001267 Result += "\nstatic struct _objc_protocol_method_list "
1268 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1269 Result += PDecl->getName();
1270 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1271 "{\n\t" + utostr(NumMethods) + "\n";
1272
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001273 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001274 Result += "\t,{{(SEL)\"";
1275 Result += Methods[0]->getSelector().getName().c_str();
1276 Result += "\", \"\"}\n";
1277
1278 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001279 Result += "\t ,{(SEL)\"";
1280 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001281 std::string MethodTypeString;
1282 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1283 Result += "\", \"";
1284 Result += MethodTypeString;
1285 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001286 }
1287 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001288 }
1289
1290 // Output class methods declared in this protocol.
1291 NumMethods = PDecl->getNumClassMethods();
1292 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001293 Result += "\nstatic struct _objc_protocol_method_list "
1294 "_OBJC_PROTOCOL_CLASS_METHODS_";
1295 Result += PDecl->getName();
1296 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1297 "{\n\t";
1298 Result += utostr(NumMethods);
1299 Result += "\n";
1300
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001301 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001302 Result += "\t,{{(SEL)\"";
1303 Result += Methods[0]->getSelector().getName().c_str();
1304 Result += "\", \"\"}\n";
1305
1306 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001307 Result += "\t ,{(SEL)\"";
1308 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001309 std::string MethodTypeString;
1310 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1311 Result += "\", \"";
1312 Result += MethodTypeString;
1313 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001314 }
1315 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001316 }
1317 // Output:
1318 /* struct _objc_protocol {
1319 // Objective-C 1.0 extensions
1320 struct _objc_protocol_extension *isa;
1321 char *protocol_name;
1322 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001323 struct _objc_protocol_method_list *instance_methods;
1324 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001325 };
1326 */
1327 static bool objc_protocol = false;
1328 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001329 Result += "\nstruct _objc_protocol {\n";
1330 Result += "\tstruct _objc_protocol_extension *isa;\n";
1331 Result += "\tchar *protocol_name;\n";
1332 Result += "\tstruct _objc_protocol **protocol_list;\n";
1333 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1334 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1335 Result += "};\n";
1336
1337 /* struct _objc_protocol_list {
1338 struct _objc_protocol_list *next;
1339 int protocol_count;
1340 struct _objc_protocol *class_protocols[];
1341 }
1342 */
1343 Result += "\nstruct _objc_protocol_list {\n";
1344 Result += "\tstruct _objc_protocol_list *next;\n";
1345 Result += "\tint protocol_count;\n";
1346 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1347 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001348 objc_protocol = true;
1349 }
1350
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001351 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1352 Result += PDecl->getName();
1353 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1354 "{\n\t0, \"";
1355 Result += PDecl->getName();
1356 Result += "\", 0, ";
1357 if (PDecl->getInstanceMethods() > 0) {
1358 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1359 Result += PDecl->getName();
1360 Result += ", ";
1361 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001362 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001363 Result += "0, ";
1364 if (PDecl->getClassMethods() > 0) {
1365 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1366 Result += PDecl->getName();
1367 Result += "\n";
1368 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001369 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001370 Result += "0\n";
1371 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001372 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001373 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001374 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1375 Result += prefix;
1376 Result += "_PROTOCOLS_";
1377 Result += ClassName;
1378 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1379 "{\n\t0, ";
1380 Result += utostr(NumProtocols);
1381 Result += "\n";
1382
1383 Result += "\t,{&_OBJC_PROTOCOL_";
1384 Result += Protocols[0]->getName();
1385 Result += " \n";
1386
1387 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001388 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001389 Result += "\t ,&_OBJC_PROTOCOL_";
1390 Result += PDecl->getName();
1391 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001392 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001393 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001394 }
1395}
1396
1397/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1398/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001399void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1400 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001401 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1402 // Find category declaration for this implementation.
1403 ObjcCategoryDecl *CDecl;
1404 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1405 CDecl = CDecl->getNextClassCategory())
1406 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1407 break;
1408 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1409
1410 char *FullCategoryName = (char*)alloca(
1411 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1412 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1413
1414 // Build _objc_method_list for class's instance methods if needed
1415 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1416 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001417 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001418 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001419
1420 // Build _objc_method_list for class's class methods if needed
1421 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1422 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001423 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001424 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001425
1426 // Protocols referenced in class declaration?
1427 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1428 CDecl->getNumReferencedProtocols(),
1429 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001430 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001431
1432 /* struct _objc_category {
1433 char *category_name;
1434 char *class_name;
1435 struct _objc_method_list *instance_methods;
1436 struct _objc_method_list *class_methods;
1437 struct _objc_protocol_list *protocols;
1438 // Objective-C 1.0 extensions
1439 uint32_t size; // sizeof (struct _objc_category)
1440 struct _objc_property_list *instance_properties; // category's own
1441 // @property decl.
1442 };
1443 */
1444
1445 static bool objc_category = false;
1446 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001447 Result += "\nstruct _objc_category {\n";
1448 Result += "\tchar *category_name;\n";
1449 Result += "\tchar *class_name;\n";
1450 Result += "\tstruct _objc_method_list *instance_methods;\n";
1451 Result += "\tstruct _objc_method_list *class_methods;\n";
1452 Result += "\tstruct _objc_protocol_list *protocols;\n";
1453 Result += "\tunsigned int size;\n";
1454 Result += "\tstruct _objc_property_list *instance_properties;\n";
1455 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001456 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001457 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001458 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1459 Result += FullCategoryName;
1460 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1461 Result += IDecl->getName();
1462 Result += "\"\n\t, \"";
1463 Result += ClassDecl->getName();
1464 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001465
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001466 if (IDecl->getNumInstanceMethods() > 0) {
1467 Result += "\t, (struct _objc_method_list *)"
1468 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1469 Result += FullCategoryName;
1470 Result += "\n";
1471 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001472 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001473 Result += "\t, 0\n";
1474 if (IDecl->getNumClassMethods() > 0) {
1475 Result += "\t, (struct _objc_method_list *)"
1476 "&_OBJC_CATEGORY_CLASS_METHODS_";
1477 Result += FullCategoryName;
1478 Result += "\n";
1479 }
1480 else
1481 Result += "\t, 0\n";
1482
1483 if (CDecl->getNumReferencedProtocols() > 0) {
1484 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1485 Result += FullCategoryName;
1486 Result += "\n";
1487 }
1488 else
1489 Result += "\t, 0\n";
1490 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001491}
1492
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001493/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1494/// ivar offset.
1495void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1496 ObjcIvarDecl *ivar,
1497 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001498 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001499 Result += IDecl->getName();
1500 Result += ", ";
1501 Result += ivar->getName();
1502 Result += ")";
1503}
1504
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001505//===----------------------------------------------------------------------===//
1506// Meta Data Emission
1507//===----------------------------------------------------------------------===//
1508
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001509void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1510 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001511 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1512
1513 // Build _objc_ivar_list metadata for classes ivars if needed
1514 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1515 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001516 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001517
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001518 SynthesizeObjcInternalStruct(CDecl, Result);
1519
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001520 if (NumIvars > 0) {
1521 static bool objc_ivar = false;
1522 if (!objc_ivar) {
1523 /* struct _objc_ivar {
1524 char *ivar_name;
1525 char *ivar_type;
1526 int ivar_offset;
1527 };
1528 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001529 Result += "\nstruct _objc_ivar {\n";
1530 Result += "\tchar *ivar_name;\n";
1531 Result += "\tchar *ivar_type;\n";
1532 Result += "\tint ivar_offset;\n";
1533 Result += "};\n";
1534
1535 /* struct _objc_ivar_list {
1536 int ivar_count;
1537 struct _objc_ivar ivar_list[];
1538 };
1539 */
1540 Result += "\nstruct _objc_ivar_list {\n";
1541 Result += "\tint ivar_count;\n";
1542 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001543 objc_ivar = true;
1544 }
1545
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001546 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1547 Result += IDecl->getName();
1548 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1549 "{\n\t";
1550 Result += utostr(NumIvars);
1551 Result += "\n";
1552
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001553 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1554 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001555 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001556 Result += "\t,{{\"";
1557 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001558 Result += "\", \"";
1559 std::string StrEncoding;
1560 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1561 Result += StrEncoding;
1562 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001563 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1564 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001565 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001566 Result += "\t ,{\"";
1567 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001568 Result += "\", \"";
1569 std::string StrEncoding;
1570 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1571 Result += StrEncoding;
1572 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001573 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1574 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001575 }
1576
1577 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001578 }
1579
1580 // Build _objc_method_list for class's instance methods if needed
1581 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1582 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001583 true,
1584 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001585
1586 // Build _objc_method_list for class's class methods if needed
1587 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001588 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001589 false,
1590 "", IDecl->getName(), Result);
1591
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001592 // Protocols referenced in class declaration?
1593 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1594 CDecl->getNumIntfRefProtocols(),
1595 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001596 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001597
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001598
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001599 // Declaration of class/meta-class metadata
1600 /* struct _objc_class {
1601 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001602 const char *super_class_name;
1603 char *name;
1604 long version;
1605 long info;
1606 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001607 struct _objc_ivar_list *ivars;
1608 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001609 struct objc_cache *cache;
1610 struct objc_protocol_list *protocols;
1611 const char *ivar_layout;
1612 struct _objc_class_ext *ext;
1613 };
1614 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001615 static bool objc_class = false;
1616 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001617 Result += "\nstruct _objc_class {\n";
1618 Result += "\tstruct _objc_class *isa;\n";
1619 Result += "\tconst char *super_class_name;\n";
1620 Result += "\tchar *name;\n";
1621 Result += "\tlong version;\n";
1622 Result += "\tlong info;\n";
1623 Result += "\tlong instance_size;\n";
1624 Result += "\tstruct _objc_ivar_list *ivars;\n";
1625 Result += "\tstruct _objc_method_list *methods;\n";
1626 Result += "\tstruct objc_cache *cache;\n";
1627 Result += "\tstruct _objc_protocol_list *protocols;\n";
1628 Result += "\tconst char *ivar_layout;\n";
1629 Result += "\tstruct _objc_class_ext *ext;\n";
1630 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001631 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001632 }
1633
1634 // Meta-class metadata generation.
1635 ObjcInterfaceDecl *RootClass = 0;
1636 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1637 while (SuperClass) {
1638 RootClass = SuperClass;
1639 SuperClass = SuperClass->getSuperClass();
1640 }
1641 SuperClass = CDecl->getSuperClass();
1642
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001643 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1644 Result += CDecl->getName();
1645 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1646 "{\n\t(struct _objc_class *)\"";
1647 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1648 Result += "\"";
1649
1650 if (SuperClass) {
1651 Result += ", \"";
1652 Result += SuperClass->getName();
1653 Result += "\", \"";
1654 Result += CDecl->getName();
1655 Result += "\"";
1656 }
1657 else {
1658 Result += ", 0, \"";
1659 Result += CDecl->getName();
1660 Result += "\"";
1661 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001662 // TODO: 'ivars' field for root class is currently set to 0.
1663 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001664 Result += ", 0,2, sizeof(struct _objc_class), 0";
1665 if (CDecl->getNumClassMethods() > 0) {
1666 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1667 Result += CDecl->getName();
1668 Result += "\n";
1669 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001670 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001671 Result += ", 0\n";
1672 if (CDecl->getNumIntfRefProtocols() > 0) {
1673 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1674 Result += CDecl->getName();
1675 Result += ",0,0\n";
1676 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001677 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001678 Result += "\t,0,0,0,0\n";
1679 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001680
1681 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001682 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1683 Result += CDecl->getName();
1684 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1685 "{\n\t&_OBJC_METACLASS_";
1686 Result += CDecl->getName();
1687 if (SuperClass) {
1688 Result += ", \"";
1689 Result += SuperClass->getName();
1690 Result += "\", \"";
1691 Result += CDecl->getName();
1692 Result += "\"";
1693 }
1694 else {
1695 Result += ", 0, \"";
1696 Result += CDecl->getName();
1697 Result += "\"";
1698 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001699 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001700 Result += ", 0,1";
1701 if (!ObjcSynthesizedStructs.count(CDecl))
1702 Result += ",0";
1703 else {
1704 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001705 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001706 Result += CDecl->getName();
1707 Result += ")";
1708 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001709 if (NumIvars > 0) {
1710 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1711 Result += CDecl->getName();
1712 Result += "\n\t";
1713 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001714 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001715 Result += ",0";
1716 if (IDecl->getNumInstanceMethods() > 0) {
1717 Result += ", &_OBJC_INSTANCE_METHODS_";
1718 Result += CDecl->getName();
1719 Result += ", 0\n\t";
1720 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001721 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001722 Result += ",0,0";
1723 if (CDecl->getNumIntfRefProtocols() > 0) {
1724 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1725 Result += CDecl->getName();
1726 Result += ", 0,0\n";
1727 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001728 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001729 Result += ",0,0,0\n";
1730 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001731}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001732
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001733/// RewriteImplementations - This routine rewrites all method implementations
1734/// and emits meta-data.
1735
1736void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001737 int ClsDefCount = ClassImplementation.size();
1738 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001739
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001740 if (ClsDefCount == 0 && CatDefCount == 0)
1741 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001742 // Rewrite implemented methods
1743 for (int i = 0; i < ClsDefCount; i++)
1744 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001745
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001746 for (int i = 0; i < CatDefCount; i++)
1747 RewriteImplementationDecl(CategoryImplementation[i]);
1748
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001749 // TODO: This is temporary until we decide how to access objc types in a
1750 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001751 Result += "#include <Objc/objc.h>\n";
1752 // This is needed for use of offsetof
1753 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001754
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001755 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001756 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001757 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001758
1759 // For each implemented category, write out all its meta data.
1760 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001761 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001762
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001763 // Write objc_symtab metadata
1764 /*
1765 struct _objc_symtab
1766 {
1767 long sel_ref_cnt;
1768 SEL *refs;
1769 short cls_def_cnt;
1770 short cat_def_cnt;
1771 void *defs[cls_def_cnt + cat_def_cnt];
1772 };
1773 */
1774
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001775 Result += "\nstruct _objc_symtab {\n";
1776 Result += "\tlong sel_ref_cnt;\n";
1777 Result += "\tSEL *refs;\n";
1778 Result += "\tshort cls_def_cnt;\n";
1779 Result += "\tshort cat_def_cnt;\n";
1780 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1781 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001782
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001783 Result += "static struct _objc_symtab "
1784 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1785 Result += "\t0, 0, " + utostr(ClsDefCount)
1786 + ", " + utostr(CatDefCount) + "\n";
1787 for (int i = 0; i < ClsDefCount; i++) {
1788 Result += "\t,&_OBJC_CLASS_";
1789 Result += ClassImplementation[i]->getName();
1790 Result += "\n";
1791 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001792
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001793 for (int i = 0; i < CatDefCount; i++) {
1794 Result += "\t,&_OBJC_CATEGORY_";
1795 Result += CategoryImplementation[i]->getClassInterface()->getName();
1796 Result += "_";
1797 Result += CategoryImplementation[i]->getName();
1798 Result += "\n";
1799 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001800
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001801 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001802
1803 // Write objc_module metadata
1804
1805 /*
1806 struct _objc_module {
1807 long version;
1808 long size;
1809 const char *name;
1810 struct _objc_symtab *symtab;
1811 }
1812 */
1813
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001814 Result += "\nstruct _objc_module {\n";
1815 Result += "\tlong version;\n";
1816 Result += "\tlong size;\n";
1817 Result += "\tconst char *name;\n";
1818 Result += "\tstruct _objc_symtab *symtab;\n";
1819 Result += "};\n\n";
1820 Result += "static struct _objc_module "
1821 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001822 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1823 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001824 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00001825
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001826}
Chris Lattner311ff022007-10-16 22:36:42 +00001827