blob: b74faf5b691edd00a3fd9221feee982433b81801 [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);
Steve Naroff423cb562007-10-30 13:30:57 +000089 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +000090 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Steve Naroff423cb562007-10-30 13:30:57 +000091 void RewriteMethods(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +000092 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +000093 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +000094 void RewriteObjcQualifiedInterfaceTypes(
95 const FunctionTypeProto *proto, FunctionDecl *FD);
96 bool needToScanForQualifiers(QualType T);
Chris Lattner311ff022007-10-16 22:36:42 +000097
Chris Lattnerf04da132007-10-24 17:06:59 +000098 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +000099 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000100 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroffb42f8412007-11-05 14:50:49 +0000101 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000102 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000103 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000104 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
105 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
106 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000107 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000108 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
109 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000110 void SynthMsgSendFunctionDecl();
111 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000112 void SynthCFStringFunctionDecl();
113
Chris Lattnerf04da132007-10-24 17:06:59 +0000114 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000115 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
116 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000117
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000118 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
119 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000120
121 void RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
122 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000123 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000124 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000125 const char *ClassName,
126 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000127
128 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
129 int NumProtocols,
130 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000131 const char *ClassName,
132 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000133 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
134 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000135 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
136 ObjcIvarDecl *ivar,
137 std::string &Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000138 void WriteObjcMetaData(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000139 };
140}
141
Chris Lattner8a12c272007-10-11 18:38:32 +0000142ASTConsumer *clang::CreateCodeRewriterTest() { return new RewriteTest(); }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000143
Chris Lattnerf04da132007-10-24 17:06:59 +0000144//===----------------------------------------------------------------------===//
145// Top Level Driver Code
146//===----------------------------------------------------------------------===//
147
Chris Lattner8a12c272007-10-11 18:38:32 +0000148void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000149 // Two cases: either the decl could be in the main file, or it could be in a
150 // #included file. If the former, rewrite it now. If the later, check to see
151 // if we rewrote the #include/#import.
152 SourceLocation Loc = D->getLocation();
153 Loc = SM->getLogicalLoc(Loc);
154
155 // If this is for a builtin, ignore it.
156 if (Loc.isInvalid()) return;
157
Steve Naroffebf2b562007-10-23 23:50:29 +0000158 // Look for built-in declarations that we need to refer during the rewrite.
159 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000160 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000161 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
162 // declared in <Foundation/NSString.h>
163 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
164 ConstantStringClassReference = FVD;
165 return;
166 }
Steve Naroffbef11852007-10-26 20:53:56 +0000167 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
168 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000169 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
170 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000171 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
172 RewriteProtocolDecl(PD);
Steve Naroffebf2b562007-10-23 23:50:29 +0000173 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000174 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000175 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
176 return HandleDeclInMainFile(D);
177
Chris Lattnerf04da132007-10-24 17:06:59 +0000178 // Otherwise, see if there is a #import in the main file that should be
179 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000180 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000181}
182
Chris Lattnerf04da132007-10-24 17:06:59 +0000183/// HandleDeclInMainFile - This is called for each top-level decl defined in the
184/// main file of the input.
185void RewriteTest::HandleDeclInMainFile(Decl *D) {
186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
187 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000188 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Chris Lattnerf04da132007-10-24 17:06:59 +0000189
190 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
191 ClassImplementation.push_back(CI);
192 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
193 CategoryImplementation.push_back(CI);
194 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
195 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000196 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
197 if (VD->getInit())
198 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
199 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000200 // Nothing yet.
201}
202
203RewriteTest::~RewriteTest() {
204 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000205
206 // Rewrite tabs if we care.
207 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000208
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000209 // Rewrite Objective-c meta data*
210 std::string ResultStr;
211 WriteObjcMetaData(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000212
Chris Lattnerf04da132007-10-24 17:06:59 +0000213 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
214 // we are done.
215 if (const RewriteBuffer *RewriteBuf =
216 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000217 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000218 std::string S(RewriteBuf->begin(), RewriteBuf->end());
219 printf("%s\n", S.c_str());
220 } else {
221 printf("No changes\n");
222 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000223 // Emit metadata.
224 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000225}
226
Chris Lattnerf04da132007-10-24 17:06:59 +0000227//===----------------------------------------------------------------------===//
228// Syntactic (non-AST) Rewriting Code
229//===----------------------------------------------------------------------===//
230
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000231void RewriteTest::RewriteInclude(SourceLocation Loc) {
232 // Rip up the #include stack to the main file.
233 SourceLocation IncLoc = Loc, NextLoc = Loc;
234 do {
235 IncLoc = Loc;
236 Loc = SM->getLogicalLoc(NextLoc);
237 NextLoc = SM->getIncludeLoc(Loc);
238 } while (!NextLoc.isInvalid());
239
240 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
241 // IncLoc indicates the header that was included if it is useful.
242 IncLoc = SM->getLogicalLoc(IncLoc);
243 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
244 Loc == LastIncLoc)
245 return;
246 LastIncLoc = Loc;
247
248 unsigned IncCol = SM->getColumnNumber(Loc);
249 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
250
251 // Replace the #import with #include.
252 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
253}
254
Chris Lattnerf04da132007-10-24 17:06:59 +0000255void RewriteTest::RewriteTabs() {
256 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
257 const char *MainBufStart = MainBuf.first;
258 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000259
Chris Lattnerf04da132007-10-24 17:06:59 +0000260 // Loop over the whole file, looking for tabs.
261 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
262 if (*BufPtr != '\t')
263 continue;
264
265 // Okay, we found a tab. This tab will turn into at least one character,
266 // but it depends on which 'virtual column' it is in. Compute that now.
267 unsigned VCol = 0;
268 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
269 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
270 ++VCol;
271
272 // Okay, now that we know the virtual column, we know how many spaces to
273 // insert. We assume 8-character tab-stops.
274 unsigned Spaces = 8-(VCol & 7);
275
276 // Get the location of the tab.
277 SourceLocation TabLoc =
278 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
279
280 // Rewrite the single tab character into a sequence of spaces.
281 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
282 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000283}
284
285
Chris Lattnerf04da132007-10-24 17:06:59 +0000286void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
287 int numDecls = ClassDecl->getNumForwardDecls();
288 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
289
290 // Get the start location and compute the semi location.
291 SourceLocation startLoc = ClassDecl->getLocation();
292 const char *startBuf = SM->getCharacterData(startLoc);
293 const char *semiPtr = strchr(startBuf, ';');
294
295 // Translate to typedef's that forward reference structs with the same name
296 // as the class. As a convenience, we include the original declaration
297 // as a comment.
298 std::string typedefString;
299 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000300 typedefString.append(startBuf, semiPtr-startBuf+1);
301 typedefString += "\n";
302 for (int i = 0; i < numDecls; i++) {
303 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff8749be52007-10-31 22:11:35 +0000304 if (ObjcForwardDecls.count(ForwardDecl))
305 continue;
Steve Naroff32174822007-11-09 12:50:28 +0000306 typedefString += "#ifndef _REWRITER_typedef_";
307 typedefString += ForwardDecl->getName();
308 typedefString += "\n";
309 typedefString += "#define _REWRITER_typedef_";
310 typedefString += ForwardDecl->getName();
311 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000312 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000313 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000314 typedefString += ";\n#endif\n";
Steve Naroff8749be52007-10-31 22:11:35 +0000315 // Mark this typedef as having been generated.
316 if (!ObjcForwardDecls.insert(ForwardDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000317 assert(false && "typedef already output");
Steve Naroff934f2762007-10-24 22:48:43 +0000318 }
319
320 // Replace the @class with typedefs corresponding to the classes.
321 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
322 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000323}
324
Steve Naroff423cb562007-10-30 13:30:57 +0000325void RewriteTest::RewriteMethods(int nMethods, ObjcMethodDecl **Methods) {
326 for (int i = 0; i < nMethods; i++) {
327 ObjcMethodDecl *Method = Methods[i];
328 SourceLocation Loc = Method->getLocStart();
329
Chris Lattner28d1fe82007-11-08 04:41:51 +0000330 Rewrite.InsertText(Loc, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000331
332 // FIXME: handle methods that are declared across multiple lines.
333 }
334}
335
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000336void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
337{
338 for (int i = 0; i < nProperties; i++) {
339 ObjcPropertyDecl *Property = Properties[i];
340 SourceLocation Loc = Property->getLocation();
341
342 Rewrite.ReplaceText(Loc, 0, "// ", 3);
343
344 // FIXME: handle properties that are declared across multiple lines.
345 }
346}
347
Steve Naroff423cb562007-10-30 13:30:57 +0000348void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
349 SourceLocation LocStart = CatDecl->getLocStart();
350
351 // FIXME: handle category headers that are declared across multiple lines.
352 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
353
354 RewriteMethods(CatDecl->getNumInstanceMethods(),
355 CatDecl->getInstanceMethods());
356 RewriteMethods(CatDecl->getNumClassMethods(),
357 CatDecl->getClassMethods());
358 // Lastly, comment out the @end.
359 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
360}
361
Steve Naroff752d6ef2007-10-30 16:42:30 +0000362void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
363 SourceLocation LocStart = PDecl->getLocStart();
364
365 // FIXME: handle protocol headers that are declared across multiple lines.
366 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
367
368 RewriteMethods(PDecl->getNumInstanceMethods(),
369 PDecl->getInstanceMethods());
370 RewriteMethods(PDecl->getNumClassMethods(),
371 PDecl->getClassMethods());
372 // Lastly, comment out the @end.
373 Rewrite.ReplaceText(PDecl->getAtEndLoc(), 0, "// ", 3);
374}
375
Steve Naroffbef11852007-10-26 20:53:56 +0000376void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000377
378 SourceLocation LocStart = ClassDecl->getLocStart();
379 SourceLocation LocEnd = ClassDecl->getLocEnd();
380
381 const char *startBuf = SM->getCharacterData(LocStart);
382 const char *endBuf = SM->getCharacterData(LocEnd);
383
Steve Naroff2feac5e2007-10-30 03:43:13 +0000384 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Steve Narofff908a872007-10-30 02:23:23 +0000385
386 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000387 if (!ObjcForwardDecls.count(ClassDecl)) {
388 // we haven't seen a forward decl - generate a typedef.
Steve Naroff32174822007-11-09 12:50:28 +0000389 ResultStr += "#ifndef _REWRITER_typedef_";
390 ResultStr += ClassDecl->getName();
391 ResultStr += "\n";
392 ResultStr += "#define _REWRITER_typedef_";
393 ResultStr += ClassDecl->getName();
394 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000395 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000396 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000397 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000398
399 // Mark this typedef as having been generated.
400 ObjcForwardDecls.insert(ClassDecl);
401 }
Steve Narofff908a872007-10-30 02:23:23 +0000402 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
403
Steve Naroff2feac5e2007-10-30 03:43:13 +0000404 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
Steve Narofff908a872007-10-30 02:23:23 +0000405 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000406 RewriteProperties(ClassDecl->getNumPropertyDecl(),
407 ClassDecl->getPropertyDecl());
Steve Naroff423cb562007-10-30 13:30:57 +0000408 RewriteMethods(ClassDecl->getNumInstanceMethods(),
409 ClassDecl->getInstanceMethods());
410 RewriteMethods(ClassDecl->getNumClassMethods(),
411 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000412
Steve Naroff2feac5e2007-10-30 03:43:13 +0000413 // Lastly, comment out the @end.
414 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000415}
416
Chris Lattnerf04da132007-10-24 17:06:59 +0000417//===----------------------------------------------------------------------===//
418// Function Body / Expression rewriting
419//===----------------------------------------------------------------------===//
420
Steve Narofff3473a72007-11-09 15:20:18 +0000421Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000422 // Otherwise, just rewrite all children.
423 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
424 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000425 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000426 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000427 if (newStmt)
428 *CI = newStmt;
429 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000430
431 // Handle specific things.
432 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
433 return RewriteAtEncode(AtEncode);
Steve Naroffb42f8412007-11-05 14:50:49 +0000434
435 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
436 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000437
438 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
439 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000440
Steve Naroff934f2762007-10-24 22:48:43 +0000441 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
442 // Before we rewrite it, put the original message expression in a comment.
443 SourceLocation startLoc = MessExpr->getLocStart();
444 SourceLocation endLoc = MessExpr->getLocEnd();
445
446 const char *startBuf = SM->getCharacterData(startLoc);
447 const char *endBuf = SM->getCharacterData(endLoc);
448
449 std::string messString;
450 messString += "// ";
451 messString.append(startBuf, endBuf-startBuf+1);
452 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000453
Steve Naroff934f2762007-10-24 22:48:43 +0000454 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
455 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
456 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000457 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000458 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000459 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000460
461 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
462 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000463
464 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
465 return RewriteObjcThrowStmt(StmtThrow);
466
Chris Lattnere64b7772007-10-24 16:57:36 +0000467 // Return this stmt unmodified.
468 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000469}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000470
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000471Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000472 // Get the start location and compute the semi location.
473 SourceLocation startLoc = S->getLocStart();
474 const char *startBuf = SM->getCharacterData(startLoc);
475
476 assert((*startBuf == '@') && "bogus @try location");
477
478 std::string buf;
479 // declare a new scope with two variables, _stack and _rethrow.
480 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
481 buf += "int buf[18/*32-bit i386*/];\n";
482 buf += "char *pointers[4];} _stack;\n";
483 buf += "id volatile _rethrow = 0;\n";
484 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000485 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000486
487 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
488
489 startLoc = S->getTryBody()->getLocEnd();
490 startBuf = SM->getCharacterData(startLoc);
491
492 assert((*startBuf == '}') && "bogus @try block");
493
494 SourceLocation lastCurlyLoc = startLoc;
495
496 startLoc = startLoc.getFileLocWithOffset(1);
497 buf = " /* @catch begin */ else {\n";
498 buf += " id _caught = objc_exception_extract(&_stack);\n";
499 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000500 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000501 buf += " _rethrow = objc_exception_extract(&_stack);\n";
502 buf += " else { /* @catch continue */";
503
Chris Lattner28d1fe82007-11-08 04:41:51 +0000504 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000505
506 bool sawIdTypedCatch = false;
507 Stmt *lastCatchBody = 0;
508 ObjcAtCatchStmt *catchList = S->getCatchStmts();
509 while (catchList) {
510 Stmt *catchStmt = catchList->getCatchParamStmt();
511
512 if (catchList == S->getCatchStmts())
513 buf = "if ("; // we are generating code for the first catch clause
514 else
515 buf = "else if (";
516 startLoc = catchList->getLocStart();
517 startBuf = SM->getCharacterData(startLoc);
518
519 assert((*startBuf == '@') && "bogus @catch location");
520
521 const char *lParenLoc = strchr(startBuf, '(');
522
523 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
524 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
525 if (t == Context->getObjcIdType()) {
526 buf += "1) { ";
527 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
528 buf.c_str(), buf.size());
529 sawIdTypedCatch = true;
530 } else if (const PointerType *pType = t->getAsPointerType()) {
531 ObjcInterfaceType *cls; // Should be a pointer to a class.
532
533 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
534 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000535 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000536 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000537 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000538 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
539 buf.c_str(), buf.size());
540 }
541 }
542 // Now rewrite the body...
543 lastCatchBody = catchList->getCatchBody();
544 SourceLocation rParenLoc = catchList->getRParenLoc();
545 SourceLocation bodyLoc = lastCatchBody->getLocStart();
546 const char *bodyBuf = SM->getCharacterData(bodyLoc);
547 const char *rParenBuf = SM->getCharacterData(rParenLoc);
548 assert((*rParenBuf == ')') && "bogus @catch paren location");
549 assert((*bodyBuf == '{') && "bogus @catch body location");
550
551 buf = " = _caught;";
552 // Here we replace ") {" with "= _caught;" (which initializes and
553 // declares the @catch parameter).
554 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
555 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000556 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000557 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000558 }
Steve Naroff75730982007-11-07 04:08:17 +0000559 catchList = catchList->getNextCatchStmt();
560 }
561 // Complete the catch list...
562 if (lastCatchBody) {
563 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
564 const char *bodyBuf = SM->getCharacterData(bodyLoc);
565 assert((*bodyBuf == '}') && "bogus @catch body location");
566 bodyLoc = bodyLoc.getFileLocWithOffset(1);
567 buf = " } } /* @catch end */\n";
568
Chris Lattner28d1fe82007-11-08 04:41:51 +0000569 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000570
571 // Set lastCurlyLoc
572 lastCurlyLoc = lastCatchBody->getLocEnd();
573 }
574 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
575 startLoc = finalStmt->getLocStart();
576 startBuf = SM->getCharacterData(startLoc);
577 assert((*startBuf == '@') && "bogus @finally start");
578
579 buf = "/* @finally */";
580 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
581
582 Stmt *body = finalStmt->getFinallyBody();
583 SourceLocation startLoc = body->getLocStart();
584 SourceLocation endLoc = body->getLocEnd();
585 const char *startBuf = SM->getCharacterData(startLoc);
586 const char *endBuf = SM->getCharacterData(endLoc);
587 assert((*startBuf == '{') && "bogus @finally body location");
588 assert((*endBuf == '}') && "bogus @finally body location");
589
590 startLoc = startLoc.getFileLocWithOffset(1);
591 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000592 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000593 endLoc = endLoc.getFileLocWithOffset(-1);
594 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000595 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000596
597 // Set lastCurlyLoc
598 lastCurlyLoc = body->getLocEnd();
599 }
600 // Now emit the final closing curly brace...
601 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
602 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000603 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000604 return 0;
605}
606
607Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
608 return 0;
609}
610
611Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
612 return 0;
613}
614
Steve Naroff2bd03922007-11-07 15:32:26 +0000615// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
616// the throw expression is typically a message expression that's already
617// been rewritten! (which implies the SourceLocation's are invalid).
618Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
619 // Get the start location and compute the semi location.
620 SourceLocation startLoc = S->getLocStart();
621 const char *startBuf = SM->getCharacterData(startLoc);
622
623 assert((*startBuf == '@') && "bogus @throw location");
624
625 std::string buf;
626 /* void objc_exception_throw(id) __attribute__((noreturn)); */
627 buf = "objc_exception_throw(";
628 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
629 const char *semiBuf = strchr(startBuf, ';');
630 assert((*semiBuf == ';') && "@throw: can't find ';'");
631 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
632 buf = ");";
633 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
634 return 0;
635}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000636
Chris Lattnere64b7772007-10-24 16:57:36 +0000637Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000638 // Create a new string expression.
639 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000640 std::string StrEncoding;
641 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
642 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
643 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000644 SourceLocation(), SourceLocation());
645 Rewrite.ReplaceStmt(Exp, Replacement);
Chris Lattnere64b7772007-10-24 16:57:36 +0000646 delete Exp;
647 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000648}
649
Steve Naroffb42f8412007-11-05 14:50:49 +0000650Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
651 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
652 // Create a call to sel_registerName("selName").
653 llvm::SmallVector<Expr*, 8> SelExprs;
654 QualType argType = Context->getPointerType(Context->CharTy);
655 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
656 Exp->getSelector().getName().size(),
657 false, argType, SourceLocation(),
658 SourceLocation()));
659 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
660 &SelExprs[0], SelExprs.size());
661 Rewrite.ReplaceStmt(Exp, SelExp);
662 delete Exp;
663 return SelExp;
664}
665
Steve Naroff934f2762007-10-24 22:48:43 +0000666CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
667 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000668 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000669 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000670
671 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000672 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000673
674 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000675 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000676 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
677
678 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000679
Steve Naroff934f2762007-10-24 22:48:43 +0000680 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
681}
682
Steve Naroffd5255f52007-11-01 13:24:47 +0000683static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
684 const char *&startRef, const char *&endRef) {
685 while (startBuf < endBuf) {
686 if (*startBuf == '<')
687 startRef = startBuf; // mark the start.
688 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000689 if (startRef && *startRef == '<') {
690 endRef = startBuf; // mark the end.
691 return true;
692 }
693 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000694 }
695 startBuf++;
696 }
697 return false;
698}
699
700bool RewriteTest::needToScanForQualifiers(QualType T) {
701 // FIXME: we don't currently represent "id <Protocol>" in the type system.
702 if (T == Context->getObjcIdType())
703 return true;
704
705 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000706 Type *pointeeType = pType->getPointeeType().getTypePtr();
707 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
708 return true; // we have "Class <Protocol> *".
709 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000710 return false;
711}
712
713void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
714 const FunctionTypeProto *proto, FunctionDecl *FD) {
715
716 if (needToScanForQualifiers(proto->getResultType())) {
717 // Since types are unique, we need to scan the buffer.
718 SourceLocation Loc = FD->getLocation();
719
720 const char *endBuf = SM->getCharacterData(Loc);
721 const char *startBuf = endBuf;
722 while (*startBuf != ';')
723 startBuf--; // scan backward (from the decl location) for return type.
724 const char *startRef = 0, *endRef = 0;
725 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
726 // Get the locations of the startRef, endRef.
727 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
728 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
729 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000730 Rewrite.InsertText(LessLoc, "/*", 2);
731 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000732 }
733 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000734 // Now check arguments.
735 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
736 if (needToScanForQualifiers(proto->getArgType(i))) {
737 // Since types are unique, we need to scan the buffer.
738 SourceLocation Loc = FD->getLocation();
739
740 const char *startBuf = SM->getCharacterData(Loc);
741 const char *endBuf = startBuf;
742 while (*endBuf != ';')
743 endBuf++; // scan forward (from the decl location) for argument types.
744 const char *startRef = 0, *endRef = 0;
745 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
746 // Get the locations of the startRef, endRef.
747 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
748 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
749 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000750 Rewrite.InsertText(LessLoc, "/*", 2);
751 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +0000752 }
753 }
754 }
Steve Naroff9165ad32007-10-31 04:38:33 +0000755}
756
Steve Naroff09b266e2007-10-30 23:14:51 +0000757void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
758 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +0000759 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000760 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +0000761 return;
762 }
763 // Check for ObjC 'id' and class types that have been adorned with protocol
764 // information (id<p>, C<p>*). The protocol references need to be rewritten!
765 const FunctionType *funcType = FD->getType()->getAsFunctionType();
766 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +0000767 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
768 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +0000769}
770
771// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
772void RewriteTest::SynthMsgSendFunctionDecl() {
773 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
774 llvm::SmallVector<QualType, 16> ArgTys;
775 QualType argT = Context->getObjcIdType();
776 assert(!argT.isNull() && "Can't find 'id' type");
777 ArgTys.push_back(argT);
778 argT = Context->getObjcSelType();
779 assert(!argT.isNull() && "Can't find 'SEL' type");
780 ArgTys.push_back(argT);
781 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
782 &ArgTys[0], ArgTys.size(),
783 true /*isVariadic*/);
784 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
785 msgSendIdent, msgSendType,
786 FunctionDecl::Extern, false, 0);
787}
788
789// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
790void RewriteTest::SynthGetClassFunctionDecl() {
791 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
792 llvm::SmallVector<QualType, 16> ArgTys;
793 ArgTys.push_back(Context->getPointerType(
794 Context->CharTy.getQualifiedType(QualType::Const)));
795 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
796 &ArgTys[0], ArgTys.size(),
797 false /*isVariadic*/);
798 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
799 getClassIdent, getClassType,
800 FunctionDecl::Extern, false, 0);
801}
802
Steve Naroff96984642007-11-08 14:30:50 +0000803// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
804void RewriteTest::SynthCFStringFunctionDecl() {
805 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
806 llvm::SmallVector<QualType, 16> ArgTys;
807 ArgTys.push_back(Context->getPointerType(
808 Context->CharTy.getQualifiedType(QualType::Const)));
809 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
810 &ArgTys[0], ArgTys.size(),
811 false /*isVariadic*/);
812 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
813 getClassIdent, getClassType,
814 FunctionDecl::Extern, false, 0);
815}
816
Steve Naroffbeaf2992007-11-03 11:27:19 +0000817Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +0000818#if 1
819 // This rewrite is specific to GCC, which has builtin support for CFString.
820 if (!CFStringFunctionDecl)
821 SynthCFStringFunctionDecl();
822 // Create a call to __builtin___CFStringMakeConstantString("cstr").
823 llvm::SmallVector<Expr*, 8> StrExpr;
824 StrExpr.push_back(Exp->getString());
825 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
826 &StrExpr[0], StrExpr.size());
827 // cast to NSConstantString *
828 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
829 Rewrite.ReplaceStmt(Exp, cast);
830 delete Exp;
831 return cast;
832#else
Steve Naroffbeaf2992007-11-03 11:27:19 +0000833 assert(ConstantStringClassReference && "Can't find constant string reference");
834 llvm::SmallVector<Expr*, 4> InitExprs;
835
836 // Synthesize "(Class)&_NSConstantStringClassReference"
837 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
838 ConstantStringClassReference->getType(),
839 SourceLocation());
840 QualType expType = Context->getPointerType(ClsRef->getType());
841 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
842 expType, SourceLocation());
843 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
844 SourceLocation());
845 InitExprs.push_back(cast); // set the 'isa'.
846 InitExprs.push_back(Exp->getString()); // set "char *bytes".
847 unsigned IntSize = static_cast<unsigned>(
848 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
849 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
850 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
851 Exp->getLocStart());
852 InitExprs.push_back(len); // set "int numBytes".
853
854 // struct NSConstantString
855 QualType CFConstantStrType = Context->getCFConstantStringType();
856 // (struct NSConstantString) { <exprs from above> }
857 InitListExpr *ILE = new InitListExpr(SourceLocation(),
858 &InitExprs[0], InitExprs.size(),
859 SourceLocation());
860 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
861 // struct NSConstantString *
862 expType = Context->getPointerType(StrRep->getType());
863 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
864 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +0000865 // cast to NSConstantString *
866 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +0000867 Rewrite.ReplaceStmt(Exp, cast);
868 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +0000869 return cast;
Steve Naroff96984642007-11-08 14:30:50 +0000870#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +0000871}
872
Steve Naroff934f2762007-10-24 22:48:43 +0000873Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000874 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +0000875 if (!MsgSendFunctionDecl)
876 SynthMsgSendFunctionDecl();
877 if (!GetClassFunctionDecl)
878 SynthGetClassFunctionDecl();
Steve Naroff934f2762007-10-24 22:48:43 +0000879
880 // Synthesize a call to objc_msgSend().
881 llvm::SmallVector<Expr*, 8> MsgExprs;
882 IdentifierInfo *clsName = Exp->getClassName();
883
884 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
885 if (clsName) { // class message.
886 llvm::SmallVector<Expr*, 8> ClsExprs;
887 QualType argType = Context->getPointerType(Context->CharTy);
888 ClsExprs.push_back(new StringLiteral(clsName->getName(),
889 clsName->getLength(),
890 false, argType, SourceLocation(),
891 SourceLocation()));
892 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
893 &ClsExprs[0], ClsExprs.size());
894 MsgExprs.push_back(Cls);
895 } else // instance message.
896 MsgExprs.push_back(Exp->getReceiver());
897
Steve Naroffbeaf2992007-11-03 11:27:19 +0000898 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +0000899 llvm::SmallVector<Expr*, 8> SelExprs;
900 QualType argType = Context->getPointerType(Context->CharTy);
901 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
902 Exp->getSelector().getName().size(),
903 false, argType, SourceLocation(),
904 SourceLocation()));
905 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
906 &SelExprs[0], SelExprs.size());
907 MsgExprs.push_back(SelExp);
908
909 // Now push any user supplied arguments.
910 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
911 MsgExprs.push_back(Exp->getArg(i));
912 // We've transferred the ownership to MsgExprs. Null out the argument in
913 // the original expression, since we will delete it below.
914 Exp->setArg(i, 0);
915 }
Steve Naroffab972d32007-11-04 22:37:50 +0000916 // Generate the funky cast.
917 CastExpr *cast;
918 llvm::SmallVector<QualType, 8> ArgTypes;
919 QualType returnType;
920
921 // Push 'id' and 'SEL', the 2 implicit arguments.
922 ArgTypes.push_back(Context->getObjcIdType());
923 ArgTypes.push_back(Context->getObjcSelType());
924 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
925 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +0000926 for (int i = 0; i < mDecl->getNumParams(); i++) {
927 QualType t = mDecl->getParamDecl(i)->getType();
928 if (t == Context->getObjcClassType())
929 t = Context->getObjcIdType(); // Convert "Class"->"id"
930 ArgTypes.push_back(t);
931 }
Steve Naroffab972d32007-11-04 22:37:50 +0000932 returnType = mDecl->getResultType();
933 } else {
934 returnType = Context->getObjcIdType();
935 }
936 // Get the type, we will need to reference it in a couple spots.
937 QualType msgSendType = MsgSendFunctionDecl->getType();
938
939 // Create a reference to the objc_msgSend() declaration.
940 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFunctionDecl, msgSendType, SourceLocation());
941
942 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
943 // If we don't do this cast, we get the following bizarre warning/note:
944 // xx.m:13: warning: function called through a non-compatible type
945 // xx.m:13: note: if this code is reached, the program will abort
946 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
947 SourceLocation());
948
949 // Now do the "normal" pointer to function cast.
950 QualType castType = Context->getFunctionType(returnType,
951 &ArgTypes[0], ArgTypes.size(),
952 false/*FIXME:variadic*/);
953 castType = Context->getPointerType(castType);
954 cast = new CastExpr(castType, cast, SourceLocation());
955
956 // Don't forget the parens to enforce the proper binding.
957 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
958
959 const FunctionType *FT = msgSendType->getAsFunctionType();
960 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
961 FT->getResultType(), SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +0000962 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +0000963 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +0000964
Chris Lattnere64b7772007-10-24 16:57:36 +0000965 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +0000966 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +0000967}
968
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000969/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
970/// an objective-c class with ivars.
971void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
972 std::string &Result) {
973 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
974 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +0000975 // Do not synthesize more than once.
976 if (ObjcSynthesizedStructs.count(CDecl))
977 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000978 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
979 if (RCDecl && !ObjcSynthesizedStructs.count(RCDecl)) {
980 // Do it for the root
981 SynthesizeObjcInternalStruct(RCDecl, Result);
982 }
983
984 int NumIvars = CDecl->getIntfDeclNumIvars();
Fariborz Jahanianaff56d02007-10-31 22:57:04 +0000985 // If no ivars and no root or if its root, directly or indirectly,
Fariborz Jahanianf1de0ca2007-10-31 23:53:01 +0000986 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000987 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl)))
988 return;
989
Steve Naroff04960052007-11-01 17:12:31 +0000990 Result += "\nstruct ";
991 Result += CDecl->getName();
992 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
993 Result += " {\n struct ";
994 Result += RCDecl->getName();
995 Result += " _";
996 Result += RCDecl->getName();
997 Result += ";\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000998 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +0000999 else
1000 Result += " {";
Steve Naroff8749be52007-10-31 22:11:35 +00001001
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001002 if (NumIvars > 0) {
1003 SourceLocation LocStart = CDecl->getLocStart();
1004 SourceLocation LocEnd = CDecl->getLocEnd();
1005
1006 const char *startBuf = SM->getCharacterData(LocStart);
1007 const char *endBuf = SM->getCharacterData(LocEnd);
1008 startBuf = strchr(startBuf, '{');
1009 assert((startBuf && endBuf)
1010 && "SynthesizeObjcInternalStruct - malformed @interface");
1011 startBuf++; // past '{'
1012 while (startBuf < endBuf) {
1013 if (*startBuf == '@') {
1014 startBuf = strchr(startBuf, 'p');
1015 // FIXME: presence of @public, etc. inside comment results in
1016 // this transformation as well, which is still correct c-code.
1017 if (!strncmp(startBuf, "public", strlen("public"))) {
1018 startBuf += strlen("public");
1019 Result += "/* @public */";
1020 }
1021 else if (!strncmp(startBuf, "private", strlen("private"))) {
1022 startBuf += strlen("private");
1023 Result += "/* @private */";
1024 }
1025 else if (!strncmp(startBuf, "protected", strlen("protected"))) {
1026 startBuf += strlen("protected");
1027 Result += "/* @protected */";
1028 }
1029 }
1030 Result += *startBuf++;
1031 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001032 }
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001033
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001034 Result += "};\n";
1035 // Mark this struct as having been generated.
1036 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001037 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001038}
1039
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001040// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1041/// class methods.
1042void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl **Methods,
1043 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001044 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001045 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001046 const char *ClassName,
1047 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001048 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001049 if (NumMethods > 0 && !objc_impl_method) {
1050 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001051 SEL _cmd;
1052 char *method_types;
1053 void *_imp;
1054 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001055 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001056 Result += "\nstruct _objc_method {\n";
1057 Result += "\tSEL _cmd;\n";
1058 Result += "\tchar *method_types;\n";
1059 Result += "\tvoid *_imp;\n";
1060 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001061
1062 /* struct _objc_method_list {
1063 struct _objc_method_list *next_method;
1064 int method_count;
1065 struct _objc_method method_list[];
1066 }
1067 */
1068 Result += "\nstruct _objc_method_list {\n";
1069 Result += "\tstruct _objc_method_list *next_method;\n";
1070 Result += "\tint method_count;\n";
1071 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001072 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001073 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001074 // Build _objc_method_list for class's methods if needed
1075 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001076 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001077 Result += prefix;
1078 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1079 Result += "_METHODS_";
1080 Result += ClassName;
1081 Result += " __attribute__ ((section (\"__OBJC, __";
1082 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001083 Result += "_meth\")))= ";
1084 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1085
1086 Result += "\t,{{(SEL)\"";
1087 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001088 std::string MethodTypeString;
1089 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1090 Result += "\", \"";
1091 Result += MethodTypeString;
1092 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001093 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001094 // TODO: Need method address as 3rd initializer.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001095 Result += "\t ,{(SEL)\"";
1096 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001097 std::string MethodTypeString;
1098 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1099 Result += "\", \"";
1100 Result += MethodTypeString;
1101 Result += "\", 0}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001102 }
1103 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001104 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001105}
1106
1107/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1108void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1109 int NumProtocols,
1110 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001111 const char *ClassName,
1112 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001113 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001114 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001115 for (int i = 0; i < NumProtocols; i++) {
1116 ObjcProtocolDecl *PDecl = Protocols[i];
1117 // Output struct protocol_methods holder of method selector and type.
1118 if (!objc_protocol_methods &&
1119 (PDecl->getNumInstanceMethods() > 0
1120 || PDecl->getNumClassMethods() > 0)) {
1121 /* struct protocol_methods {
1122 SEL _cmd;
1123 char *method_types;
1124 }
1125 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001126 Result += "\nstruct protocol_methods {\n";
1127 Result += "\tSEL _cmd;\n";
1128 Result += "\tchar *method_types;\n";
1129 Result += "};\n";
1130
1131 /* struct _objc_protocol_method_list {
1132 int protocol_method_count;
1133 struct protocol_methods protocols[];
1134 }
1135 */
1136 Result += "\nstruct _objc_protocol_method_list {\n";
1137 Result += "\tint protocol_method_count;\n";
1138 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001139 objc_protocol_methods = true;
1140 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001141
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001142 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001143 int NumMethods = PDecl->getNumInstanceMethods();
1144 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001145 Result += "\nstatic struct _objc_protocol_method_list "
1146 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1147 Result += PDecl->getName();
1148 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1149 "{\n\t" + utostr(NumMethods) + "\n";
1150
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001151 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001152 Result += "\t,{{(SEL)\"";
1153 Result += Methods[0]->getSelector().getName().c_str();
1154 Result += "\", \"\"}\n";
1155
1156 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001157 Result += "\t ,{(SEL)\"";
1158 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001159 std::string MethodTypeString;
1160 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1161 Result += "\", \"";
1162 Result += MethodTypeString;
1163 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001164 }
1165 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001166 }
1167
1168 // Output class methods declared in this protocol.
1169 NumMethods = PDecl->getNumClassMethods();
1170 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001171 Result += "\nstatic struct _objc_protocol_method_list "
1172 "_OBJC_PROTOCOL_CLASS_METHODS_";
1173 Result += PDecl->getName();
1174 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1175 "{\n\t";
1176 Result += utostr(NumMethods);
1177 Result += "\n";
1178
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001179 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001180 Result += "\t,{{(SEL)\"";
1181 Result += Methods[0]->getSelector().getName().c_str();
1182 Result += "\", \"\"}\n";
1183
1184 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001185 Result += "\t ,{(SEL)\"";
1186 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001187 std::string MethodTypeString;
1188 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1189 Result += "\", \"";
1190 Result += MethodTypeString;
1191 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001192 }
1193 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001194 }
1195 // Output:
1196 /* struct _objc_protocol {
1197 // Objective-C 1.0 extensions
1198 struct _objc_protocol_extension *isa;
1199 char *protocol_name;
1200 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001201 struct _objc_protocol_method_list *instance_methods;
1202 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001203 };
1204 */
1205 static bool objc_protocol = false;
1206 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001207 Result += "\nstruct _objc_protocol {\n";
1208 Result += "\tstruct _objc_protocol_extension *isa;\n";
1209 Result += "\tchar *protocol_name;\n";
1210 Result += "\tstruct _objc_protocol **protocol_list;\n";
1211 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1212 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1213 Result += "};\n";
1214
1215 /* struct _objc_protocol_list {
1216 struct _objc_protocol_list *next;
1217 int protocol_count;
1218 struct _objc_protocol *class_protocols[];
1219 }
1220 */
1221 Result += "\nstruct _objc_protocol_list {\n";
1222 Result += "\tstruct _objc_protocol_list *next;\n";
1223 Result += "\tint protocol_count;\n";
1224 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1225 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001226 objc_protocol = true;
1227 }
1228
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001229 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1230 Result += PDecl->getName();
1231 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1232 "{\n\t0, \"";
1233 Result += PDecl->getName();
1234 Result += "\", 0, ";
1235 if (PDecl->getInstanceMethods() > 0) {
1236 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1237 Result += PDecl->getName();
1238 Result += ", ";
1239 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001240 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001241 Result += "0, ";
1242 if (PDecl->getClassMethods() > 0) {
1243 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1244 Result += PDecl->getName();
1245 Result += "\n";
1246 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001247 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001248 Result += "0\n";
1249 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001250 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001251 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001252 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1253 Result += prefix;
1254 Result += "_PROTOCOLS_";
1255 Result += ClassName;
1256 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1257 "{\n\t0, ";
1258 Result += utostr(NumProtocols);
1259 Result += "\n";
1260
1261 Result += "\t,{&_OBJC_PROTOCOL_";
1262 Result += Protocols[0]->getName();
1263 Result += " \n";
1264
1265 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001266 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001267 Result += "\t ,&_OBJC_PROTOCOL_";
1268 Result += PDecl->getName();
1269 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001270 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001271 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001272 }
1273}
1274
1275/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1276/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001277void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1278 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001279 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1280 // Find category declaration for this implementation.
1281 ObjcCategoryDecl *CDecl;
1282 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1283 CDecl = CDecl->getNextClassCategory())
1284 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1285 break;
1286 assert(CDecl && "RewriteObjcCategoryImplDecl - bad category");
1287
1288 char *FullCategoryName = (char*)alloca(
1289 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1290 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1291
1292 // Build _objc_method_list for class's instance methods if needed
1293 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1294 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001295 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001296 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001297
1298 // Build _objc_method_list for class's class methods if needed
1299 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1300 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001301 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001302 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001303
1304 // Protocols referenced in class declaration?
1305 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1306 CDecl->getNumReferencedProtocols(),
1307 "CATEGORY",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001308 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001309
1310 /* struct _objc_category {
1311 char *category_name;
1312 char *class_name;
1313 struct _objc_method_list *instance_methods;
1314 struct _objc_method_list *class_methods;
1315 struct _objc_protocol_list *protocols;
1316 // Objective-C 1.0 extensions
1317 uint32_t size; // sizeof (struct _objc_category)
1318 struct _objc_property_list *instance_properties; // category's own
1319 // @property decl.
1320 };
1321 */
1322
1323 static bool objc_category = false;
1324 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001325 Result += "\nstruct _objc_category {\n";
1326 Result += "\tchar *category_name;\n";
1327 Result += "\tchar *class_name;\n";
1328 Result += "\tstruct _objc_method_list *instance_methods;\n";
1329 Result += "\tstruct _objc_method_list *class_methods;\n";
1330 Result += "\tstruct _objc_protocol_list *protocols;\n";
1331 Result += "\tunsigned int size;\n";
1332 Result += "\tstruct _objc_property_list *instance_properties;\n";
1333 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001334 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001335 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001336 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1337 Result += FullCategoryName;
1338 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1339 Result += IDecl->getName();
1340 Result += "\"\n\t, \"";
1341 Result += ClassDecl->getName();
1342 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001343
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001344 if (IDecl->getNumInstanceMethods() > 0) {
1345 Result += "\t, (struct _objc_method_list *)"
1346 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1347 Result += FullCategoryName;
1348 Result += "\n";
1349 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001350 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001351 Result += "\t, 0\n";
1352 if (IDecl->getNumClassMethods() > 0) {
1353 Result += "\t, (struct _objc_method_list *)"
1354 "&_OBJC_CATEGORY_CLASS_METHODS_";
1355 Result += FullCategoryName;
1356 Result += "\n";
1357 }
1358 else
1359 Result += "\t, 0\n";
1360
1361 if (CDecl->getNumReferencedProtocols() > 0) {
1362 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1363 Result += FullCategoryName;
1364 Result += "\n";
1365 }
1366 else
1367 Result += "\t, 0\n";
1368 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001369}
1370
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001371/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1372/// ivar offset.
1373void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1374 ObjcIvarDecl *ivar,
1375 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001376 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001377 Result += IDecl->getName();
1378 Result += ", ";
1379 Result += ivar->getName();
1380 Result += ")";
1381}
1382
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001383//===----------------------------------------------------------------------===//
1384// Meta Data Emission
1385//===----------------------------------------------------------------------===//
1386
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001387void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1388 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001389 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1390
1391 // Build _objc_ivar_list metadata for classes ivars if needed
1392 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1393 ? IDecl->getImplDeclNumIvars()
1394 : (CDecl ? CDecl->getIntfDeclNumIvars() : 0);
1395
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001396 SynthesizeObjcInternalStruct(CDecl, Result);
1397
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001398 if (NumIvars > 0) {
1399 static bool objc_ivar = false;
1400 if (!objc_ivar) {
1401 /* struct _objc_ivar {
1402 char *ivar_name;
1403 char *ivar_type;
1404 int ivar_offset;
1405 };
1406 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001407 Result += "\nstruct _objc_ivar {\n";
1408 Result += "\tchar *ivar_name;\n";
1409 Result += "\tchar *ivar_type;\n";
1410 Result += "\tint ivar_offset;\n";
1411 Result += "};\n";
1412
1413 /* struct _objc_ivar_list {
1414 int ivar_count;
1415 struct _objc_ivar ivar_list[];
1416 };
1417 */
1418 Result += "\nstruct _objc_ivar_list {\n";
1419 Result += "\tint ivar_count;\n";
1420 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001421 objc_ivar = true;
1422 }
1423
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001424 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1425 Result += IDecl->getName();
1426 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1427 "{\n\t";
1428 Result += utostr(NumIvars);
1429 Result += "\n";
1430
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001431 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1432 ? IDecl->getImplDeclIVars()
1433 : CDecl->getIntfDeclIvars();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001434 Result += "\t,{{\"";
1435 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001436 Result += "\", \"";
1437 std::string StrEncoding;
1438 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1439 Result += StrEncoding;
1440 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001441 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1442 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001443 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001444 Result += "\t ,{\"";
1445 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001446 Result += "\", \"";
1447 std::string StrEncoding;
1448 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1449 Result += StrEncoding;
1450 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001451 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1452 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001453 }
1454
1455 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001456 }
1457
1458 // Build _objc_method_list for class's instance methods if needed
1459 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1460 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001461 true,
1462 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001463
1464 // Build _objc_method_list for class's class methods if needed
1465 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001466 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001467 false,
1468 "", IDecl->getName(), Result);
1469
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001470 // Protocols referenced in class declaration?
1471 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1472 CDecl->getNumIntfRefProtocols(),
1473 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001474 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001475
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001476
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001477 // Declaration of class/meta-class metadata
1478 /* struct _objc_class {
1479 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001480 const char *super_class_name;
1481 char *name;
1482 long version;
1483 long info;
1484 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001485 struct _objc_ivar_list *ivars;
1486 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001487 struct objc_cache *cache;
1488 struct objc_protocol_list *protocols;
1489 const char *ivar_layout;
1490 struct _objc_class_ext *ext;
1491 };
1492 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001493 static bool objc_class = false;
1494 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001495 Result += "\nstruct _objc_class {\n";
1496 Result += "\tstruct _objc_class *isa;\n";
1497 Result += "\tconst char *super_class_name;\n";
1498 Result += "\tchar *name;\n";
1499 Result += "\tlong version;\n";
1500 Result += "\tlong info;\n";
1501 Result += "\tlong instance_size;\n";
1502 Result += "\tstruct _objc_ivar_list *ivars;\n";
1503 Result += "\tstruct _objc_method_list *methods;\n";
1504 Result += "\tstruct objc_cache *cache;\n";
1505 Result += "\tstruct _objc_protocol_list *protocols;\n";
1506 Result += "\tconst char *ivar_layout;\n";
1507 Result += "\tstruct _objc_class_ext *ext;\n";
1508 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001509 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001510 }
1511
1512 // Meta-class metadata generation.
1513 ObjcInterfaceDecl *RootClass = 0;
1514 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
1515 while (SuperClass) {
1516 RootClass = SuperClass;
1517 SuperClass = SuperClass->getSuperClass();
1518 }
1519 SuperClass = CDecl->getSuperClass();
1520
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001521 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
1522 Result += CDecl->getName();
1523 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
1524 "{\n\t(struct _objc_class *)\"";
1525 Result += (RootClass ? RootClass->getName() : CDecl->getName());
1526 Result += "\"";
1527
1528 if (SuperClass) {
1529 Result += ", \"";
1530 Result += SuperClass->getName();
1531 Result += "\", \"";
1532 Result += CDecl->getName();
1533 Result += "\"";
1534 }
1535 else {
1536 Result += ", 0, \"";
1537 Result += CDecl->getName();
1538 Result += "\"";
1539 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001540 // TODO: 'ivars' field for root class is currently set to 0.
1541 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001542 Result += ", 0,2, sizeof(struct _objc_class), 0";
1543 if (CDecl->getNumClassMethods() > 0) {
1544 Result += "\n\t, &_OBJC_CLASS_METHODS_";
1545 Result += CDecl->getName();
1546 Result += "\n";
1547 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001548 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001549 Result += ", 0\n";
1550 if (CDecl->getNumIntfRefProtocols() > 0) {
1551 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
1552 Result += CDecl->getName();
1553 Result += ",0,0\n";
1554 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001555 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001556 Result += "\t,0,0,0,0\n";
1557 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001558
1559 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001560 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
1561 Result += CDecl->getName();
1562 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
1563 "{\n\t&_OBJC_METACLASS_";
1564 Result += CDecl->getName();
1565 if (SuperClass) {
1566 Result += ", \"";
1567 Result += SuperClass->getName();
1568 Result += "\", \"";
1569 Result += CDecl->getName();
1570 Result += "\"";
1571 }
1572 else {
1573 Result += ", 0, \"";
1574 Result += CDecl->getName();
1575 Result += "\"";
1576 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001577 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001578 Result += ", 0,1";
1579 if (!ObjcSynthesizedStructs.count(CDecl))
1580 Result += ",0";
1581 else {
1582 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001583 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001584 Result += CDecl->getName();
1585 Result += ")";
1586 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001587 if (NumIvars > 0) {
1588 Result += ", &_OBJC_INSTANCE_VARIABLES_";
1589 Result += CDecl->getName();
1590 Result += "\n\t";
1591 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001592 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001593 Result += ",0";
1594 if (IDecl->getNumInstanceMethods() > 0) {
1595 Result += ", &_OBJC_INSTANCE_METHODS_";
1596 Result += CDecl->getName();
1597 Result += ", 0\n\t";
1598 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001599 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001600 Result += ",0,0";
1601 if (CDecl->getNumIntfRefProtocols() > 0) {
1602 Result += ", &_OBJC_CLASS_PROTOCOLS_";
1603 Result += CDecl->getName();
1604 Result += ", 0,0\n";
1605 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00001606 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001607 Result += ",0,0,0\n";
1608 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00001609}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001610
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001611void RewriteTest::WriteObjcMetaData(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001612 int ClsDefCount = ClassImplementation.size();
1613 int CatDefCount = CategoryImplementation.size();
1614 if (ClsDefCount == 0 && CatDefCount == 0)
1615 return;
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001616
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001617 // TODO: This is temporary until we decide how to access objc types in a
1618 // c program
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001619 Result += "#include <Objc/objc.h>\n";
1620 // This is needed for use of offsetof
1621 Result += "#include <stddef.h>\n";
Fariborz Jahanian454cb012007-10-24 20:54:23 +00001622
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001623 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001624 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001625 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001626
1627 // For each implemented category, write out all its meta data.
1628 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001629 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00001630
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001631 // Write objc_symtab metadata
1632 /*
1633 struct _objc_symtab
1634 {
1635 long sel_ref_cnt;
1636 SEL *refs;
1637 short cls_def_cnt;
1638 short cat_def_cnt;
1639 void *defs[cls_def_cnt + cat_def_cnt];
1640 };
1641 */
1642
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001643 Result += "\nstruct _objc_symtab {\n";
1644 Result += "\tlong sel_ref_cnt;\n";
1645 Result += "\tSEL *refs;\n";
1646 Result += "\tshort cls_def_cnt;\n";
1647 Result += "\tshort cat_def_cnt;\n";
1648 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
1649 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001650
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001651 Result += "static struct _objc_symtab "
1652 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
1653 Result += "\t0, 0, " + utostr(ClsDefCount)
1654 + ", " + utostr(CatDefCount) + "\n";
1655 for (int i = 0; i < ClsDefCount; i++) {
1656 Result += "\t,&_OBJC_CLASS_";
1657 Result += ClassImplementation[i]->getName();
1658 Result += "\n";
1659 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001660
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001661 for (int i = 0; i < CatDefCount; i++) {
1662 Result += "\t,&_OBJC_CATEGORY_";
1663 Result += CategoryImplementation[i]->getClassInterface()->getName();
1664 Result += "_";
1665 Result += CategoryImplementation[i]->getName();
1666 Result += "\n";
1667 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001668
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001669 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001670
1671 // Write objc_module metadata
1672
1673 /*
1674 struct _objc_module {
1675 long version;
1676 long size;
1677 const char *name;
1678 struct _objc_symtab *symtab;
1679 }
1680 */
1681
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001682 Result += "\nstruct _objc_module {\n";
1683 Result += "\tlong version;\n";
1684 Result += "\tlong size;\n";
1685 Result += "\tconst char *name;\n";
1686 Result += "\tstruct _objc_symtab *symtab;\n";
1687 Result += "};\n\n";
1688 Result += "static struct _objc_module "
1689 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001690 Result += "\t" + utostr(OBJC_ABI_VERSION) +
1691 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001692 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00001693}
Chris Lattner311ff022007-10-16 22:36:42 +00001694