blob: 865328cc986edd852f7132f4ecd007b73d1a764b [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 Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff874e2322007-11-15 10:28:18 +000025#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000026using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000028
Chris Lattner77cd2a02007-10-11 00:43:27 +000029namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattner01c57482007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000038 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000040 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff8749be52007-10-31 22:11:35 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +000042 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000050 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000051 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000052
Steve Naroffbeaf2992007-11-03 11:27:19 +000053 // ObjC string constant support.
54 FileVarDecl *ConstantStringClassReference;
55 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000056
Steve Naroff874e2322007-11-15 10:28:18 +000057 // Needed for super.
58 ObjcMethodDecl *CurMethodDecl;
59 RecordDecl *SuperStructDecl;
60
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000061 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000062 public:
Chris Lattner01c57482007-10-17 22:35:30 +000063 void Initialize(ASTContext &context, unsigned mainFileID) {
64 Context = &context;
65 SM = &Context->SourceMgr;
Steve Naroffebf2b562007-10-23 23:50:29 +000066 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000067 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000068 MsgSendStretFunctionDecl = 0;
69 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000070 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000071 GetClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000072 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000073 CFStringFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000074 ConstantStringClassReference = 0;
75 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000076 CurMethodDecl = 0;
77 SuperStructDecl = 0;
78
Chris Lattner26de4652007-12-02 01:13:47 +000079 // Get the ID and start/end of the main file.
80 MainFileID = mainFileID;
81 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
82 MainFileStart = MainBuf->getBufferStart();
83 MainFileEnd = MainBuf->getBufferEnd();
84
85
Chris Lattner01c57482007-10-17 22:35:30 +000086 Rewrite.setSourceMgr(Context->SourceMgr);
Steve Naroffe3abbf52007-11-05 14:55:35 +000087 // declaring objc_selector outside the parameter list removes a silly
88 // scope related warning...
Steve Naroff3cadd032007-12-04 23:59:30 +000089 const char *s = "struct objc_selector; struct objc_class;\n"
90 "#ifndef OBJC_SUPER\n"
91 "struct objc_super { struct objc_object *o; struct objc_object *superClass; };\n"
92 "#define OBJC_SUPER\n"
93 "#endif\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000094 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000095 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +000096 "extern struct objc_object *objc_msgSendSuper"
97 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000098 "extern struct objc_object *objc_msgSend_stret"
99 "(struct objc_object *, struct objc_selector *, ...);\n"
100 "extern struct objc_object *objc_msgSendSuper_stret"
101 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000102 "extern struct objc_object *objc_msgSend_fpret"
103 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000104 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000105 "(const char *);\n"
106 "extern void objc_exception_throw(struct objc_object *);\n"
107 "extern void objc_exception_try_enter(void *);\n"
108 "extern void objc_exception_try_exit(void *);\n"
109 "extern struct objc_object *objc_exception_extract(void *);\n"
110 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000111 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian2c1e9c72007-12-03 23:04:29 +0000112 "#include <objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000113
Steve Naroffab972d32007-11-04 22:37:50 +0000114 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
115 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000116 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000117
Chris Lattnerf04da132007-10-24 17:06:59 +0000118 // Top Level Driver code.
119 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000120 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000121 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000122 ~RewriteTest();
123
124 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000125 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000126 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000127 void RewriteTabs();
128 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000129 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000130 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000131 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000132 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000133 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000134 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000135 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000136 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000137 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +0000138 void RewriteObjcQualifiedInterfaceTypes(
139 const FunctionTypeProto *proto, FunctionDecl *FD);
140 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000141 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
142 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000143
Chris Lattnerf04da132007-10-24 17:06:59 +0000144 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000145 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000146 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000147 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000148 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000149 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000150 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000151 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
152 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
153 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000154 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000155 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
156 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000157 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000158 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000159 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000160 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000161 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000162 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000163 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000164 void SynthSelGetUidFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000165
Chris Lattnerf04da132007-10-24 17:06:59 +0000166 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000167 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
168 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000169
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000170 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
171 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000172
Steve Naroff0416fb92007-11-11 17:19:15 +0000173 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000174 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000175 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000176 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000177 const char *ClassName,
178 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000179
180 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
181 int NumProtocols,
182 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000183 const char *ClassName,
184 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000185 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
186 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000187 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
188 ObjcIvarDecl *ivar,
189 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000190 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000191 };
192}
193
Chris Lattnere365c502007-11-30 22:25:36 +0000194ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
195 return new RewriteTest(Diags);
196}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000197
Chris Lattnerf04da132007-10-24 17:06:59 +0000198//===----------------------------------------------------------------------===//
199// Top Level Driver Code
200//===----------------------------------------------------------------------===//
201
Chris Lattner8a12c272007-10-11 18:38:32 +0000202void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000203 // Two cases: either the decl could be in the main file, or it could be in a
204 // #included file. If the former, rewrite it now. If the later, check to see
205 // if we rewrote the #include/#import.
206 SourceLocation Loc = D->getLocation();
207 Loc = SM->getLogicalLoc(Loc);
208
209 // If this is for a builtin, ignore it.
210 if (Loc.isInvalid()) return;
211
Steve Naroffebf2b562007-10-23 23:50:29 +0000212 // Look for built-in declarations that we need to refer during the rewrite.
213 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000214 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000215 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
216 // declared in <Foundation/NSString.h>
217 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
218 ConstantStringClassReference = FVD;
219 return;
220 }
Steve Naroffbef11852007-10-26 20:53:56 +0000221 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
222 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000223 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
224 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000225 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
226 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000227 } else if (ObjcForwardProtocolDecl *FP =
228 dyn_cast<ObjcForwardProtocolDecl>(D)){
229 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000230 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000231 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000232 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
233 return HandleDeclInMainFile(D);
234
Chris Lattnerf04da132007-10-24 17:06:59 +0000235 // Otherwise, see if there is a #import in the main file that should be
236 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000237 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000238}
239
Chris Lattnerf04da132007-10-24 17:06:59 +0000240/// HandleDeclInMainFile - This is called for each top-level decl defined in the
241/// main file of the input.
242void RewriteTest::HandleDeclInMainFile(Decl *D) {
243 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
244 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000245 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000246
247 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000248 if (Stmt *Body = MD->getBody()) {
249 //Body->dump();
250 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000251 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000252 CurMethodDecl = 0;
253 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000254 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000255 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
256 ClassImplementation.push_back(CI);
257 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
258 CategoryImplementation.push_back(CI);
259 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
260 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000261 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
262 if (VD->getInit())
263 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
264 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000265 // Nothing yet.
266}
267
268RewriteTest::~RewriteTest() {
269 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000270
271 // Rewrite tabs if we care.
272 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000273
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000274 // Rewrite Objective-c meta data*
275 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000276 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000277
Chris Lattnerf04da132007-10-24 17:06:59 +0000278 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
279 // we are done.
280 if (const RewriteBuffer *RewriteBuf =
281 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000282 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000283 std::string S(RewriteBuf->begin(), RewriteBuf->end());
284 printf("%s\n", S.c_str());
285 } else {
286 printf("No changes\n");
287 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000288 // Emit metadata.
289 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000290}
291
Chris Lattnerf04da132007-10-24 17:06:59 +0000292//===----------------------------------------------------------------------===//
293// Syntactic (non-AST) Rewriting Code
294//===----------------------------------------------------------------------===//
295
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000296void RewriteTest::RewriteInclude(SourceLocation Loc) {
297 // Rip up the #include stack to the main file.
298 SourceLocation IncLoc = Loc, NextLoc = Loc;
299 do {
300 IncLoc = Loc;
301 Loc = SM->getLogicalLoc(NextLoc);
302 NextLoc = SM->getIncludeLoc(Loc);
303 } while (!NextLoc.isInvalid());
304
305 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
306 // IncLoc indicates the header that was included if it is useful.
307 IncLoc = SM->getLogicalLoc(IncLoc);
308 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
309 Loc == LastIncLoc)
310 return;
311 LastIncLoc = Loc;
312
313 unsigned IncCol = SM->getColumnNumber(Loc);
314 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
315
316 // Replace the #import with #include.
317 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
318}
319
Chris Lattnerf04da132007-10-24 17:06:59 +0000320void RewriteTest::RewriteTabs() {
321 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
322 const char *MainBufStart = MainBuf.first;
323 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000324
Chris Lattnerf04da132007-10-24 17:06:59 +0000325 // Loop over the whole file, looking for tabs.
326 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
327 if (*BufPtr != '\t')
328 continue;
329
330 // Okay, we found a tab. This tab will turn into at least one character,
331 // but it depends on which 'virtual column' it is in. Compute that now.
332 unsigned VCol = 0;
333 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
334 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
335 ++VCol;
336
337 // Okay, now that we know the virtual column, we know how many spaces to
338 // insert. We assume 8-character tab-stops.
339 unsigned Spaces = 8-(VCol & 7);
340
341 // Get the location of the tab.
342 SourceLocation TabLoc =
343 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
344
345 // Rewrite the single tab character into a sequence of spaces.
346 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
347 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000348}
349
350
Chris Lattnerf04da132007-10-24 17:06:59 +0000351void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
352 int numDecls = ClassDecl->getNumForwardDecls();
353 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
354
355 // Get the start location and compute the semi location.
356 SourceLocation startLoc = ClassDecl->getLocation();
357 const char *startBuf = SM->getCharacterData(startLoc);
358 const char *semiPtr = strchr(startBuf, ';');
359
360 // Translate to typedef's that forward reference structs with the same name
361 // as the class. As a convenience, we include the original declaration
362 // as a comment.
363 std::string typedefString;
364 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000365 typedefString.append(startBuf, semiPtr-startBuf+1);
366 typedefString += "\n";
367 for (int i = 0; i < numDecls; i++) {
368 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000369 typedefString += "#ifndef _REWRITER_typedef_";
370 typedefString += ForwardDecl->getName();
371 typedefString += "\n";
372 typedefString += "#define _REWRITER_typedef_";
373 typedefString += ForwardDecl->getName();
374 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000375 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000376 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000377 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000378 }
379
380 // Replace the @class with typedefs corresponding to the classes.
381 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
382 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000383}
384
Steve Naroff71c0a952007-11-13 23:01:27 +0000385void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000386 for (int i = 0; i < nMethods; i++) {
387 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000388 SourceLocation LocStart = Method->getLocStart();
389 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000390
Steve Naroff1d098f62007-11-14 14:34:23 +0000391 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
392 Rewrite.InsertText(LocStart, "/* ", 3);
393 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
394 } else {
395 Rewrite.InsertText(LocStart, "// ", 3);
396 }
Steve Naroff423cb562007-10-30 13:30:57 +0000397 }
398}
399
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000400void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
401{
402 for (int i = 0; i < nProperties; i++) {
403 ObjcPropertyDecl *Property = Properties[i];
404 SourceLocation Loc = Property->getLocation();
405
406 Rewrite.ReplaceText(Loc, 0, "// ", 3);
407
408 // FIXME: handle properties that are declared across multiple lines.
409 }
410}
411
Steve Naroff423cb562007-10-30 13:30:57 +0000412void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
413 SourceLocation LocStart = CatDecl->getLocStart();
414
415 // FIXME: handle category headers that are declared across multiple lines.
416 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
417
Steve Naroff71c0a952007-11-13 23:01:27 +0000418 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
419 CatDecl->getInstanceMethods());
420 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
421 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000422 // Lastly, comment out the @end.
423 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
424}
425
Steve Naroff752d6ef2007-10-30 16:42:30 +0000426void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000427 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000428
Steve Naroff752d6ef2007-10-30 16:42:30 +0000429 SourceLocation LocStart = PDecl->getLocStart();
430
431 // FIXME: handle protocol headers that are declared across multiple lines.
432 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
433
Steve Naroff71c0a952007-11-13 23:01:27 +0000434 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
435 PDecl->getInstanceMethods());
436 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
437 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000438 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000439 SourceLocation LocEnd = PDecl->getAtEndLoc();
440 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000441
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000442 // Must comment out @optional/@required
443 const char *startBuf = SM->getCharacterData(LocStart);
444 const char *endBuf = SM->getCharacterData(LocEnd);
445 for (const char *p = startBuf; p < endBuf; p++) {
446 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
447 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000448 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000449 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
450 CommentedOptional.c_str(), CommentedOptional.size());
451
452 }
453 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
454 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000455 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000456 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
457 CommentedRequired.c_str(), CommentedRequired.size());
458
459 }
460 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000461}
462
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000463void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
464 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000465 if (LocStart.isInvalid())
466 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000467 // FIXME: handle forward protocol that are declared across multiple lines.
468 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
469}
470
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000471void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
472 std::string &ResultStr) {
473 ResultStr += "\nstatic ";
474 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000475 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000476
477 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000478 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000479
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000480 if (OMD->isInstance())
481 NameStr += "_I_";
482 else
483 NameStr += "_C_";
484
485 NameStr += OMD->getClassInterface()->getName();
486 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000487
488 NamedDecl *MethodContext = OMD->getMethodContext();
489 if (ObjcCategoryImplDecl *CID =
490 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000491 NameStr += CID->getName();
492 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000493 }
494 // Append selector names, replacing ':' with '_'
495 const char *selName = OMD->getSelector().getName().c_str();
496 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000497 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000498 else {
499 std::string selString = OMD->getSelector().getName();
500 int len = selString.size();
501 for (int i = 0; i < len; i++)
502 if (selString[i] == ':')
503 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000504 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000505 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000506 // Remember this name for metadata emission
507 MethodInternalNames[OMD] = NameStr;
508 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000509
510 // Rewrite arguments
511 ResultStr += "(";
512
513 // invisible arguments
514 if (OMD->isInstance()) {
515 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
516 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000517 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
518 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000519 ResultStr += selfTy.getAsString();
520 }
521 else
522 ResultStr += Context->getObjcIdType().getAsString();
523
524 ResultStr += " self, ";
525 ResultStr += Context->getObjcSelType().getAsString();
526 ResultStr += " _cmd";
527
528 // Method arguments.
529 for (int i = 0; i < OMD->getNumParams(); i++) {
530 ParmVarDecl *PDecl = OMD->getParamDecl(i);
531 ResultStr += ", ";
532 ResultStr += PDecl->getType().getAsString();
533 ResultStr += " ";
534 ResultStr += PDecl->getName();
535 }
536 ResultStr += ")";
537
538}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000539void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
540 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
541 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000542
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000543 if (IMD)
544 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
545 else
546 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000547
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000548 int numMethods = IMD ? IMD->getNumInstanceMethods()
549 : CID->getNumInstanceMethods();
550
551 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000552 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000553 ObjcMethodDecl *OMD;
554 if (IMD)
555 OMD = IMD->getInstanceMethods()[i];
556 else
557 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000558 RewriteObjcMethodDecl(OMD, ResultStr);
559 SourceLocation LocStart = OMD->getLocStart();
560 SourceLocation LocEnd = OMD->getBody()->getLocStart();
561
562 const char *startBuf = SM->getCharacterData(LocStart);
563 const char *endBuf = SM->getCharacterData(LocEnd);
564 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
565 ResultStr.c_str(), ResultStr.size());
566 }
567
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000568 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
569 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000570 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000571 ObjcMethodDecl *OMD;
572 if (IMD)
573 OMD = IMD->getClassMethods()[i];
574 else
575 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000576 RewriteObjcMethodDecl(OMD, ResultStr);
577 SourceLocation LocStart = OMD->getLocStart();
578 SourceLocation LocEnd = OMD->getBody()->getLocStart();
579
580 const char *startBuf = SM->getCharacterData(LocStart);
581 const char *endBuf = SM->getCharacterData(LocEnd);
582 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
583 ResultStr.c_str(), ResultStr.size());
584 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000585 if (IMD)
586 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
587 else
588 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000589}
590
Steve Naroffbef11852007-10-26 20:53:56 +0000591void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000592 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000593 if (!ObjcForwardDecls.count(ClassDecl)) {
594 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000595 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000596 ResultStr += ClassDecl->getName();
597 ResultStr += "\n";
598 ResultStr += "#define _REWRITER_typedef_";
599 ResultStr += ClassDecl->getName();
600 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000601 ResultStr += "typedef struct ";
602 ResultStr += ClassDecl->getName();
603 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000604 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000605 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000606
607 // Mark this typedef as having been generated.
608 ObjcForwardDecls.insert(ClassDecl);
609 }
Steve Narofff908a872007-10-30 02:23:23 +0000610 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
611
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000612 RewriteProperties(ClassDecl->getNumPropertyDecl(),
613 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000614 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
615 ClassDecl->getInstanceMethods());
616 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
617 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000618
Steve Naroff2feac5e2007-10-30 03:43:13 +0000619 // Lastly, comment out the @end.
620 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000621}
622
Steve Naroff7e3411b2007-11-15 02:58:25 +0000623Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
624 ObjcIvarDecl *D = IV->getDecl();
625 if (IV->isFreeIvar()) {
626 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
627 IV->getLocation());
628 Rewrite.ReplaceStmt(IV, Replacement);
629 delete IV;
630 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000631 } else {
632 if (CurMethodDecl) {
633 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
634 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
635 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
636 IdentifierInfo *II = intT->getDecl()->getIdentifier();
637 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
638 II, 0);
639 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
640
641 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
642 // Don't forget the parens to enforce the proper binding.
643 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
644 Rewrite.ReplaceStmt(IV->getBase(), PE);
645 delete IV->getBase();
646 return PE;
647 }
648 }
649 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000650 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000651 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000652}
653
Chris Lattnerf04da132007-10-24 17:06:59 +0000654//===----------------------------------------------------------------------===//
655// Function Body / Expression rewriting
656//===----------------------------------------------------------------------===//
657
Steve Narofff3473a72007-11-09 15:20:18 +0000658Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000659 // Otherwise, just rewrite all children.
660 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
661 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000662 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000663 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000664 if (newStmt)
665 *CI = newStmt;
666 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000667
668 // Handle specific things.
669 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
670 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000671
672 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
673 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000674
675 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
676 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000677
678 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
679 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000680
Steve Naroff934f2762007-10-24 22:48:43 +0000681 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
682 // Before we rewrite it, put the original message expression in a comment.
683 SourceLocation startLoc = MessExpr->getLocStart();
684 SourceLocation endLoc = MessExpr->getLocEnd();
685
686 const char *startBuf = SM->getCharacterData(startLoc);
687 const char *endBuf = SM->getCharacterData(endLoc);
688
689 std::string messString;
690 messString += "// ";
691 messString.append(startBuf, endBuf-startBuf+1);
692 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000693
Steve Naroff934f2762007-10-24 22:48:43 +0000694 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
695 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
696 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000697 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000698 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000699 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000700
701 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
702 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000703
704 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
705 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000706#if 0
707 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
708 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
709 // Get the new text.
710 std::ostringstream Buf;
711 Replacement->printPretty(Buf);
712 const std::string &Str = Buf.str();
713
714 printf("CAST = %s\n", &Str[0]);
715 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
716 delete S;
717 return Replacement;
718 }
719#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000720 // Return this stmt unmodified.
721 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000722}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000723
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000724Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000725 // Get the start location and compute the semi location.
726 SourceLocation startLoc = S->getLocStart();
727 const char *startBuf = SM->getCharacterData(startLoc);
728
729 assert((*startBuf == '@') && "bogus @try location");
730
731 std::string buf;
732 // declare a new scope with two variables, _stack and _rethrow.
733 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
734 buf += "int buf[18/*32-bit i386*/];\n";
735 buf += "char *pointers[4];} _stack;\n";
736 buf += "id volatile _rethrow = 0;\n";
737 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000738 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000739
740 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
741
742 startLoc = S->getTryBody()->getLocEnd();
743 startBuf = SM->getCharacterData(startLoc);
744
745 assert((*startBuf == '}') && "bogus @try block");
746
747 SourceLocation lastCurlyLoc = startLoc;
748
749 startLoc = startLoc.getFileLocWithOffset(1);
750 buf = " /* @catch begin */ else {\n";
751 buf += " id _caught = objc_exception_extract(&_stack);\n";
752 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000753 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000754 buf += " _rethrow = objc_exception_extract(&_stack);\n";
755 buf += " else { /* @catch continue */";
756
Chris Lattner28d1fe82007-11-08 04:41:51 +0000757 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000758
759 bool sawIdTypedCatch = false;
760 Stmt *lastCatchBody = 0;
761 ObjcAtCatchStmt *catchList = S->getCatchStmts();
762 while (catchList) {
763 Stmt *catchStmt = catchList->getCatchParamStmt();
764
765 if (catchList == S->getCatchStmts())
766 buf = "if ("; // we are generating code for the first catch clause
767 else
768 buf = "else if (";
769 startLoc = catchList->getLocStart();
770 startBuf = SM->getCharacterData(startLoc);
771
772 assert((*startBuf == '@') && "bogus @catch location");
773
774 const char *lParenLoc = strchr(startBuf, '(');
775
776 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
777 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
778 if (t == Context->getObjcIdType()) {
779 buf += "1) { ";
780 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
781 buf.c_str(), buf.size());
782 sawIdTypedCatch = true;
783 } else if (const PointerType *pType = t->getAsPointerType()) {
784 ObjcInterfaceType *cls; // Should be a pointer to a class.
785
786 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
787 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000788 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000789 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000790 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000791 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
792 buf.c_str(), buf.size());
793 }
794 }
795 // Now rewrite the body...
796 lastCatchBody = catchList->getCatchBody();
797 SourceLocation rParenLoc = catchList->getRParenLoc();
798 SourceLocation bodyLoc = lastCatchBody->getLocStart();
799 const char *bodyBuf = SM->getCharacterData(bodyLoc);
800 const char *rParenBuf = SM->getCharacterData(rParenLoc);
801 assert((*rParenBuf == ')') && "bogus @catch paren location");
802 assert((*bodyBuf == '{') && "bogus @catch body location");
803
804 buf = " = _caught;";
805 // Here we replace ") {" with "= _caught;" (which initializes and
806 // declares the @catch parameter).
807 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
808 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000809 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000810 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000811 }
Steve Naroff75730982007-11-07 04:08:17 +0000812 catchList = catchList->getNextCatchStmt();
813 }
814 // Complete the catch list...
815 if (lastCatchBody) {
816 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
817 const char *bodyBuf = SM->getCharacterData(bodyLoc);
818 assert((*bodyBuf == '}') && "bogus @catch body location");
819 bodyLoc = bodyLoc.getFileLocWithOffset(1);
820 buf = " } } /* @catch end */\n";
821
Chris Lattner28d1fe82007-11-08 04:41:51 +0000822 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000823
824 // Set lastCurlyLoc
825 lastCurlyLoc = lastCatchBody->getLocEnd();
826 }
827 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
828 startLoc = finalStmt->getLocStart();
829 startBuf = SM->getCharacterData(startLoc);
830 assert((*startBuf == '@') && "bogus @finally start");
831
832 buf = "/* @finally */";
833 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
834
835 Stmt *body = finalStmt->getFinallyBody();
836 SourceLocation startLoc = body->getLocStart();
837 SourceLocation endLoc = body->getLocEnd();
838 const char *startBuf = SM->getCharacterData(startLoc);
839 const char *endBuf = SM->getCharacterData(endLoc);
840 assert((*startBuf == '{') && "bogus @finally body location");
841 assert((*endBuf == '}') && "bogus @finally body location");
842
843 startLoc = startLoc.getFileLocWithOffset(1);
844 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000845 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000846 endLoc = endLoc.getFileLocWithOffset(-1);
847 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000848 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000849
850 // Set lastCurlyLoc
851 lastCurlyLoc = body->getLocEnd();
852 }
853 // Now emit the final closing curly brace...
854 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
855 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000856 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000857 return 0;
858}
859
860Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
861 return 0;
862}
863
864Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
865 return 0;
866}
867
Steve Naroff2bd03922007-11-07 15:32:26 +0000868// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
869// the throw expression is typically a message expression that's already
870// been rewritten! (which implies the SourceLocation's are invalid).
871Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
872 // Get the start location and compute the semi location.
873 SourceLocation startLoc = S->getLocStart();
874 const char *startBuf = SM->getCharacterData(startLoc);
875
876 assert((*startBuf == '@') && "bogus @throw location");
877
878 std::string buf;
879 /* void objc_exception_throw(id) __attribute__((noreturn)); */
880 buf = "objc_exception_throw(";
881 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
882 const char *semiBuf = strchr(startBuf, ';');
883 assert((*semiBuf == ';') && "@throw: can't find ';'");
884 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
885 buf = ");";
886 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
887 return 0;
888}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000889
Chris Lattnere64b7772007-10-24 16:57:36 +0000890Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000891 // Create a new string expression.
892 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000893 std::string StrEncoding;
894 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
895 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
896 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000897 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000898 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
899 // replacement failed.
Chris Lattner182745a2007-12-02 01:09:57 +0000900 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
901 "rewriter could not replace sub-expression due to macros");
902 SourceRange Range = Exp->getSourceRange();
903 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
904 delete Replacement;
Chris Lattnere365c502007-11-30 22:25:36 +0000905 return Exp;
906 }
907
Chris Lattner07506182007-11-30 22:53:43 +0000908 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000909 delete Exp;
910 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000911}
912
Steve Naroffb42f8412007-11-05 14:50:49 +0000913Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
914 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
915 // Create a call to sel_registerName("selName").
916 llvm::SmallVector<Expr*, 8> SelExprs;
917 QualType argType = Context->getPointerType(Context->CharTy);
918 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
919 Exp->getSelector().getName().size(),
920 false, argType, SourceLocation(),
921 SourceLocation()));
922 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
923 &SelExprs[0], SelExprs.size());
924 Rewrite.ReplaceStmt(Exp, SelExp);
925 delete Exp;
926 return SelExp;
927}
928
Steve Naroff934f2762007-10-24 22:48:43 +0000929CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
930 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000931 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000932 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000933
934 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000935 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000936
937 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000938 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000939 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
940
941 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000942
Steve Naroff934f2762007-10-24 22:48:43 +0000943 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
944}
945
Steve Naroffd5255f52007-11-01 13:24:47 +0000946static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
947 const char *&startRef, const char *&endRef) {
948 while (startBuf < endBuf) {
949 if (*startBuf == '<')
950 startRef = startBuf; // mark the start.
951 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000952 if (startRef && *startRef == '<') {
953 endRef = startBuf; // mark the end.
954 return true;
955 }
956 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000957 }
958 startBuf++;
959 }
960 return false;
961}
962
963bool RewriteTest::needToScanForQualifiers(QualType T) {
964 // FIXME: we don't currently represent "id <Protocol>" in the type system.
965 if (T == Context->getObjcIdType())
966 return true;
967
968 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000969 Type *pointeeType = pType->getPointeeType().getTypePtr();
970 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
971 return true; // we have "Class <Protocol> *".
972 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000973 return false;
974}
975
976void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
977 const FunctionTypeProto *proto, FunctionDecl *FD) {
978
979 if (needToScanForQualifiers(proto->getResultType())) {
980 // Since types are unique, we need to scan the buffer.
981 SourceLocation Loc = FD->getLocation();
982
983 const char *endBuf = SM->getCharacterData(Loc);
984 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +0000985 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +0000986 startBuf--; // scan backward (from the decl location) for return type.
987 const char *startRef = 0, *endRef = 0;
988 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
989 // Get the locations of the startRef, endRef.
990 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
991 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
992 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000993 Rewrite.InsertText(LessLoc, "/*", 2);
994 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000995 }
996 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000997 // Now check arguments.
998 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
999 if (needToScanForQualifiers(proto->getArgType(i))) {
1000 // Since types are unique, we need to scan the buffer.
1001 SourceLocation Loc = FD->getLocation();
1002
1003 const char *startBuf = SM->getCharacterData(Loc);
1004 const char *endBuf = startBuf;
1005 while (*endBuf != ';')
1006 endBuf++; // scan forward (from the decl location) for argument types.
1007 const char *startRef = 0, *endRef = 0;
1008 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1009 // Get the locations of the startRef, endRef.
1010 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1011 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1012 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001013 Rewrite.InsertText(LessLoc, "/*", 2);
1014 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001015 }
1016 }
1017 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001018}
1019
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001020// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1021void RewriteTest::SynthSelGetUidFunctionDecl() {
1022 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1023 llvm::SmallVector<QualType, 16> ArgTys;
1024 ArgTys.push_back(Context->getPointerType(
1025 Context->CharTy.getQualifiedType(QualType::Const)));
1026 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1027 &ArgTys[0], ArgTys.size(),
1028 false /*isVariadic*/);
1029 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1030 SelGetUidIdent, getFuncType,
1031 FunctionDecl::Extern, false, 0);
1032}
1033
Steve Naroff09b266e2007-10-30 23:14:51 +00001034void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1035 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001036 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001037 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001038 return;
1039 }
1040 // Check for ObjC 'id' and class types that have been adorned with protocol
1041 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1042 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1043 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +00001044 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
1045 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001046}
1047
1048// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1049void RewriteTest::SynthMsgSendFunctionDecl() {
1050 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1051 llvm::SmallVector<QualType, 16> ArgTys;
1052 QualType argT = Context->getObjcIdType();
1053 assert(!argT.isNull() && "Can't find 'id' type");
1054 ArgTys.push_back(argT);
1055 argT = Context->getObjcSelType();
1056 assert(!argT.isNull() && "Can't find 'SEL' type");
1057 ArgTys.push_back(argT);
1058 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1059 &ArgTys[0], ArgTys.size(),
1060 true /*isVariadic*/);
1061 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1062 msgSendIdent, msgSendType,
1063 FunctionDecl::Extern, false, 0);
1064}
1065
Steve Naroff874e2322007-11-15 10:28:18 +00001066// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1067void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1068 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1069 llvm::SmallVector<QualType, 16> ArgTys;
1070 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1071 &Context->Idents.get("objc_super"), 0);
1072 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1073 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1074 ArgTys.push_back(argT);
1075 argT = Context->getObjcSelType();
1076 assert(!argT.isNull() && "Can't find 'SEL' type");
1077 ArgTys.push_back(argT);
1078 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1079 &ArgTys[0], ArgTys.size(),
1080 true /*isVariadic*/);
1081 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1082 msgSendIdent, msgSendType,
1083 FunctionDecl::Extern, false, 0);
1084}
1085
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001086// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1087void RewriteTest::SynthMsgSendStretFunctionDecl() {
1088 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1089 llvm::SmallVector<QualType, 16> ArgTys;
1090 QualType argT = Context->getObjcIdType();
1091 assert(!argT.isNull() && "Can't find 'id' type");
1092 ArgTys.push_back(argT);
1093 argT = Context->getObjcSelType();
1094 assert(!argT.isNull() && "Can't find 'SEL' type");
1095 ArgTys.push_back(argT);
1096 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1097 &ArgTys[0], ArgTys.size(),
1098 true /*isVariadic*/);
1099 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1100 msgSendIdent, msgSendType,
1101 FunctionDecl::Extern, false, 0);
1102}
1103
1104// SynthMsgSendSuperStretFunctionDecl -
1105// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1106void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1107 IdentifierInfo *msgSendIdent =
1108 &Context->Idents.get("objc_msgSendSuper_stret");
1109 llvm::SmallVector<QualType, 16> ArgTys;
1110 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1111 &Context->Idents.get("objc_super"), 0);
1112 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1113 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1114 ArgTys.push_back(argT);
1115 argT = Context->getObjcSelType();
1116 assert(!argT.isNull() && "Can't find 'SEL' type");
1117 ArgTys.push_back(argT);
1118 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1119 &ArgTys[0], ArgTys.size(),
1120 true /*isVariadic*/);
1121 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1122 msgSendIdent, msgSendType,
1123 FunctionDecl::Extern, false, 0);
1124}
1125
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001126// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1127void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1128 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1129 llvm::SmallVector<QualType, 16> ArgTys;
1130 QualType argT = Context->getObjcIdType();
1131 assert(!argT.isNull() && "Can't find 'id' type");
1132 ArgTys.push_back(argT);
1133 argT = Context->getObjcSelType();
1134 assert(!argT.isNull() && "Can't find 'SEL' type");
1135 ArgTys.push_back(argT);
1136 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1137 &ArgTys[0], ArgTys.size(),
1138 true /*isVariadic*/);
1139 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1140 msgSendIdent, msgSendType,
1141 FunctionDecl::Extern, false, 0);
1142}
1143
Steve Naroff09b266e2007-10-30 23:14:51 +00001144// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1145void RewriteTest::SynthGetClassFunctionDecl() {
1146 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1147 llvm::SmallVector<QualType, 16> ArgTys;
1148 ArgTys.push_back(Context->getPointerType(
1149 Context->CharTy.getQualifiedType(QualType::Const)));
1150 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1151 &ArgTys[0], ArgTys.size(),
1152 false /*isVariadic*/);
1153 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1154 getClassIdent, getClassType,
1155 FunctionDecl::Extern, false, 0);
1156}
1157
Steve Naroff96984642007-11-08 14:30:50 +00001158// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1159void RewriteTest::SynthCFStringFunctionDecl() {
1160 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1161 llvm::SmallVector<QualType, 16> ArgTys;
1162 ArgTys.push_back(Context->getPointerType(
1163 Context->CharTy.getQualifiedType(QualType::Const)));
1164 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1165 &ArgTys[0], ArgTys.size(),
1166 false /*isVariadic*/);
1167 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1168 getClassIdent, getClassType,
1169 FunctionDecl::Extern, false, 0);
1170}
1171
Steve Naroffbeaf2992007-11-03 11:27:19 +00001172Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001173#if 1
1174 // This rewrite is specific to GCC, which has builtin support for CFString.
1175 if (!CFStringFunctionDecl)
1176 SynthCFStringFunctionDecl();
1177 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1178 llvm::SmallVector<Expr*, 8> StrExpr;
1179 StrExpr.push_back(Exp->getString());
1180 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1181 &StrExpr[0], StrExpr.size());
1182 // cast to NSConstantString *
1183 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1184 Rewrite.ReplaceStmt(Exp, cast);
1185 delete Exp;
1186 return cast;
1187#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001188 assert(ConstantStringClassReference && "Can't find constant string reference");
1189 llvm::SmallVector<Expr*, 4> InitExprs;
1190
1191 // Synthesize "(Class)&_NSConstantStringClassReference"
1192 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1193 ConstantStringClassReference->getType(),
1194 SourceLocation());
1195 QualType expType = Context->getPointerType(ClsRef->getType());
1196 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1197 expType, SourceLocation());
1198 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1199 SourceLocation());
1200 InitExprs.push_back(cast); // set the 'isa'.
1201 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1202 unsigned IntSize = static_cast<unsigned>(
1203 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1204 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1205 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1206 Exp->getLocStart());
1207 InitExprs.push_back(len); // set "int numBytes".
1208
1209 // struct NSConstantString
1210 QualType CFConstantStrType = Context->getCFConstantStringType();
1211 // (struct NSConstantString) { <exprs from above> }
1212 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1213 &InitExprs[0], InitExprs.size(),
1214 SourceLocation());
1215 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1216 // struct NSConstantString *
1217 expType = Context->getPointerType(StrRep->getType());
1218 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1219 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001220 // cast to NSConstantString *
1221 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001222 Rewrite.ReplaceStmt(Exp, cast);
1223 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001224 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001225#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001226}
1227
Steve Naroff874e2322007-11-15 10:28:18 +00001228ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1229 if (CurMethodDecl) { // check if we are sending a message to 'super'
1230 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1231 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1232 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1233 if (!strcmp(PVD->getName(), "self")) {
1234 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1235 if (ObjcInterfaceType *IT =
1236 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1237 if (IT->getDecl() ==
1238 CurMethodDecl->getClassInterface()->getSuperClass())
1239 return IT->getDecl();
1240 }
1241 }
1242 }
1243 }
1244 }
1245 }
1246 }
1247 return 0;
1248}
1249
1250// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1251QualType RewriteTest::getSuperStructType() {
1252 if (!SuperStructDecl) {
1253 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1254 &Context->Idents.get("objc_super"), 0);
1255 QualType FieldTypes[2];
1256
1257 // struct objc_object *receiver;
1258 FieldTypes[0] = Context->getObjcIdType();
1259 // struct objc_class *super;
1260 FieldTypes[1] = Context->getObjcClassType();
1261 // Create fields
1262 FieldDecl *FieldDecls[2];
1263
1264 for (unsigned i = 0; i < 2; ++i)
1265 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1266
1267 SuperStructDecl->defineBody(FieldDecls, 4);
1268 }
1269 return Context->getTagDeclType(SuperStructDecl);
1270}
1271
Steve Naroff934f2762007-10-24 22:48:43 +00001272Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001273 if (!SelGetUidFunctionDecl)
1274 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001275 if (!MsgSendFunctionDecl)
1276 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001277 if (!MsgSendSuperFunctionDecl)
1278 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001279 if (!MsgSendStretFunctionDecl)
1280 SynthMsgSendStretFunctionDecl();
1281 if (!MsgSendSuperStretFunctionDecl)
1282 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001283 if (!MsgSendFpretFunctionDecl)
1284 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001285 if (!GetClassFunctionDecl)
1286 SynthGetClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001287
Steve Naroff874e2322007-11-15 10:28:18 +00001288 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001289 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1290 // May need to use objc_msgSend_stret() as well.
1291 FunctionDecl *MsgSendStretFlavor = 0;
1292 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1293 QualType resultType = mDecl->getResultType();
1294 if (resultType.getCanonicalType()->isStructureType()
1295 || resultType.getCanonicalType()->isUnionType())
1296 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001297 else if (resultType.getCanonicalType()->isRealFloatingType())
1298 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001299 }
Steve Naroff874e2322007-11-15 10:28:18 +00001300
Steve Naroff934f2762007-10-24 22:48:43 +00001301 // Synthesize a call to objc_msgSend().
1302 llvm::SmallVector<Expr*, 8> MsgExprs;
1303 IdentifierInfo *clsName = Exp->getClassName();
1304
1305 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1306 if (clsName) { // class message.
1307 llvm::SmallVector<Expr*, 8> ClsExprs;
1308 QualType argType = Context->getPointerType(Context->CharTy);
1309 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1310 clsName->getLength(),
1311 false, argType, SourceLocation(),
1312 SourceLocation()));
1313 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1314 &ClsExprs[0], ClsExprs.size());
1315 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001316 } else { // instance message.
1317 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001318
1319 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1320 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001321 if (MsgSendStretFlavor)
1322 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001323 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1324
1325 llvm::SmallVector<Expr*, 4> InitExprs;
1326
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001327 InitExprs.push_back(
1328 new CastExpr(Context->getObjcIdType(),
1329 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001330
1331 llvm::SmallVector<Expr*, 8> ClsExprs;
1332 QualType argType = Context->getPointerType(Context->CharTy);
1333 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1334 ID->getIdentifier()->getLength(),
1335 false, argType, SourceLocation(),
1336 SourceLocation()));
1337 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001338 &ClsExprs[0],
1339 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001340 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001341 InitExprs.push_back(
Fariborz Jahanian71274312007-12-05 17:29:46 +00001342 new CastExpr(Context->getObjcIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001343 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001344 // struct objc_super
1345 QualType superType = getSuperStructType();
1346 // (struct objc_super) { <exprs from above> }
1347 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1348 &InitExprs[0], InitExprs.size(),
1349 SourceLocation());
1350 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1351 // struct objc_super *
1352 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1353 Context->getPointerType(SuperRep->getType()),
1354 SourceLocation());
1355 MsgExprs.push_back(Unop);
1356 } else {
1357 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1358 MsgExprs.push_back(recExpr);
1359 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001360 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001361 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001362 llvm::SmallVector<Expr*, 8> SelExprs;
1363 QualType argType = Context->getPointerType(Context->CharTy);
1364 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1365 Exp->getSelector().getName().size(),
1366 false, argType, SourceLocation(),
1367 SourceLocation()));
1368 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1369 &SelExprs[0], SelExprs.size());
1370 MsgExprs.push_back(SelExp);
1371
1372 // Now push any user supplied arguments.
1373 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001374 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001375 // Make all implicit casts explicit...ICE comes in handy:-)
1376 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1377 // Reuse the ICE type, it is exactly what the doctor ordered.
1378 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1379 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001380 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001381 // We've transferred the ownership to MsgExprs. Null out the argument in
1382 // the original expression, since we will delete it below.
1383 Exp->setArg(i, 0);
1384 }
Steve Naroffab972d32007-11-04 22:37:50 +00001385 // Generate the funky cast.
1386 CastExpr *cast;
1387 llvm::SmallVector<QualType, 8> ArgTypes;
1388 QualType returnType;
1389
1390 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001391 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1392 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1393 else
1394 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001395 ArgTypes.push_back(Context->getObjcSelType());
1396 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1397 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001398 for (int i = 0; i < mDecl->getNumParams(); i++) {
1399 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001400 ArgTypes.push_back(t);
1401 }
Steve Naroffab972d32007-11-04 22:37:50 +00001402 returnType = mDecl->getResultType();
1403 } else {
1404 returnType = Context->getObjcIdType();
1405 }
1406 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001407 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001408
1409 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001410 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1411 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001412
1413 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1414 // If we don't do this cast, we get the following bizarre warning/note:
1415 // xx.m:13: warning: function called through a non-compatible type
1416 // xx.m:13: note: if this code is reached, the program will abort
1417 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1418 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001419
Steve Naroffab972d32007-11-04 22:37:50 +00001420 // Now do the "normal" pointer to function cast.
1421 QualType castType = Context->getFunctionType(returnType,
1422 &ArgTypes[0], ArgTypes.size(),
Steve Naroff335eafa2007-11-15 12:35:21 +00001423 Exp->getMethodDecl()->isVariadic());
Steve Naroffab972d32007-11-04 22:37:50 +00001424 castType = Context->getPointerType(castType);
1425 cast = new CastExpr(castType, cast, SourceLocation());
1426
1427 // Don't forget the parens to enforce the proper binding.
1428 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1429
1430 const FunctionType *FT = msgSendType->getAsFunctionType();
1431 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1432 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001433 if (MsgSendStretFlavor) {
1434 // We have the method which returns a struct/union. Must also generate
1435 // call to objc_msgSend_stret and hang both varieties on a conditional
1436 // expression which dictate which one to envoke depending on size of
1437 // method's return type.
1438
1439 // Create a reference to the objc_msgSend_stret() declaration.
1440 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1441 SourceLocation());
1442 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1443 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1444 SourceLocation());
1445 // Now do the "normal" pointer to function cast.
1446 castType = Context->getFunctionType(returnType,
1447 &ArgTypes[0], ArgTypes.size(),
1448 Exp->getMethodDecl()->isVariadic());
1449 castType = Context->getPointerType(castType);
1450 cast = new CastExpr(castType, cast, SourceLocation());
1451
1452 // Don't forget the parens to enforce the proper binding.
1453 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1454
1455 FT = msgSendType->getAsFunctionType();
1456 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1457 FT->getResultType(), SourceLocation());
1458
1459 // Build sizeof(returnType)
1460 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1461 returnType, Context->getSizeType(),
1462 SourceLocation(), SourceLocation());
1463 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1464 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1465 // For X86 it is more complicated and some kind of target specific routine
1466 // is needed to decide what to do.
1467 unsigned IntSize = static_cast<unsigned>(
1468 Context->getTypeSize(Context->IntTy, SourceLocation()));
1469
1470 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1471 Context->IntTy,
1472 SourceLocation());
1473 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1474 BinaryOperator::LE,
1475 Context->IntTy,
1476 SourceLocation());
1477 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1478 ConditionalOperator *CondExpr =
1479 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1480 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1481 // Now do the actual rewrite.
1482 Rewrite.ReplaceStmt(Exp, PE);
1483 delete Exp;
1484 return PE;
1485 }
Steve Naroff934f2762007-10-24 22:48:43 +00001486 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001487 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001488
Chris Lattnere64b7772007-10-24 16:57:36 +00001489 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001490 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001491}
1492
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001493/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1494/// an objective-c class with ivars.
1495void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1496 std::string &Result) {
1497 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1498 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001499 // Do not synthesize more than once.
1500 if (ObjcSynthesizedStructs.count(CDecl))
1501 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001502 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001503 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001504 SourceLocation LocStart = CDecl->getLocStart();
1505 SourceLocation LocEnd = CDecl->getLocEnd();
1506
1507 const char *startBuf = SM->getCharacterData(LocStart);
1508 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001509 // If no ivars and no root or if its root, directly or indirectly,
1510 // have no ivars (thus not synthesized) then no need to synthesize this class.
1511 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001512 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1513 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1514 Result.c_str(), Result.size());
1515 return;
1516 }
1517
1518 // FIXME: This has potential of causing problem. If
1519 // SynthesizeObjcInternalStruct is ever called recursively.
1520 Result += "\nstruct ";
1521 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001522
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001523 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001524 const char *cursor = strchr(startBuf, '{');
1525 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001526 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001527
1528 // rewrite the original header *without* disturbing the '{'
1529 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1530 Result.c_str(), Result.size());
1531 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1532 Result = "\n struct ";
1533 Result += RCDecl->getName();
1534 Result += " _";
1535 Result += RCDecl->getName();
1536 Result += ";\n";
1537
1538 // insert the super class structure definition.
1539 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1540 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1541 }
1542 cursor++; // past '{'
1543
1544 // Now comment out any visibility specifiers.
1545 while (cursor < endBuf) {
1546 if (*cursor == '@') {
1547 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001548 // Skip whitespace.
1549 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1550 /*scan*/;
1551
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001552 // FIXME: presence of @public, etc. inside comment results in
1553 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001554 if (!strncmp(cursor, "public", strlen("public")) ||
1555 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001556 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001557 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001558 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001559 // FIXME: If there are cases where '<' is used in ivar declaration part
1560 // of user code, then scan the ivar list and use needToScanForQualifiers
1561 // for type checking.
1562 else if (*cursor == '<') {
1563 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1564 Rewrite.InsertText(atLoc, "/* ", 3);
1565 cursor = strchr(cursor, '>');
1566 cursor++;
1567 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1568 Rewrite.InsertText(atLoc, " */", 3);
1569 }
Steve Narofffea763e82007-11-14 19:25:57 +00001570 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001571 }
Steve Narofffea763e82007-11-14 19:25:57 +00001572 // Don't forget to add a ';'!!
1573 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1574 } else { // we don't have any instance variables - insert super struct.
1575 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1576 Result += " {\n struct ";
1577 Result += RCDecl->getName();
1578 Result += " _";
1579 Result += RCDecl->getName();
1580 Result += ";\n};\n";
1581 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1582 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001583 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001584 // Mark this struct as having been generated.
1585 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001586 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001587}
1588
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001589// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1590/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001591void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001592 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001593 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001594 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001595 const char *ClassName,
1596 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001597 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001598 if (NumMethods > 0 && !objc_impl_method) {
1599 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001600 SEL _cmd;
1601 char *method_types;
1602 void *_imp;
1603 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001604 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001605 Result += "\nstruct _objc_method {\n";
1606 Result += "\tSEL _cmd;\n";
1607 Result += "\tchar *method_types;\n";
1608 Result += "\tvoid *_imp;\n";
1609 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001610
1611 /* struct _objc_method_list {
1612 struct _objc_method_list *next_method;
1613 int method_count;
1614 struct _objc_method method_list[];
1615 }
1616 */
1617 Result += "\nstruct _objc_method_list {\n";
1618 Result += "\tstruct _objc_method_list *next_method;\n";
1619 Result += "\tint method_count;\n";
1620 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001621 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001622 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001623 // Build _objc_method_list for class's methods if needed
1624 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001625 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001626 Result += prefix;
1627 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1628 Result += "_METHODS_";
1629 Result += ClassName;
1630 Result += " __attribute__ ((section (\"__OBJC, __";
1631 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001632 Result += "_meth\")))= ";
1633 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1634
1635 Result += "\t,{{(SEL)\"";
1636 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001637 std::string MethodTypeString;
1638 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1639 Result += "\", \"";
1640 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001641 Result += "\", ";
1642 Result += MethodInternalNames[Methods[0]];
1643 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001644 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001645 Result += "\t ,{(SEL)\"";
1646 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001647 std::string MethodTypeString;
1648 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1649 Result += "\", \"";
1650 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001651 Result += "\", ";
1652 Result += MethodInternalNames[Methods[i]];
1653 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001654 }
1655 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001656 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001657}
1658
1659/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1660void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1661 int NumProtocols,
1662 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001663 const char *ClassName,
1664 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001665 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001666 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001667 for (int i = 0; i < NumProtocols; i++) {
1668 ObjcProtocolDecl *PDecl = Protocols[i];
1669 // Output struct protocol_methods holder of method selector and type.
1670 if (!objc_protocol_methods &&
1671 (PDecl->getNumInstanceMethods() > 0
1672 || PDecl->getNumClassMethods() > 0)) {
1673 /* struct protocol_methods {
1674 SEL _cmd;
1675 char *method_types;
1676 }
1677 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001678 Result += "\nstruct protocol_methods {\n";
1679 Result += "\tSEL _cmd;\n";
1680 Result += "\tchar *method_types;\n";
1681 Result += "};\n";
1682
1683 /* struct _objc_protocol_method_list {
1684 int protocol_method_count;
1685 struct protocol_methods protocols[];
1686 }
1687 */
1688 Result += "\nstruct _objc_protocol_method_list {\n";
1689 Result += "\tint protocol_method_count;\n";
1690 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001691 objc_protocol_methods = true;
1692 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001693
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001694 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001695 int NumMethods = PDecl->getNumInstanceMethods();
1696 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001697 Result += "\nstatic struct _objc_protocol_method_list "
1698 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1699 Result += PDecl->getName();
1700 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1701 "{\n\t" + utostr(NumMethods) + "\n";
1702
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001703 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001704 Result += "\t,{{(SEL)\"";
1705 Result += Methods[0]->getSelector().getName().c_str();
1706 Result += "\", \"\"}\n";
1707
1708 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001709 Result += "\t ,{(SEL)\"";
1710 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001711 std::string MethodTypeString;
1712 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1713 Result += "\", \"";
1714 Result += MethodTypeString;
1715 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001716 }
1717 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001718 }
1719
1720 // Output class methods declared in this protocol.
1721 NumMethods = PDecl->getNumClassMethods();
1722 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001723 Result += "\nstatic struct _objc_protocol_method_list "
1724 "_OBJC_PROTOCOL_CLASS_METHODS_";
1725 Result += PDecl->getName();
1726 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1727 "{\n\t";
1728 Result += utostr(NumMethods);
1729 Result += "\n";
1730
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001731 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001732 Result += "\t,{{(SEL)\"";
1733 Result += Methods[0]->getSelector().getName().c_str();
1734 Result += "\", \"\"}\n";
1735
1736 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001737 Result += "\t ,{(SEL)\"";
1738 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001739 std::string MethodTypeString;
1740 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1741 Result += "\", \"";
1742 Result += MethodTypeString;
1743 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001744 }
1745 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001746 }
1747 // Output:
1748 /* struct _objc_protocol {
1749 // Objective-C 1.0 extensions
1750 struct _objc_protocol_extension *isa;
1751 char *protocol_name;
1752 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001753 struct _objc_protocol_method_list *instance_methods;
1754 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001755 };
1756 */
1757 static bool objc_protocol = false;
1758 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001759 Result += "\nstruct _objc_protocol {\n";
1760 Result += "\tstruct _objc_protocol_extension *isa;\n";
1761 Result += "\tchar *protocol_name;\n";
1762 Result += "\tstruct _objc_protocol **protocol_list;\n";
1763 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1764 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1765 Result += "};\n";
1766
1767 /* struct _objc_protocol_list {
1768 struct _objc_protocol_list *next;
1769 int protocol_count;
1770 struct _objc_protocol *class_protocols[];
1771 }
1772 */
1773 Result += "\nstruct _objc_protocol_list {\n";
1774 Result += "\tstruct _objc_protocol_list *next;\n";
1775 Result += "\tint protocol_count;\n";
1776 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1777 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001778 objc_protocol = true;
1779 }
1780
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001781 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1782 Result += PDecl->getName();
1783 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1784 "{\n\t0, \"";
1785 Result += PDecl->getName();
1786 Result += "\", 0, ";
1787 if (PDecl->getInstanceMethods() > 0) {
1788 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1789 Result += PDecl->getName();
1790 Result += ", ";
1791 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001792 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001793 Result += "0, ";
1794 if (PDecl->getClassMethods() > 0) {
1795 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1796 Result += PDecl->getName();
1797 Result += "\n";
1798 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001799 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001800 Result += "0\n";
1801 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001802 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001803 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001804 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1805 Result += prefix;
1806 Result += "_PROTOCOLS_";
1807 Result += ClassName;
1808 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1809 "{\n\t0, ";
1810 Result += utostr(NumProtocols);
1811 Result += "\n";
1812
1813 Result += "\t,{&_OBJC_PROTOCOL_";
1814 Result += Protocols[0]->getName();
1815 Result += " \n";
1816
1817 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001818 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001819 Result += "\t ,&_OBJC_PROTOCOL_";
1820 Result += PDecl->getName();
1821 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001822 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001823 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001824 }
1825}
1826
1827/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1828/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001829void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1830 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001831 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1832 // Find category declaration for this implementation.
1833 ObjcCategoryDecl *CDecl;
1834 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1835 CDecl = CDecl->getNextClassCategory())
1836 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1837 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001838
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001839 char *FullCategoryName = (char*)alloca(
1840 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1841 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1842
1843 // Build _objc_method_list for class's instance methods if needed
1844 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1845 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001846 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001847 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001848
1849 // Build _objc_method_list for class's class methods if needed
1850 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1851 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001852 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001853 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001854
1855 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001856 // Null CDecl is case of a category implementation with no category interface
1857 if (CDecl)
1858 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1859 CDecl->getNumReferencedProtocols(),
1860 "CATEGORY",
1861 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001862
1863 /* struct _objc_category {
1864 char *category_name;
1865 char *class_name;
1866 struct _objc_method_list *instance_methods;
1867 struct _objc_method_list *class_methods;
1868 struct _objc_protocol_list *protocols;
1869 // Objective-C 1.0 extensions
1870 uint32_t size; // sizeof (struct _objc_category)
1871 struct _objc_property_list *instance_properties; // category's own
1872 // @property decl.
1873 };
1874 */
1875
1876 static bool objc_category = false;
1877 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001878 Result += "\nstruct _objc_category {\n";
1879 Result += "\tchar *category_name;\n";
1880 Result += "\tchar *class_name;\n";
1881 Result += "\tstruct _objc_method_list *instance_methods;\n";
1882 Result += "\tstruct _objc_method_list *class_methods;\n";
1883 Result += "\tstruct _objc_protocol_list *protocols;\n";
1884 Result += "\tunsigned int size;\n";
1885 Result += "\tstruct _objc_property_list *instance_properties;\n";
1886 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001887 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001888 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001889 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1890 Result += FullCategoryName;
1891 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1892 Result += IDecl->getName();
1893 Result += "\"\n\t, \"";
1894 Result += ClassDecl->getName();
1895 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001896
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001897 if (IDecl->getNumInstanceMethods() > 0) {
1898 Result += "\t, (struct _objc_method_list *)"
1899 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1900 Result += FullCategoryName;
1901 Result += "\n";
1902 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001903 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001904 Result += "\t, 0\n";
1905 if (IDecl->getNumClassMethods() > 0) {
1906 Result += "\t, (struct _objc_method_list *)"
1907 "&_OBJC_CATEGORY_CLASS_METHODS_";
1908 Result += FullCategoryName;
1909 Result += "\n";
1910 }
1911 else
1912 Result += "\t, 0\n";
1913
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001914 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001915 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1916 Result += FullCategoryName;
1917 Result += "\n";
1918 }
1919 else
1920 Result += "\t, 0\n";
1921 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001922}
1923
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001924/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1925/// ivar offset.
1926void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1927 ObjcIvarDecl *ivar,
1928 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001929 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001930 Result += IDecl->getName();
1931 Result += ", ";
1932 Result += ivar->getName();
1933 Result += ")";
1934}
1935
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001936//===----------------------------------------------------------------------===//
1937// Meta Data Emission
1938//===----------------------------------------------------------------------===//
1939
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001940void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1941 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001942 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1943
1944 // Build _objc_ivar_list metadata for classes ivars if needed
1945 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1946 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001947 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00001948 // Explictly declared @interface's are already synthesized.
1949 if (CDecl->ImplicitInterfaceDecl()) {
1950 // FIXME: Implementation of a class with no @interface (legacy) doese not
1951 // produce correct synthesis as yet.
1952 SynthesizeObjcInternalStruct(CDecl, Result);
1953 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001954
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001955 if (NumIvars > 0) {
1956 static bool objc_ivar = false;
1957 if (!objc_ivar) {
1958 /* struct _objc_ivar {
1959 char *ivar_name;
1960 char *ivar_type;
1961 int ivar_offset;
1962 };
1963 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001964 Result += "\nstruct _objc_ivar {\n";
1965 Result += "\tchar *ivar_name;\n";
1966 Result += "\tchar *ivar_type;\n";
1967 Result += "\tint ivar_offset;\n";
1968 Result += "};\n";
1969
1970 /* struct _objc_ivar_list {
1971 int ivar_count;
1972 struct _objc_ivar ivar_list[];
1973 };
1974 */
1975 Result += "\nstruct _objc_ivar_list {\n";
1976 Result += "\tint ivar_count;\n";
1977 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001978 objc_ivar = true;
1979 }
1980
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001981 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1982 Result += IDecl->getName();
1983 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1984 "{\n\t";
1985 Result += utostr(NumIvars);
1986 Result += "\n";
1987
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001988 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1989 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001990 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001991 Result += "\t,{{\"";
1992 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001993 Result += "\", \"";
1994 std::string StrEncoding;
1995 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1996 Result += StrEncoding;
1997 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001998 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1999 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002000 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002001 Result += "\t ,{\"";
2002 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002003 Result += "\", \"";
2004 std::string StrEncoding;
2005 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
2006 Result += StrEncoding;
2007 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002008 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
2009 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002010 }
2011
2012 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002013 }
2014
2015 // Build _objc_method_list for class's instance methods if needed
2016 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2017 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002018 true,
2019 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002020
2021 // Build _objc_method_list for class's class methods if needed
2022 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002023 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002024 false,
2025 "", IDecl->getName(), Result);
2026
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002027 // Protocols referenced in class declaration?
2028 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2029 CDecl->getNumIntfRefProtocols(),
2030 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002031 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002032
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002033
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002034 // Declaration of class/meta-class metadata
2035 /* struct _objc_class {
2036 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002037 const char *super_class_name;
2038 char *name;
2039 long version;
2040 long info;
2041 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002042 struct _objc_ivar_list *ivars;
2043 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002044 struct objc_cache *cache;
2045 struct objc_protocol_list *protocols;
2046 const char *ivar_layout;
2047 struct _objc_class_ext *ext;
2048 };
2049 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002050 static bool objc_class = false;
2051 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002052 Result += "\nstruct _objc_class {\n";
2053 Result += "\tstruct _objc_class *isa;\n";
2054 Result += "\tconst char *super_class_name;\n";
2055 Result += "\tchar *name;\n";
2056 Result += "\tlong version;\n";
2057 Result += "\tlong info;\n";
2058 Result += "\tlong instance_size;\n";
2059 Result += "\tstruct _objc_ivar_list *ivars;\n";
2060 Result += "\tstruct _objc_method_list *methods;\n";
2061 Result += "\tstruct objc_cache *cache;\n";
2062 Result += "\tstruct _objc_protocol_list *protocols;\n";
2063 Result += "\tconst char *ivar_layout;\n";
2064 Result += "\tstruct _objc_class_ext *ext;\n";
2065 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002066 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002067 }
2068
2069 // Meta-class metadata generation.
2070 ObjcInterfaceDecl *RootClass = 0;
2071 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2072 while (SuperClass) {
2073 RootClass = SuperClass;
2074 SuperClass = SuperClass->getSuperClass();
2075 }
2076 SuperClass = CDecl->getSuperClass();
2077
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002078 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2079 Result += CDecl->getName();
2080 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2081 "{\n\t(struct _objc_class *)\"";
2082 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2083 Result += "\"";
2084
2085 if (SuperClass) {
2086 Result += ", \"";
2087 Result += SuperClass->getName();
2088 Result += "\", \"";
2089 Result += CDecl->getName();
2090 Result += "\"";
2091 }
2092 else {
2093 Result += ", 0, \"";
2094 Result += CDecl->getName();
2095 Result += "\"";
2096 }
Fariborz Jahanian04b38242007-12-04 19:31:56 +00002097 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002098 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002099 Result += ", 0,2, sizeof(struct _objc_class), 0";
2100 if (CDecl->getNumClassMethods() > 0) {
2101 Result += "\n\t, &_OBJC_CLASS_METHODS_";
2102 Result += CDecl->getName();
2103 Result += "\n";
2104 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002105 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002106 Result += ", 0\n";
2107 if (CDecl->getNumIntfRefProtocols() > 0) {
2108 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2109 Result += CDecl->getName();
2110 Result += ",0,0\n";
2111 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002112 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002113 Result += "\t,0,0,0,0\n";
2114 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002115
2116 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002117 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2118 Result += CDecl->getName();
2119 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2120 "{\n\t&_OBJC_METACLASS_";
2121 Result += CDecl->getName();
2122 if (SuperClass) {
2123 Result += ", \"";
2124 Result += SuperClass->getName();
2125 Result += "\", \"";
2126 Result += CDecl->getName();
2127 Result += "\"";
2128 }
2129 else {
2130 Result += ", 0, \"";
2131 Result += CDecl->getName();
2132 Result += "\"";
2133 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002134 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002135 Result += ", 0,1";
2136 if (!ObjcSynthesizedStructs.count(CDecl))
2137 Result += ",0";
2138 else {
2139 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002140 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002141 Result += CDecl->getName();
2142 Result += ")";
2143 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002144 if (NumIvars > 0) {
2145 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2146 Result += CDecl->getName();
2147 Result += "\n\t";
2148 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002149 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002150 Result += ",0";
2151 if (IDecl->getNumInstanceMethods() > 0) {
2152 Result += ", &_OBJC_INSTANCE_METHODS_";
2153 Result += CDecl->getName();
2154 Result += ", 0\n\t";
2155 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002156 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002157 Result += ",0,0";
2158 if (CDecl->getNumIntfRefProtocols() > 0) {
2159 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2160 Result += CDecl->getName();
2161 Result += ", 0,0\n";
2162 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002163 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002164 Result += ",0,0,0\n";
2165 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002166}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002167
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002168/// RewriteImplementations - This routine rewrites all method implementations
2169/// and emits meta-data.
2170
2171void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002172 int ClsDefCount = ClassImplementation.size();
2173 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002174
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002175 if (ClsDefCount == 0 && CatDefCount == 0)
2176 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002177 // Rewrite implemented methods
2178 for (int i = 0; i < ClsDefCount; i++)
2179 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002180
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002181 for (int i = 0; i < CatDefCount; i++)
2182 RewriteImplementationDecl(CategoryImplementation[i]);
2183
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002184 // This is needed for use of offsetof
2185 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002186
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002187 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002188 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002189 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002190
2191 // For each implemented category, write out all its meta data.
2192 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002193 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002194
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002195 // Write objc_symtab metadata
2196 /*
2197 struct _objc_symtab
2198 {
2199 long sel_ref_cnt;
2200 SEL *refs;
2201 short cls_def_cnt;
2202 short cat_def_cnt;
2203 void *defs[cls_def_cnt + cat_def_cnt];
2204 };
2205 */
2206
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002207 Result += "\nstruct _objc_symtab {\n";
2208 Result += "\tlong sel_ref_cnt;\n";
2209 Result += "\tSEL *refs;\n";
2210 Result += "\tshort cls_def_cnt;\n";
2211 Result += "\tshort cat_def_cnt;\n";
2212 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2213 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002214
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002215 Result += "static struct _objc_symtab "
2216 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2217 Result += "\t0, 0, " + utostr(ClsDefCount)
2218 + ", " + utostr(CatDefCount) + "\n";
2219 for (int i = 0; i < ClsDefCount; i++) {
2220 Result += "\t,&_OBJC_CLASS_";
2221 Result += ClassImplementation[i]->getName();
2222 Result += "\n";
2223 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002224
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002225 for (int i = 0; i < CatDefCount; i++) {
2226 Result += "\t,&_OBJC_CATEGORY_";
2227 Result += CategoryImplementation[i]->getClassInterface()->getName();
2228 Result += "_";
2229 Result += CategoryImplementation[i]->getName();
2230 Result += "\n";
2231 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002232
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002233 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002234
2235 // Write objc_module metadata
2236
2237 /*
2238 struct _objc_module {
2239 long version;
2240 long size;
2241 const char *name;
2242 struct _objc_symtab *symtab;
2243 }
2244 */
2245
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002246 Result += "\nstruct _objc_module {\n";
2247 Result += "\tlong version;\n";
2248 Result += "\tlong size;\n";
2249 Result += "\tconst char *name;\n";
2250 Result += "\tstruct _objc_symtab *symtab;\n";
2251 Result += "};\n\n";
2252 Result += "static struct _objc_module "
2253 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002254 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2255 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002256 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002257
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002258}
Chris Lattner311ff022007-10-16 22:36:42 +00002259