blob: b17f32bd1428eec89b2d575a838191e4a024b462 [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 Narofff6248702007-11-15 17:06:21 +000089 const char *s = "struct objc_selector; struct objc_class; struct objc_super;\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +000090 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +000091 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +000092 "extern struct objc_object *objc_msgSendSuper"
93 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000094 "extern struct objc_object *objc_msgSend_stret"
95 "(struct objc_object *, struct objc_selector *, ...);\n"
96 "extern struct objc_object *objc_msgSendSuper_stret"
97 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +000098 "extern struct objc_object *objc_msgSend_fpret"
99 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000100 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000101 "(const char *);\n"
102 "extern void objc_exception_throw(struct objc_object *);\n"
103 "extern void objc_exception_try_enter(void *);\n"
104 "extern void objc_exception_try_exit(void *);\n"
105 "extern struct objc_object *objc_exception_extract(void *);\n"
106 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000107 "(struct objc_class *, struct objc_object *, ...);\n"
108 "#include <Objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000109
Steve Naroffab972d32007-11-04 22:37:50 +0000110 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
111 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000112 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000113
Chris Lattnerf04da132007-10-24 17:06:59 +0000114 // Top Level Driver code.
115 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000116 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000117 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000118 ~RewriteTest();
119
120 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000121 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000122 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000123 void RewriteTabs();
124 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000125 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000126 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000127 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000128 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000129 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000130 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff71c0a952007-11-13 23:01:27 +0000131 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000132 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000133 void RewriteFunctionDecl(FunctionDecl *FD);
Steve Naroffd5255f52007-11-01 13:24:47 +0000134 void RewriteObjcQualifiedInterfaceTypes(
135 const FunctionTypeProto *proto, FunctionDecl *FD);
136 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000137 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
138 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000139
Chris Lattnerf04da132007-10-24 17:06:59 +0000140 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000141 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000142 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000143 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000144 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000145 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000146 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000147 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
148 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
149 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000150 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000151 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
152 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000153 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000154 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000155 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000156 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000157 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000158 void SynthGetClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000159 void SynthCFStringFunctionDecl();
160
Chris Lattnerf04da132007-10-24 17:06:59 +0000161 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000162 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
163 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000164
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000165 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
166 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000167
Steve Naroff0416fb92007-11-11 17:19:15 +0000168 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000169 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000170 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000171 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000172 const char *ClassName,
173 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000174
175 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
176 int NumProtocols,
177 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000178 const char *ClassName,
179 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000180 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
181 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000182 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
183 ObjcIvarDecl *ivar,
184 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000185 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000186 };
187}
188
Chris Lattnere365c502007-11-30 22:25:36 +0000189ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
190 return new RewriteTest(Diags);
191}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000192
Chris Lattnerf04da132007-10-24 17:06:59 +0000193//===----------------------------------------------------------------------===//
194// Top Level Driver Code
195//===----------------------------------------------------------------------===//
196
Chris Lattner8a12c272007-10-11 18:38:32 +0000197void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000198 // Two cases: either the decl could be in the main file, or it could be in a
199 // #included file. If the former, rewrite it now. If the later, check to see
200 // if we rewrote the #include/#import.
201 SourceLocation Loc = D->getLocation();
202 Loc = SM->getLogicalLoc(Loc);
203
204 // If this is for a builtin, ignore it.
205 if (Loc.isInvalid()) return;
206
Steve Naroffebf2b562007-10-23 23:50:29 +0000207 // Look for built-in declarations that we need to refer during the rewrite.
208 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000209 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000210 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
211 // declared in <Foundation/NSString.h>
212 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
213 ConstantStringClassReference = FVD;
214 return;
215 }
Steve Naroffbef11852007-10-26 20:53:56 +0000216 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
217 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000218 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
219 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000220 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
221 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000222 } else if (ObjcForwardProtocolDecl *FP =
223 dyn_cast<ObjcForwardProtocolDecl>(D)){
224 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000225 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000226 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000227 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
228 return HandleDeclInMainFile(D);
229
Chris Lattnerf04da132007-10-24 17:06:59 +0000230 // Otherwise, see if there is a #import in the main file that should be
231 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000232 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000233}
234
Chris Lattnerf04da132007-10-24 17:06:59 +0000235/// HandleDeclInMainFile - This is called for each top-level decl defined in the
236/// main file of the input.
237void RewriteTest::HandleDeclInMainFile(Decl *D) {
238 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
239 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000240 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000241
242 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000243 if (Stmt *Body = MD->getBody()) {
244 //Body->dump();
245 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000246 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000247 CurMethodDecl = 0;
248 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000249 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
251 ClassImplementation.push_back(CI);
252 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
253 CategoryImplementation.push_back(CI);
254 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
255 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000256 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
257 if (VD->getInit())
258 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
259 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000260 // Nothing yet.
261}
262
263RewriteTest::~RewriteTest() {
264 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000265
266 // Rewrite tabs if we care.
267 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000268
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000269 // Rewrite Objective-c meta data*
270 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000271 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000272
Chris Lattnerf04da132007-10-24 17:06:59 +0000273 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
274 // we are done.
275 if (const RewriteBuffer *RewriteBuf =
276 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000277 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000278 std::string S(RewriteBuf->begin(), RewriteBuf->end());
279 printf("%s\n", S.c_str());
280 } else {
281 printf("No changes\n");
282 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000283 // Emit metadata.
284 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000285}
286
Chris Lattnerf04da132007-10-24 17:06:59 +0000287//===----------------------------------------------------------------------===//
288// Syntactic (non-AST) Rewriting Code
289//===----------------------------------------------------------------------===//
290
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000291void RewriteTest::RewriteInclude(SourceLocation Loc) {
292 // Rip up the #include stack to the main file.
293 SourceLocation IncLoc = Loc, NextLoc = Loc;
294 do {
295 IncLoc = Loc;
296 Loc = SM->getLogicalLoc(NextLoc);
297 NextLoc = SM->getIncludeLoc(Loc);
298 } while (!NextLoc.isInvalid());
299
300 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
301 // IncLoc indicates the header that was included if it is useful.
302 IncLoc = SM->getLogicalLoc(IncLoc);
303 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
304 Loc == LastIncLoc)
305 return;
306 LastIncLoc = Loc;
307
308 unsigned IncCol = SM->getColumnNumber(Loc);
309 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
310
311 // Replace the #import with #include.
312 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
313}
314
Chris Lattnerf04da132007-10-24 17:06:59 +0000315void RewriteTest::RewriteTabs() {
316 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
317 const char *MainBufStart = MainBuf.first;
318 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000319
Chris Lattnerf04da132007-10-24 17:06:59 +0000320 // Loop over the whole file, looking for tabs.
321 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
322 if (*BufPtr != '\t')
323 continue;
324
325 // Okay, we found a tab. This tab will turn into at least one character,
326 // but it depends on which 'virtual column' it is in. Compute that now.
327 unsigned VCol = 0;
328 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
329 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
330 ++VCol;
331
332 // Okay, now that we know the virtual column, we know how many spaces to
333 // insert. We assume 8-character tab-stops.
334 unsigned Spaces = 8-(VCol & 7);
335
336 // Get the location of the tab.
337 SourceLocation TabLoc =
338 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
339
340 // Rewrite the single tab character into a sequence of spaces.
341 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
342 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000343}
344
345
Chris Lattnerf04da132007-10-24 17:06:59 +0000346void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
347 int numDecls = ClassDecl->getNumForwardDecls();
348 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
349
350 // Get the start location and compute the semi location.
351 SourceLocation startLoc = ClassDecl->getLocation();
352 const char *startBuf = SM->getCharacterData(startLoc);
353 const char *semiPtr = strchr(startBuf, ';');
354
355 // Translate to typedef's that forward reference structs with the same name
356 // as the class. As a convenience, we include the original declaration
357 // as a comment.
358 std::string typedefString;
359 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000360 typedefString.append(startBuf, semiPtr-startBuf+1);
361 typedefString += "\n";
362 for (int i = 0; i < numDecls; i++) {
363 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000364 typedefString += "#ifndef _REWRITER_typedef_";
365 typedefString += ForwardDecl->getName();
366 typedefString += "\n";
367 typedefString += "#define _REWRITER_typedef_";
368 typedefString += ForwardDecl->getName();
369 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000370 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000371 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000372 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000373 }
374
375 // Replace the @class with typedefs corresponding to the classes.
376 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
377 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000378}
379
Steve Naroff71c0a952007-11-13 23:01:27 +0000380void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff423cb562007-10-30 13:30:57 +0000381 for (int i = 0; i < nMethods; i++) {
382 ObjcMethodDecl *Method = Methods[i];
Steve Naroff1d098f62007-11-14 14:34:23 +0000383 SourceLocation LocStart = Method->getLocStart();
384 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000385
Steve Naroff1d098f62007-11-14 14:34:23 +0000386 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
387 Rewrite.InsertText(LocStart, "/* ", 3);
388 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
389 } else {
390 Rewrite.InsertText(LocStart, "// ", 3);
391 }
Steve Naroff423cb562007-10-30 13:30:57 +0000392 }
393}
394
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000395void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
396{
397 for (int i = 0; i < nProperties; i++) {
398 ObjcPropertyDecl *Property = Properties[i];
399 SourceLocation Loc = Property->getLocation();
400
401 Rewrite.ReplaceText(Loc, 0, "// ", 3);
402
403 // FIXME: handle properties that are declared across multiple lines.
404 }
405}
406
Steve Naroff423cb562007-10-30 13:30:57 +0000407void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
408 SourceLocation LocStart = CatDecl->getLocStart();
409
410 // FIXME: handle category headers that are declared across multiple lines.
411 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
412
Steve Naroff71c0a952007-11-13 23:01:27 +0000413 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
414 CatDecl->getInstanceMethods());
415 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
416 CatDecl->getClassMethods());
Steve Naroff423cb562007-10-30 13:30:57 +0000417 // Lastly, comment out the @end.
418 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
419}
420
Steve Naroff752d6ef2007-10-30 16:42:30 +0000421void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000422 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000423
Steve Naroff752d6ef2007-10-30 16:42:30 +0000424 SourceLocation LocStart = PDecl->getLocStart();
425
426 // FIXME: handle protocol headers that are declared across multiple lines.
427 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
428
Steve Naroff71c0a952007-11-13 23:01:27 +0000429 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
430 PDecl->getInstanceMethods());
431 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
432 PDecl->getClassMethods());
Steve Naroff752d6ef2007-10-30 16:42:30 +0000433 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000434 SourceLocation LocEnd = PDecl->getAtEndLoc();
435 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000436
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000437 // Must comment out @optional/@required
438 const char *startBuf = SM->getCharacterData(LocStart);
439 const char *endBuf = SM->getCharacterData(LocEnd);
440 for (const char *p = startBuf; p < endBuf; p++) {
441 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
442 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000443 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000444 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
445 CommentedOptional.c_str(), CommentedOptional.size());
446
447 }
448 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
449 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000450 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000451 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
452 CommentedRequired.c_str(), CommentedRequired.size());
453
454 }
455 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000456}
457
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000458void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
459 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000460 if (LocStart.isInvalid())
461 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000462 // FIXME: handle forward protocol that are declared across multiple lines.
463 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
464}
465
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000466void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
467 std::string &ResultStr) {
468 ResultStr += "\nstatic ";
469 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000470 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000471
472 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000473 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000474
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000475 if (OMD->isInstance())
476 NameStr += "_I_";
477 else
478 NameStr += "_C_";
479
480 NameStr += OMD->getClassInterface()->getName();
481 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000482
483 NamedDecl *MethodContext = OMD->getMethodContext();
484 if (ObjcCategoryImplDecl *CID =
485 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000486 NameStr += CID->getName();
487 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000488 }
489 // Append selector names, replacing ':' with '_'
490 const char *selName = OMD->getSelector().getName().c_str();
491 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000492 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000493 else {
494 std::string selString = OMD->getSelector().getName();
495 int len = selString.size();
496 for (int i = 0; i < len; i++)
497 if (selString[i] == ':')
498 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000499 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000500 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000501 // Remember this name for metadata emission
502 MethodInternalNames[OMD] = NameStr;
503 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000504
505 // Rewrite arguments
506 ResultStr += "(";
507
508 // invisible arguments
509 if (OMD->isInstance()) {
510 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
511 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000512 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
513 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000514 ResultStr += selfTy.getAsString();
515 }
516 else
517 ResultStr += Context->getObjcIdType().getAsString();
518
519 ResultStr += " self, ";
520 ResultStr += Context->getObjcSelType().getAsString();
521 ResultStr += " _cmd";
522
523 // Method arguments.
524 for (int i = 0; i < OMD->getNumParams(); i++) {
525 ParmVarDecl *PDecl = OMD->getParamDecl(i);
526 ResultStr += ", ";
527 ResultStr += PDecl->getType().getAsString();
528 ResultStr += " ";
529 ResultStr += PDecl->getName();
530 }
531 ResultStr += ")";
532
533}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000534void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
535 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
536 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000537
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000538 if (IMD)
539 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
540 else
541 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000542
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000543 int numMethods = IMD ? IMD->getNumInstanceMethods()
544 : CID->getNumInstanceMethods();
545
546 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000547 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000548 ObjcMethodDecl *OMD;
549 if (IMD)
550 OMD = IMD->getInstanceMethods()[i];
551 else
552 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000553 RewriteObjcMethodDecl(OMD, ResultStr);
554 SourceLocation LocStart = OMD->getLocStart();
555 SourceLocation LocEnd = OMD->getBody()->getLocStart();
556
557 const char *startBuf = SM->getCharacterData(LocStart);
558 const char *endBuf = SM->getCharacterData(LocEnd);
559 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
560 ResultStr.c_str(), ResultStr.size());
561 }
562
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000563 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
564 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000565 std::string ResultStr;
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000566 ObjcMethodDecl *OMD;
567 if (IMD)
568 OMD = IMD->getClassMethods()[i];
569 else
570 OMD = CID->getClassMethods()[i];
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000571 RewriteObjcMethodDecl(OMD, ResultStr);
572 SourceLocation LocStart = OMD->getLocStart();
573 SourceLocation LocEnd = OMD->getBody()->getLocStart();
574
575 const char *startBuf = SM->getCharacterData(LocStart);
576 const char *endBuf = SM->getCharacterData(LocEnd);
577 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
578 ResultStr.c_str(), ResultStr.size());
579 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000580 if (IMD)
581 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
582 else
583 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000584}
585
Steve Naroffbef11852007-10-26 20:53:56 +0000586void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000587 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000588 if (!ObjcForwardDecls.count(ClassDecl)) {
589 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000590 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000591 ResultStr += ClassDecl->getName();
592 ResultStr += "\n";
593 ResultStr += "#define _REWRITER_typedef_";
594 ResultStr += ClassDecl->getName();
595 ResultStr += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000596 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000597 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000598 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000599
600 // Mark this typedef as having been generated.
601 ObjcForwardDecls.insert(ClassDecl);
602 }
Steve Narofff908a872007-10-30 02:23:23 +0000603 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
604
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000605 RewriteProperties(ClassDecl->getNumPropertyDecl(),
606 ClassDecl->getPropertyDecl());
Steve Naroff71c0a952007-11-13 23:01:27 +0000607 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
608 ClassDecl->getInstanceMethods());
609 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
610 ClassDecl->getClassMethods());
Steve Naroffbef11852007-10-26 20:53:56 +0000611
Steve Naroff2feac5e2007-10-30 03:43:13 +0000612 // Lastly, comment out the @end.
613 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000614}
615
Steve Naroff7e3411b2007-11-15 02:58:25 +0000616Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
617 ObjcIvarDecl *D = IV->getDecl();
618 if (IV->isFreeIvar()) {
619 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
620 IV->getLocation());
621 Rewrite.ReplaceStmt(IV, Replacement);
622 delete IV;
623 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000624 } else {
625 if (CurMethodDecl) {
626 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
627 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
628 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
629 IdentifierInfo *II = intT->getDecl()->getIdentifier();
630 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
631 II, 0);
632 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
633
634 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
635 // Don't forget the parens to enforce the proper binding.
636 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
637 Rewrite.ReplaceStmt(IV->getBase(), PE);
638 delete IV->getBase();
639 return PE;
640 }
641 }
642 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000643 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000644 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000645}
646
Chris Lattnerf04da132007-10-24 17:06:59 +0000647//===----------------------------------------------------------------------===//
648// Function Body / Expression rewriting
649//===----------------------------------------------------------------------===//
650
Steve Narofff3473a72007-11-09 15:20:18 +0000651Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000652 // Otherwise, just rewrite all children.
653 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
654 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000655 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000656 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000657 if (newStmt)
658 *CI = newStmt;
659 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000660
661 // Handle specific things.
662 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
663 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000664
665 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
666 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000667
668 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
669 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000670
671 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
672 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000673
Steve Naroff934f2762007-10-24 22:48:43 +0000674 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
675 // Before we rewrite it, put the original message expression in a comment.
676 SourceLocation startLoc = MessExpr->getLocStart();
677 SourceLocation endLoc = MessExpr->getLocEnd();
678
679 const char *startBuf = SM->getCharacterData(startLoc);
680 const char *endBuf = SM->getCharacterData(endLoc);
681
682 std::string messString;
683 messString += "// ";
684 messString.append(startBuf, endBuf-startBuf+1);
685 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000686
Steve Naroff934f2762007-10-24 22:48:43 +0000687 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
688 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
689 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000690 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000691 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000692 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000693
694 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
695 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000696
697 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
698 return RewriteObjcThrowStmt(StmtThrow);
Steve Naroff874e2322007-11-15 10:28:18 +0000699#if 0
700 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
701 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
702 // Get the new text.
703 std::ostringstream Buf;
704 Replacement->printPretty(Buf);
705 const std::string &Str = Buf.str();
706
707 printf("CAST = %s\n", &Str[0]);
708 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
709 delete S;
710 return Replacement;
711 }
712#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000713 // Return this stmt unmodified.
714 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000715}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000716
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000717Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000718 // Get the start location and compute the semi location.
719 SourceLocation startLoc = S->getLocStart();
720 const char *startBuf = SM->getCharacterData(startLoc);
721
722 assert((*startBuf == '@') && "bogus @try location");
723
724 std::string buf;
725 // declare a new scope with two variables, _stack and _rethrow.
726 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
727 buf += "int buf[18/*32-bit i386*/];\n";
728 buf += "char *pointers[4];} _stack;\n";
729 buf += "id volatile _rethrow = 0;\n";
730 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000731 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000732
733 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
734
735 startLoc = S->getTryBody()->getLocEnd();
736 startBuf = SM->getCharacterData(startLoc);
737
738 assert((*startBuf == '}') && "bogus @try block");
739
740 SourceLocation lastCurlyLoc = startLoc;
741
742 startLoc = startLoc.getFileLocWithOffset(1);
743 buf = " /* @catch begin */ else {\n";
744 buf += " id _caught = objc_exception_extract(&_stack);\n";
745 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000746 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000747 buf += " _rethrow = objc_exception_extract(&_stack);\n";
748 buf += " else { /* @catch continue */";
749
Chris Lattner28d1fe82007-11-08 04:41:51 +0000750 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000751
752 bool sawIdTypedCatch = false;
753 Stmt *lastCatchBody = 0;
754 ObjcAtCatchStmt *catchList = S->getCatchStmts();
755 while (catchList) {
756 Stmt *catchStmt = catchList->getCatchParamStmt();
757
758 if (catchList == S->getCatchStmts())
759 buf = "if ("; // we are generating code for the first catch clause
760 else
761 buf = "else if (";
762 startLoc = catchList->getLocStart();
763 startBuf = SM->getCharacterData(startLoc);
764
765 assert((*startBuf == '@') && "bogus @catch location");
766
767 const char *lParenLoc = strchr(startBuf, '(');
768
769 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
770 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
771 if (t == Context->getObjcIdType()) {
772 buf += "1) { ";
773 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
774 buf.c_str(), buf.size());
775 sawIdTypedCatch = true;
776 } else if (const PointerType *pType = t->getAsPointerType()) {
777 ObjcInterfaceType *cls; // Should be a pointer to a class.
778
779 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
780 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000781 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000782 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000783 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000784 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
785 buf.c_str(), buf.size());
786 }
787 }
788 // Now rewrite the body...
789 lastCatchBody = catchList->getCatchBody();
790 SourceLocation rParenLoc = catchList->getRParenLoc();
791 SourceLocation bodyLoc = lastCatchBody->getLocStart();
792 const char *bodyBuf = SM->getCharacterData(bodyLoc);
793 const char *rParenBuf = SM->getCharacterData(rParenLoc);
794 assert((*rParenBuf == ')') && "bogus @catch paren location");
795 assert((*bodyBuf == '{') && "bogus @catch body location");
796
797 buf = " = _caught;";
798 // Here we replace ") {" with "= _caught;" (which initializes and
799 // declares the @catch parameter).
800 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
801 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000802 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000803 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000804 }
Steve Naroff75730982007-11-07 04:08:17 +0000805 catchList = catchList->getNextCatchStmt();
806 }
807 // Complete the catch list...
808 if (lastCatchBody) {
809 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
810 const char *bodyBuf = SM->getCharacterData(bodyLoc);
811 assert((*bodyBuf == '}') && "bogus @catch body location");
812 bodyLoc = bodyLoc.getFileLocWithOffset(1);
813 buf = " } } /* @catch end */\n";
814
Chris Lattner28d1fe82007-11-08 04:41:51 +0000815 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000816
817 // Set lastCurlyLoc
818 lastCurlyLoc = lastCatchBody->getLocEnd();
819 }
820 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
821 startLoc = finalStmt->getLocStart();
822 startBuf = SM->getCharacterData(startLoc);
823 assert((*startBuf == '@') && "bogus @finally start");
824
825 buf = "/* @finally */";
826 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
827
828 Stmt *body = finalStmt->getFinallyBody();
829 SourceLocation startLoc = body->getLocStart();
830 SourceLocation endLoc = body->getLocEnd();
831 const char *startBuf = SM->getCharacterData(startLoc);
832 const char *endBuf = SM->getCharacterData(endLoc);
833 assert((*startBuf == '{') && "bogus @finally body location");
834 assert((*endBuf == '}') && "bogus @finally body location");
835
836 startLoc = startLoc.getFileLocWithOffset(1);
837 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000838 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000839 endLoc = endLoc.getFileLocWithOffset(-1);
840 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000841 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000842
843 // Set lastCurlyLoc
844 lastCurlyLoc = body->getLocEnd();
845 }
846 // Now emit the final closing curly brace...
847 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
848 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000849 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000850 return 0;
851}
852
853Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
854 return 0;
855}
856
857Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
858 return 0;
859}
860
Steve Naroff2bd03922007-11-07 15:32:26 +0000861// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
862// the throw expression is typically a message expression that's already
863// been rewritten! (which implies the SourceLocation's are invalid).
864Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
865 // Get the start location and compute the semi location.
866 SourceLocation startLoc = S->getLocStart();
867 const char *startBuf = SM->getCharacterData(startLoc);
868
869 assert((*startBuf == '@') && "bogus @throw location");
870
871 std::string buf;
872 /* void objc_exception_throw(id) __attribute__((noreturn)); */
873 buf = "objc_exception_throw(";
874 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
875 const char *semiBuf = strchr(startBuf, ';');
876 assert((*semiBuf == ';') && "@throw: can't find ';'");
877 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
878 buf = ");";
879 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
880 return 0;
881}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000882
Chris Lattnere64b7772007-10-24 16:57:36 +0000883Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000884 // Create a new string expression.
885 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000886 std::string StrEncoding;
887 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
888 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
889 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000890 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000891 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
892 // replacement failed.
Chris Lattner182745a2007-12-02 01:09:57 +0000893 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
894 "rewriter could not replace sub-expression due to macros");
895 SourceRange Range = Exp->getSourceRange();
896 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
897 delete Replacement;
Chris Lattnere365c502007-11-30 22:25:36 +0000898 return Exp;
899 }
900
Chris Lattner07506182007-11-30 22:53:43 +0000901 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000902 delete Exp;
903 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000904}
905
Steve Naroffb42f8412007-11-05 14:50:49 +0000906Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
907 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
908 // Create a call to sel_registerName("selName").
909 llvm::SmallVector<Expr*, 8> SelExprs;
910 QualType argType = Context->getPointerType(Context->CharTy);
911 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
912 Exp->getSelector().getName().size(),
913 false, argType, SourceLocation(),
914 SourceLocation()));
915 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
916 &SelExprs[0], SelExprs.size());
917 Rewrite.ReplaceStmt(Exp, SelExp);
918 delete Exp;
919 return SelExp;
920}
921
Steve Naroff934f2762007-10-24 22:48:43 +0000922CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
923 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000924 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000925 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000926
927 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000928 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000929
930 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000931 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000932 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
933
934 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000935
Steve Naroff934f2762007-10-24 22:48:43 +0000936 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
937}
938
Steve Naroffd5255f52007-11-01 13:24:47 +0000939static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
940 const char *&startRef, const char *&endRef) {
941 while (startBuf < endBuf) {
942 if (*startBuf == '<')
943 startRef = startBuf; // mark the start.
944 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000945 if (startRef && *startRef == '<') {
946 endRef = startBuf; // mark the end.
947 return true;
948 }
949 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000950 }
951 startBuf++;
952 }
953 return false;
954}
955
956bool RewriteTest::needToScanForQualifiers(QualType T) {
957 // FIXME: we don't currently represent "id <Protocol>" in the type system.
958 if (T == Context->getObjcIdType())
959 return true;
960
961 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +0000962 Type *pointeeType = pType->getPointeeType().getTypePtr();
963 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
964 return true; // we have "Class <Protocol> *".
965 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000966 return false;
967}
968
969void RewriteTest::RewriteObjcQualifiedInterfaceTypes(
970 const FunctionTypeProto *proto, FunctionDecl *FD) {
971
972 if (needToScanForQualifiers(proto->getResultType())) {
973 // Since types are unique, we need to scan the buffer.
974 SourceLocation Loc = FD->getLocation();
975
976 const char *endBuf = SM->getCharacterData(Loc);
977 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +0000978 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +0000979 startBuf--; // scan backward (from the decl location) for return type.
980 const char *startRef = 0, *endRef = 0;
981 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
982 // Get the locations of the startRef, endRef.
983 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
984 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
985 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +0000986 Rewrite.InsertText(LessLoc, "/*", 2);
987 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +0000988 }
989 }
Steve Naroffd5255f52007-11-01 13:24:47 +0000990 // Now check arguments.
991 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
992 if (needToScanForQualifiers(proto->getArgType(i))) {
993 // Since types are unique, we need to scan the buffer.
994 SourceLocation Loc = FD->getLocation();
995
996 const char *startBuf = SM->getCharacterData(Loc);
997 const char *endBuf = startBuf;
998 while (*endBuf != ';')
999 endBuf++; // scan forward (from the decl location) for argument types.
1000 const char *startRef = 0, *endRef = 0;
1001 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1002 // Get the locations of the startRef, endRef.
1003 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1004 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1005 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001006 Rewrite.InsertText(LessLoc, "/*", 2);
1007 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001008 }
1009 }
1010 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001011}
1012
Steve Naroff09b266e2007-10-30 23:14:51 +00001013void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1014 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001015 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001016 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001017 return;
1018 }
1019 // Check for ObjC 'id' and class types that have been adorned with protocol
1020 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1021 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1022 assert(funcType && "missing function type");
Steve Naroffd5255f52007-11-01 13:24:47 +00001023 if (const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType))
1024 RewriteObjcQualifiedInterfaceTypes(proto, FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001025}
1026
1027// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1028void RewriteTest::SynthMsgSendFunctionDecl() {
1029 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1030 llvm::SmallVector<QualType, 16> ArgTys;
1031 QualType argT = Context->getObjcIdType();
1032 assert(!argT.isNull() && "Can't find 'id' type");
1033 ArgTys.push_back(argT);
1034 argT = Context->getObjcSelType();
1035 assert(!argT.isNull() && "Can't find 'SEL' type");
1036 ArgTys.push_back(argT);
1037 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1038 &ArgTys[0], ArgTys.size(),
1039 true /*isVariadic*/);
1040 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1041 msgSendIdent, msgSendType,
1042 FunctionDecl::Extern, false, 0);
1043}
1044
Steve Naroff874e2322007-11-15 10:28:18 +00001045// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1046void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1047 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1048 llvm::SmallVector<QualType, 16> ArgTys;
1049 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1050 &Context->Idents.get("objc_super"), 0);
1051 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1052 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1053 ArgTys.push_back(argT);
1054 argT = Context->getObjcSelType();
1055 assert(!argT.isNull() && "Can't find 'SEL' type");
1056 ArgTys.push_back(argT);
1057 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1058 &ArgTys[0], ArgTys.size(),
1059 true /*isVariadic*/);
1060 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1061 msgSendIdent, msgSendType,
1062 FunctionDecl::Extern, false, 0);
1063}
1064
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001065// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1066void RewriteTest::SynthMsgSendStretFunctionDecl() {
1067 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1068 llvm::SmallVector<QualType, 16> ArgTys;
1069 QualType argT = Context->getObjcIdType();
1070 assert(!argT.isNull() && "Can't find 'id' type");
1071 ArgTys.push_back(argT);
1072 argT = Context->getObjcSelType();
1073 assert(!argT.isNull() && "Can't find 'SEL' type");
1074 ArgTys.push_back(argT);
1075 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1076 &ArgTys[0], ArgTys.size(),
1077 true /*isVariadic*/);
1078 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1079 msgSendIdent, msgSendType,
1080 FunctionDecl::Extern, false, 0);
1081}
1082
1083// SynthMsgSendSuperStretFunctionDecl -
1084// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1085void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1086 IdentifierInfo *msgSendIdent =
1087 &Context->Idents.get("objc_msgSendSuper_stret");
1088 llvm::SmallVector<QualType, 16> ArgTys;
1089 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1090 &Context->Idents.get("objc_super"), 0);
1091 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1092 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1093 ArgTys.push_back(argT);
1094 argT = Context->getObjcSelType();
1095 assert(!argT.isNull() && "Can't find 'SEL' type");
1096 ArgTys.push_back(argT);
1097 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1098 &ArgTys[0], ArgTys.size(),
1099 true /*isVariadic*/);
1100 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1101 msgSendIdent, msgSendType,
1102 FunctionDecl::Extern, false, 0);
1103}
1104
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001105// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1106void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1107 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1108 llvm::SmallVector<QualType, 16> ArgTys;
1109 QualType argT = Context->getObjcIdType();
1110 assert(!argT.isNull() && "Can't find 'id' type");
1111 ArgTys.push_back(argT);
1112 argT = Context->getObjcSelType();
1113 assert(!argT.isNull() && "Can't find 'SEL' type");
1114 ArgTys.push_back(argT);
1115 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1116 &ArgTys[0], ArgTys.size(),
1117 true /*isVariadic*/);
1118 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1119 msgSendIdent, msgSendType,
1120 FunctionDecl::Extern, false, 0);
1121}
1122
Steve Naroff09b266e2007-10-30 23:14:51 +00001123// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1124void RewriteTest::SynthGetClassFunctionDecl() {
1125 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1126 llvm::SmallVector<QualType, 16> ArgTys;
1127 ArgTys.push_back(Context->getPointerType(
1128 Context->CharTy.getQualifiedType(QualType::Const)));
1129 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1130 &ArgTys[0], ArgTys.size(),
1131 false /*isVariadic*/);
1132 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1133 getClassIdent, getClassType,
1134 FunctionDecl::Extern, false, 0);
1135}
1136
Steve Naroff96984642007-11-08 14:30:50 +00001137// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1138void RewriteTest::SynthCFStringFunctionDecl() {
1139 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1140 llvm::SmallVector<QualType, 16> ArgTys;
1141 ArgTys.push_back(Context->getPointerType(
1142 Context->CharTy.getQualifiedType(QualType::Const)));
1143 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1144 &ArgTys[0], ArgTys.size(),
1145 false /*isVariadic*/);
1146 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1147 getClassIdent, getClassType,
1148 FunctionDecl::Extern, false, 0);
1149}
1150
Steve Naroffbeaf2992007-11-03 11:27:19 +00001151Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001152#if 1
1153 // This rewrite is specific to GCC, which has builtin support for CFString.
1154 if (!CFStringFunctionDecl)
1155 SynthCFStringFunctionDecl();
1156 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1157 llvm::SmallVector<Expr*, 8> StrExpr;
1158 StrExpr.push_back(Exp->getString());
1159 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1160 &StrExpr[0], StrExpr.size());
1161 // cast to NSConstantString *
1162 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1163 Rewrite.ReplaceStmt(Exp, cast);
1164 delete Exp;
1165 return cast;
1166#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001167 assert(ConstantStringClassReference && "Can't find constant string reference");
1168 llvm::SmallVector<Expr*, 4> InitExprs;
1169
1170 // Synthesize "(Class)&_NSConstantStringClassReference"
1171 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1172 ConstantStringClassReference->getType(),
1173 SourceLocation());
1174 QualType expType = Context->getPointerType(ClsRef->getType());
1175 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1176 expType, SourceLocation());
1177 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1178 SourceLocation());
1179 InitExprs.push_back(cast); // set the 'isa'.
1180 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1181 unsigned IntSize = static_cast<unsigned>(
1182 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1183 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1184 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1185 Exp->getLocStart());
1186 InitExprs.push_back(len); // set "int numBytes".
1187
1188 // struct NSConstantString
1189 QualType CFConstantStrType = Context->getCFConstantStringType();
1190 // (struct NSConstantString) { <exprs from above> }
1191 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1192 &InitExprs[0], InitExprs.size(),
1193 SourceLocation());
1194 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1195 // struct NSConstantString *
1196 expType = Context->getPointerType(StrRep->getType());
1197 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1198 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001199 // cast to NSConstantString *
1200 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001201 Rewrite.ReplaceStmt(Exp, cast);
1202 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001203 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001204#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001205}
1206
Steve Naroff874e2322007-11-15 10:28:18 +00001207ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
1208 if (CurMethodDecl) { // check if we are sending a message to 'super'
1209 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1210 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1211 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1212 if (!strcmp(PVD->getName(), "self")) {
1213 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1214 if (ObjcInterfaceType *IT =
1215 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1216 if (IT->getDecl() ==
1217 CurMethodDecl->getClassInterface()->getSuperClass())
1218 return IT->getDecl();
1219 }
1220 }
1221 }
1222 }
1223 }
1224 }
1225 }
1226 return 0;
1227}
1228
1229// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1230QualType RewriteTest::getSuperStructType() {
1231 if (!SuperStructDecl) {
1232 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1233 &Context->Idents.get("objc_super"), 0);
1234 QualType FieldTypes[2];
1235
1236 // struct objc_object *receiver;
1237 FieldTypes[0] = Context->getObjcIdType();
1238 // struct objc_class *super;
1239 FieldTypes[1] = Context->getObjcClassType();
1240 // Create fields
1241 FieldDecl *FieldDecls[2];
1242
1243 for (unsigned i = 0; i < 2; ++i)
1244 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1245
1246 SuperStructDecl->defineBody(FieldDecls, 4);
1247 }
1248 return Context->getTagDeclType(SuperStructDecl);
1249}
1250
Steve Naroff934f2762007-10-24 22:48:43 +00001251Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Steve Naroffbeaf2992007-11-03 11:27:19 +00001252 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
Steve Naroff09b266e2007-10-30 23:14:51 +00001253 if (!MsgSendFunctionDecl)
1254 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001255 if (!MsgSendSuperFunctionDecl)
1256 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001257 if (!MsgSendStretFunctionDecl)
1258 SynthMsgSendStretFunctionDecl();
1259 if (!MsgSendSuperStretFunctionDecl)
1260 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001261 if (!MsgSendFpretFunctionDecl)
1262 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001263 if (!GetClassFunctionDecl)
1264 SynthGetClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001265
Steve Naroff874e2322007-11-15 10:28:18 +00001266 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001267 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1268 // May need to use objc_msgSend_stret() as well.
1269 FunctionDecl *MsgSendStretFlavor = 0;
1270 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1271 QualType resultType = mDecl->getResultType();
1272 if (resultType.getCanonicalType()->isStructureType()
1273 || resultType.getCanonicalType()->isUnionType())
1274 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001275 else if (resultType.getCanonicalType()->isRealFloatingType())
1276 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001277 }
Steve Naroff874e2322007-11-15 10:28:18 +00001278
Steve Naroff934f2762007-10-24 22:48:43 +00001279 // Synthesize a call to objc_msgSend().
1280 llvm::SmallVector<Expr*, 8> MsgExprs;
1281 IdentifierInfo *clsName = Exp->getClassName();
1282
1283 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1284 if (clsName) { // class message.
1285 llvm::SmallVector<Expr*, 8> ClsExprs;
1286 QualType argType = Context->getPointerType(Context->CharTy);
1287 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1288 clsName->getLength(),
1289 false, argType, SourceLocation(),
1290 SourceLocation()));
1291 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1292 &ClsExprs[0], ClsExprs.size());
1293 MsgExprs.push_back(Cls);
Steve Naroff6568d4d2007-11-14 23:54:14 +00001294 } else { // instance message.
1295 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001296
1297 if (ObjcInterfaceDecl *ID = isSuperReceiver(recExpr)) {
1298 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001299 if (MsgSendStretFlavor)
1300 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001301 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1302
1303 llvm::SmallVector<Expr*, 4> InitExprs;
1304
1305 InitExprs.push_back(recExpr); // set the 'receiver'.
1306
1307 llvm::SmallVector<Expr*, 8> ClsExprs;
1308 QualType argType = Context->getPointerType(Context->CharTy);
1309 ClsExprs.push_back(new StringLiteral(ID->getIdentifier()->getName(),
1310 ID->getIdentifier()->getLength(),
1311 false, argType, SourceLocation(),
1312 SourceLocation()));
1313 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1314 &ClsExprs[0], ClsExprs.size());
1315 InitExprs.push_back(Cls); // set 'super class', using objc_getClass().
1316 // struct objc_super
1317 QualType superType = getSuperStructType();
1318 // (struct objc_super) { <exprs from above> }
1319 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1320 &InitExprs[0], InitExprs.size(),
1321 SourceLocation());
1322 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1323 // struct objc_super *
1324 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1325 Context->getPointerType(SuperRep->getType()),
1326 SourceLocation());
1327 MsgExprs.push_back(Unop);
1328 } else {
1329 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1330 MsgExprs.push_back(recExpr);
1331 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001332 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001333 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001334 llvm::SmallVector<Expr*, 8> SelExprs;
1335 QualType argType = Context->getPointerType(Context->CharTy);
1336 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1337 Exp->getSelector().getName().size(),
1338 false, argType, SourceLocation(),
1339 SourceLocation()));
1340 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1341 &SelExprs[0], SelExprs.size());
1342 MsgExprs.push_back(SelExp);
1343
1344 // Now push any user supplied arguments.
1345 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001346 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001347 // Make all implicit casts explicit...ICE comes in handy:-)
1348 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1349 // Reuse the ICE type, it is exactly what the doctor ordered.
1350 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1351 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001352 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001353 // We've transferred the ownership to MsgExprs. Null out the argument in
1354 // the original expression, since we will delete it below.
1355 Exp->setArg(i, 0);
1356 }
Steve Naroffab972d32007-11-04 22:37:50 +00001357 // Generate the funky cast.
1358 CastExpr *cast;
1359 llvm::SmallVector<QualType, 8> ArgTypes;
1360 QualType returnType;
1361
1362 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001363 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1364 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1365 else
1366 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001367 ArgTypes.push_back(Context->getObjcSelType());
1368 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1369 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001370 for (int i = 0; i < mDecl->getNumParams(); i++) {
1371 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001372 ArgTypes.push_back(t);
1373 }
Steve Naroffab972d32007-11-04 22:37:50 +00001374 returnType = mDecl->getResultType();
1375 } else {
1376 returnType = Context->getObjcIdType();
1377 }
1378 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001379 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001380
1381 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001382 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1383 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001384
1385 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1386 // If we don't do this cast, we get the following bizarre warning/note:
1387 // xx.m:13: warning: function called through a non-compatible type
1388 // xx.m:13: note: if this code is reached, the program will abort
1389 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1390 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001391
Steve Naroffab972d32007-11-04 22:37:50 +00001392 // Now do the "normal" pointer to function cast.
1393 QualType castType = Context->getFunctionType(returnType,
1394 &ArgTypes[0], ArgTypes.size(),
Steve Naroff335eafa2007-11-15 12:35:21 +00001395 Exp->getMethodDecl()->isVariadic());
Steve Naroffab972d32007-11-04 22:37:50 +00001396 castType = Context->getPointerType(castType);
1397 cast = new CastExpr(castType, cast, SourceLocation());
1398
1399 // Don't forget the parens to enforce the proper binding.
1400 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1401
1402 const FunctionType *FT = msgSendType->getAsFunctionType();
1403 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1404 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001405 if (MsgSendStretFlavor) {
1406 // We have the method which returns a struct/union. Must also generate
1407 // call to objc_msgSend_stret and hang both varieties on a conditional
1408 // expression which dictate which one to envoke depending on size of
1409 // method's return type.
1410
1411 // Create a reference to the objc_msgSend_stret() declaration.
1412 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1413 SourceLocation());
1414 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1415 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1416 SourceLocation());
1417 // Now do the "normal" pointer to function cast.
1418 castType = Context->getFunctionType(returnType,
1419 &ArgTypes[0], ArgTypes.size(),
1420 Exp->getMethodDecl()->isVariadic());
1421 castType = Context->getPointerType(castType);
1422 cast = new CastExpr(castType, cast, SourceLocation());
1423
1424 // Don't forget the parens to enforce the proper binding.
1425 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1426
1427 FT = msgSendType->getAsFunctionType();
1428 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1429 FT->getResultType(), SourceLocation());
1430
1431 // Build sizeof(returnType)
1432 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1433 returnType, Context->getSizeType(),
1434 SourceLocation(), SourceLocation());
1435 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1436 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1437 // For X86 it is more complicated and some kind of target specific routine
1438 // is needed to decide what to do.
1439 unsigned IntSize = static_cast<unsigned>(
1440 Context->getTypeSize(Context->IntTy, SourceLocation()));
1441
1442 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1443 Context->IntTy,
1444 SourceLocation());
1445 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1446 BinaryOperator::LE,
1447 Context->IntTy,
1448 SourceLocation());
1449 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1450 ConditionalOperator *CondExpr =
1451 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1452 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1453 // Now do the actual rewrite.
1454 Rewrite.ReplaceStmt(Exp, PE);
1455 delete Exp;
1456 return PE;
1457 }
Steve Naroff934f2762007-10-24 22:48:43 +00001458 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001459 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001460
Chris Lattnere64b7772007-10-24 16:57:36 +00001461 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001462 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001463}
1464
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001465/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1466/// an objective-c class with ivars.
1467void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1468 std::string &Result) {
1469 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1470 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001471 // Do not synthesize more than once.
1472 if (ObjcSynthesizedStructs.count(CDecl))
1473 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001474 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001475 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001476 SourceLocation LocStart = CDecl->getLocStart();
1477 SourceLocation LocEnd = CDecl->getLocEnd();
1478
1479 const char *startBuf = SM->getCharacterData(LocStart);
1480 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001481 // If no ivars and no root or if its root, directly or indirectly,
1482 // have no ivars (thus not synthesized) then no need to synthesize this class.
1483 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001484 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1485 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1486 Result.c_str(), Result.size());
1487 return;
1488 }
1489
1490 // FIXME: This has potential of causing problem. If
1491 // SynthesizeObjcInternalStruct is ever called recursively.
1492 Result += "\nstruct ";
1493 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001494
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001495 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001496 const char *cursor = strchr(startBuf, '{');
1497 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001498 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001499
1500 // rewrite the original header *without* disturbing the '{'
1501 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1502 Result.c_str(), Result.size());
1503 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1504 Result = "\n struct ";
1505 Result += RCDecl->getName();
1506 Result += " _";
1507 Result += RCDecl->getName();
1508 Result += ";\n";
1509
1510 // insert the super class structure definition.
1511 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1512 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1513 }
1514 cursor++; // past '{'
1515
1516 // Now comment out any visibility specifiers.
1517 while (cursor < endBuf) {
1518 if (*cursor == '@') {
1519 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001520 // Skip whitespace.
1521 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1522 /*scan*/;
1523
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001524 // FIXME: presence of @public, etc. inside comment results in
1525 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001526 if (!strncmp(cursor, "public", strlen("public")) ||
1527 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001528 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001529 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001530 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001531 // FIXME: If there are cases where '<' is used in ivar declaration part
1532 // of user code, then scan the ivar list and use needToScanForQualifiers
1533 // for type checking.
1534 else if (*cursor == '<') {
1535 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1536 Rewrite.InsertText(atLoc, "/* ", 3);
1537 cursor = strchr(cursor, '>');
1538 cursor++;
1539 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1540 Rewrite.InsertText(atLoc, " */", 3);
1541 }
Steve Narofffea763e82007-11-14 19:25:57 +00001542 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001543 }
Steve Narofffea763e82007-11-14 19:25:57 +00001544 // Don't forget to add a ';'!!
1545 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1546 } else { // we don't have any instance variables - insert super struct.
1547 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1548 Result += " {\n struct ";
1549 Result += RCDecl->getName();
1550 Result += " _";
1551 Result += RCDecl->getName();
1552 Result += ";\n};\n";
1553 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1554 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001555 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001556 // Mark this struct as having been generated.
1557 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001558 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001559}
1560
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001561// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1562/// class methods.
Steve Naroff0416fb92007-11-11 17:19:15 +00001563void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001564 int NumMethods,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001565 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001566 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001567 const char *ClassName,
1568 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001569 static bool objc_impl_method = false;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001570 if (NumMethods > 0 && !objc_impl_method) {
1571 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001572 SEL _cmd;
1573 char *method_types;
1574 void *_imp;
1575 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001576 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001577 Result += "\nstruct _objc_method {\n";
1578 Result += "\tSEL _cmd;\n";
1579 Result += "\tchar *method_types;\n";
1580 Result += "\tvoid *_imp;\n";
1581 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001582
1583 /* struct _objc_method_list {
1584 struct _objc_method_list *next_method;
1585 int method_count;
1586 struct _objc_method method_list[];
1587 }
1588 */
1589 Result += "\nstruct _objc_method_list {\n";
1590 Result += "\tstruct _objc_method_list *next_method;\n";
1591 Result += "\tint method_count;\n";
1592 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001593 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001594 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001595 // Build _objc_method_list for class's methods if needed
1596 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001597 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattner158ecb92007-10-25 17:07:24 +00001598 Result += prefix;
1599 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1600 Result += "_METHODS_";
1601 Result += ClassName;
1602 Result += " __attribute__ ((section (\"__OBJC, __";
1603 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001604 Result += "_meth\")))= ";
1605 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1606
1607 Result += "\t,{{(SEL)\"";
1608 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001609 std::string MethodTypeString;
1610 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1611 Result += "\", \"";
1612 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001613 Result += "\", ";
1614 Result += MethodInternalNames[Methods[0]];
1615 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001616 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001617 Result += "\t ,{(SEL)\"";
1618 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001619 std::string MethodTypeString;
1620 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1621 Result += "\", \"";
1622 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001623 Result += "\", ";
1624 Result += MethodInternalNames[Methods[i]];
1625 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001626 }
1627 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001628 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001629}
1630
1631/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1632void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1633 int NumProtocols,
1634 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001635 const char *ClassName,
1636 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001637 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001638 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001639 for (int i = 0; i < NumProtocols; i++) {
1640 ObjcProtocolDecl *PDecl = Protocols[i];
1641 // Output struct protocol_methods holder of method selector and type.
1642 if (!objc_protocol_methods &&
1643 (PDecl->getNumInstanceMethods() > 0
1644 || PDecl->getNumClassMethods() > 0)) {
1645 /* struct protocol_methods {
1646 SEL _cmd;
1647 char *method_types;
1648 }
1649 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001650 Result += "\nstruct protocol_methods {\n";
1651 Result += "\tSEL _cmd;\n";
1652 Result += "\tchar *method_types;\n";
1653 Result += "};\n";
1654
1655 /* struct _objc_protocol_method_list {
1656 int protocol_method_count;
1657 struct protocol_methods protocols[];
1658 }
1659 */
1660 Result += "\nstruct _objc_protocol_method_list {\n";
1661 Result += "\tint protocol_method_count;\n";
1662 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001663 objc_protocol_methods = true;
1664 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001665
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001666 // Output instance methods declared in this protocol.
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001667 int NumMethods = PDecl->getNumInstanceMethods();
1668 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001669 Result += "\nstatic struct _objc_protocol_method_list "
1670 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1671 Result += PDecl->getName();
1672 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1673 "{\n\t" + utostr(NumMethods) + "\n";
1674
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001675 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001676 Result += "\t,{{(SEL)\"";
1677 Result += Methods[0]->getSelector().getName().c_str();
1678 Result += "\", \"\"}\n";
1679
1680 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001681 Result += "\t ,{(SEL)\"";
1682 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001683 std::string MethodTypeString;
1684 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1685 Result += "\", \"";
1686 Result += MethodTypeString;
1687 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001688 }
1689 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001690 }
1691
1692 // Output class methods declared in this protocol.
1693 NumMethods = PDecl->getNumClassMethods();
1694 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001695 Result += "\nstatic struct _objc_protocol_method_list "
1696 "_OBJC_PROTOCOL_CLASS_METHODS_";
1697 Result += PDecl->getName();
1698 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1699 "{\n\t";
1700 Result += utostr(NumMethods);
1701 Result += "\n";
1702
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001703 ObjcMethodDecl **Methods = PDecl->getClassMethods();
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 // Output:
1720 /* struct _objc_protocol {
1721 // Objective-C 1.0 extensions
1722 struct _objc_protocol_extension *isa;
1723 char *protocol_name;
1724 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001725 struct _objc_protocol_method_list *instance_methods;
1726 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001727 };
1728 */
1729 static bool objc_protocol = false;
1730 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001731 Result += "\nstruct _objc_protocol {\n";
1732 Result += "\tstruct _objc_protocol_extension *isa;\n";
1733 Result += "\tchar *protocol_name;\n";
1734 Result += "\tstruct _objc_protocol **protocol_list;\n";
1735 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1736 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1737 Result += "};\n";
1738
1739 /* struct _objc_protocol_list {
1740 struct _objc_protocol_list *next;
1741 int protocol_count;
1742 struct _objc_protocol *class_protocols[];
1743 }
1744 */
1745 Result += "\nstruct _objc_protocol_list {\n";
1746 Result += "\tstruct _objc_protocol_list *next;\n";
1747 Result += "\tint protocol_count;\n";
1748 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1749 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001750 objc_protocol = true;
1751 }
1752
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001753 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1754 Result += PDecl->getName();
1755 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1756 "{\n\t0, \"";
1757 Result += PDecl->getName();
1758 Result += "\", 0, ";
1759 if (PDecl->getInstanceMethods() > 0) {
1760 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1761 Result += PDecl->getName();
1762 Result += ", ";
1763 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001764 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001765 Result += "0, ";
1766 if (PDecl->getClassMethods() > 0) {
1767 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1768 Result += PDecl->getName();
1769 Result += "\n";
1770 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001771 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001772 Result += "0\n";
1773 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001774 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001775 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001776 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1777 Result += prefix;
1778 Result += "_PROTOCOLS_";
1779 Result += ClassName;
1780 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1781 "{\n\t0, ";
1782 Result += utostr(NumProtocols);
1783 Result += "\n";
1784
1785 Result += "\t,{&_OBJC_PROTOCOL_";
1786 Result += Protocols[0]->getName();
1787 Result += " \n";
1788
1789 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001790 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001791 Result += "\t ,&_OBJC_PROTOCOL_";
1792 Result += PDecl->getName();
1793 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001794 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001795 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001796 }
1797}
1798
1799/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1800/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001801void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1802 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001803 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1804 // Find category declaration for this implementation.
1805 ObjcCategoryDecl *CDecl;
1806 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1807 CDecl = CDecl->getNextClassCategory())
1808 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1809 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001810
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001811 char *FullCategoryName = (char*)alloca(
1812 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1813 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1814
1815 // Build _objc_method_list for class's instance methods if needed
1816 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1817 IDecl->getNumInstanceMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001818 true,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001819 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001820
1821 // Build _objc_method_list for class's class methods if needed
1822 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1823 IDecl->getNumClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001824 false,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001825 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001826
1827 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001828 // Null CDecl is case of a category implementation with no category interface
1829 if (CDecl)
1830 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1831 CDecl->getNumReferencedProtocols(),
1832 "CATEGORY",
1833 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001834
1835 /* struct _objc_category {
1836 char *category_name;
1837 char *class_name;
1838 struct _objc_method_list *instance_methods;
1839 struct _objc_method_list *class_methods;
1840 struct _objc_protocol_list *protocols;
1841 // Objective-C 1.0 extensions
1842 uint32_t size; // sizeof (struct _objc_category)
1843 struct _objc_property_list *instance_properties; // category's own
1844 // @property decl.
1845 };
1846 */
1847
1848 static bool objc_category = false;
1849 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001850 Result += "\nstruct _objc_category {\n";
1851 Result += "\tchar *category_name;\n";
1852 Result += "\tchar *class_name;\n";
1853 Result += "\tstruct _objc_method_list *instance_methods;\n";
1854 Result += "\tstruct _objc_method_list *class_methods;\n";
1855 Result += "\tstruct _objc_protocol_list *protocols;\n";
1856 Result += "\tunsigned int size;\n";
1857 Result += "\tstruct _objc_property_list *instance_properties;\n";
1858 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001859 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001860 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001861 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
1862 Result += FullCategoryName;
1863 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
1864 Result += IDecl->getName();
1865 Result += "\"\n\t, \"";
1866 Result += ClassDecl->getName();
1867 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001868
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001869 if (IDecl->getNumInstanceMethods() > 0) {
1870 Result += "\t, (struct _objc_method_list *)"
1871 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
1872 Result += FullCategoryName;
1873 Result += "\n";
1874 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001875 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001876 Result += "\t, 0\n";
1877 if (IDecl->getNumClassMethods() > 0) {
1878 Result += "\t, (struct _objc_method_list *)"
1879 "&_OBJC_CATEGORY_CLASS_METHODS_";
1880 Result += FullCategoryName;
1881 Result += "\n";
1882 }
1883 else
1884 Result += "\t, 0\n";
1885
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00001886 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001887 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
1888 Result += FullCategoryName;
1889 Result += "\n";
1890 }
1891 else
1892 Result += "\t, 0\n";
1893 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001894}
1895
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001896/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
1897/// ivar offset.
1898void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
1899 ObjcIvarDecl *ivar,
1900 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001901 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001902 Result += IDecl->getName();
1903 Result += ", ";
1904 Result += ivar->getName();
1905 Result += ")";
1906}
1907
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001908//===----------------------------------------------------------------------===//
1909// Meta Data Emission
1910//===----------------------------------------------------------------------===//
1911
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001912void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
1913 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001914 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
1915
1916 // Build _objc_ivar_list metadata for classes ivars if needed
1917 int NumIvars = IDecl->getImplDeclNumIvars() > 0
1918 ? IDecl->getImplDeclNumIvars()
Steve Naroff03300712007-11-12 13:56:41 +00001919 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00001920 // Explictly declared @interface's are already synthesized.
1921 if (CDecl->ImplicitInterfaceDecl()) {
1922 // FIXME: Implementation of a class with no @interface (legacy) doese not
1923 // produce correct synthesis as yet.
1924 SynthesizeObjcInternalStruct(CDecl, Result);
1925 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00001926
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001927 if (NumIvars > 0) {
1928 static bool objc_ivar = false;
1929 if (!objc_ivar) {
1930 /* struct _objc_ivar {
1931 char *ivar_name;
1932 char *ivar_type;
1933 int ivar_offset;
1934 };
1935 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001936 Result += "\nstruct _objc_ivar {\n";
1937 Result += "\tchar *ivar_name;\n";
1938 Result += "\tchar *ivar_type;\n";
1939 Result += "\tint ivar_offset;\n";
1940 Result += "};\n";
1941
1942 /* struct _objc_ivar_list {
1943 int ivar_count;
1944 struct _objc_ivar ivar_list[];
1945 };
1946 */
1947 Result += "\nstruct _objc_ivar_list {\n";
1948 Result += "\tint ivar_count;\n";
1949 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001950 objc_ivar = true;
1951 }
1952
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001953 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
1954 Result += IDecl->getName();
1955 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
1956 "{\n\t";
1957 Result += utostr(NumIvars);
1958 Result += "\n";
1959
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001960 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
1961 ? IDecl->getImplDeclIVars()
Steve Naroff03300712007-11-12 13:56:41 +00001962 : CDecl->getInstanceVariables();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001963 Result += "\t,{{\"";
1964 Result += Ivars[0]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001965 Result += "\", \"";
1966 std::string StrEncoding;
1967 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
1968 Result += StrEncoding;
1969 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001970 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
1971 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001972 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001973 Result += "\t ,{\"";
1974 Result += Ivars[i]->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00001975 Result += "\", \"";
1976 std::string StrEncoding;
1977 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
1978 Result += StrEncoding;
1979 Result += "\", ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001980 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
1981 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001982 }
1983
1984 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001985 }
1986
1987 // Build _objc_method_list for class's instance methods if needed
1988 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1989 IDecl->getNumInstanceMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001990 true,
1991 "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001992
1993 // Build _objc_method_list for class's class methods if needed
1994 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001995 IDecl->getNumClassMethods(),
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001996 false,
1997 "", IDecl->getName(), Result);
1998
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001999 // Protocols referenced in class declaration?
2000 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2001 CDecl->getNumIntfRefProtocols(),
2002 "CLASS",
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002003 CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002004
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002005
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002006 // Declaration of class/meta-class metadata
2007 /* struct _objc_class {
2008 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002009 const char *super_class_name;
2010 char *name;
2011 long version;
2012 long info;
2013 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002014 struct _objc_ivar_list *ivars;
2015 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002016 struct objc_cache *cache;
2017 struct objc_protocol_list *protocols;
2018 const char *ivar_layout;
2019 struct _objc_class_ext *ext;
2020 };
2021 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002022 static bool objc_class = false;
2023 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002024 Result += "\nstruct _objc_class {\n";
2025 Result += "\tstruct _objc_class *isa;\n";
2026 Result += "\tconst char *super_class_name;\n";
2027 Result += "\tchar *name;\n";
2028 Result += "\tlong version;\n";
2029 Result += "\tlong info;\n";
2030 Result += "\tlong instance_size;\n";
2031 Result += "\tstruct _objc_ivar_list *ivars;\n";
2032 Result += "\tstruct _objc_method_list *methods;\n";
2033 Result += "\tstruct objc_cache *cache;\n";
2034 Result += "\tstruct _objc_protocol_list *protocols;\n";
2035 Result += "\tconst char *ivar_layout;\n";
2036 Result += "\tstruct _objc_class_ext *ext;\n";
2037 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002038 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002039 }
2040
2041 // Meta-class metadata generation.
2042 ObjcInterfaceDecl *RootClass = 0;
2043 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2044 while (SuperClass) {
2045 RootClass = SuperClass;
2046 SuperClass = SuperClass->getSuperClass();
2047 }
2048 SuperClass = CDecl->getSuperClass();
2049
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002050 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2051 Result += CDecl->getName();
2052 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2053 "{\n\t(struct _objc_class *)\"";
2054 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2055 Result += "\"";
2056
2057 if (SuperClass) {
2058 Result += ", \"";
2059 Result += SuperClass->getName();
2060 Result += "\", \"";
2061 Result += CDecl->getName();
2062 Result += "\"";
2063 }
2064 else {
2065 Result += ", 0, \"";
2066 Result += CDecl->getName();
2067 Result += "\"";
2068 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002069 // TODO: 'ivars' field for root class is currently set to 0.
2070 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002071 Result += ", 0,2, sizeof(struct _objc_class), 0";
2072 if (CDecl->getNumClassMethods() > 0) {
2073 Result += "\n\t, &_OBJC_CLASS_METHODS_";
2074 Result += CDecl->getName();
2075 Result += "\n";
2076 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002077 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002078 Result += ", 0\n";
2079 if (CDecl->getNumIntfRefProtocols() > 0) {
2080 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2081 Result += CDecl->getName();
2082 Result += ",0,0\n";
2083 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002084 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002085 Result += "\t,0,0,0,0\n";
2086 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002087
2088 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002089 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2090 Result += CDecl->getName();
2091 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2092 "{\n\t&_OBJC_METACLASS_";
2093 Result += CDecl->getName();
2094 if (SuperClass) {
2095 Result += ", \"";
2096 Result += SuperClass->getName();
2097 Result += "\", \"";
2098 Result += CDecl->getName();
2099 Result += "\"";
2100 }
2101 else {
2102 Result += ", 0, \"";
2103 Result += CDecl->getName();
2104 Result += "\"";
2105 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002106 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002107 Result += ", 0,1";
2108 if (!ObjcSynthesizedStructs.count(CDecl))
2109 Result += ",0";
2110 else {
2111 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002112 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002113 Result += CDecl->getName();
2114 Result += ")";
2115 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002116 if (NumIvars > 0) {
2117 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2118 Result += CDecl->getName();
2119 Result += "\n\t";
2120 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002121 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002122 Result += ",0";
2123 if (IDecl->getNumInstanceMethods() > 0) {
2124 Result += ", &_OBJC_INSTANCE_METHODS_";
2125 Result += CDecl->getName();
2126 Result += ", 0\n\t";
2127 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002128 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002129 Result += ",0,0";
2130 if (CDecl->getNumIntfRefProtocols() > 0) {
2131 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2132 Result += CDecl->getName();
2133 Result += ", 0,0\n";
2134 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002135 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002136 Result += ",0,0,0\n";
2137 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002138}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002139
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002140/// RewriteImplementations - This routine rewrites all method implementations
2141/// and emits meta-data.
2142
2143void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002144 int ClsDefCount = ClassImplementation.size();
2145 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002146
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002147 if (ClsDefCount == 0 && CatDefCount == 0)
2148 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002149 // Rewrite implemented methods
2150 for (int i = 0; i < ClsDefCount; i++)
2151 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002152
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002153 for (int i = 0; i < CatDefCount; i++)
2154 RewriteImplementationDecl(CategoryImplementation[i]);
2155
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002156 // This is needed for use of offsetof
2157 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002158
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002159 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002160 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002161 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002162
2163 // For each implemented category, write out all its meta data.
2164 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002165 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002166
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002167 // Write objc_symtab metadata
2168 /*
2169 struct _objc_symtab
2170 {
2171 long sel_ref_cnt;
2172 SEL *refs;
2173 short cls_def_cnt;
2174 short cat_def_cnt;
2175 void *defs[cls_def_cnt + cat_def_cnt];
2176 };
2177 */
2178
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002179 Result += "\nstruct _objc_symtab {\n";
2180 Result += "\tlong sel_ref_cnt;\n";
2181 Result += "\tSEL *refs;\n";
2182 Result += "\tshort cls_def_cnt;\n";
2183 Result += "\tshort cat_def_cnt;\n";
2184 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2185 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002186
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002187 Result += "static struct _objc_symtab "
2188 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2189 Result += "\t0, 0, " + utostr(ClsDefCount)
2190 + ", " + utostr(CatDefCount) + "\n";
2191 for (int i = 0; i < ClsDefCount; i++) {
2192 Result += "\t,&_OBJC_CLASS_";
2193 Result += ClassImplementation[i]->getName();
2194 Result += "\n";
2195 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002196
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002197 for (int i = 0; i < CatDefCount; i++) {
2198 Result += "\t,&_OBJC_CATEGORY_";
2199 Result += CategoryImplementation[i]->getClassInterface()->getName();
2200 Result += "_";
2201 Result += CategoryImplementation[i]->getName();
2202 Result += "\n";
2203 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002204
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002205 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002206
2207 // Write objc_module metadata
2208
2209 /*
2210 struct _objc_module {
2211 long version;
2212 long size;
2213 const char *name;
2214 struct _objc_symtab *symtab;
2215 }
2216 */
2217
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002218 Result += "\nstruct _objc_module {\n";
2219 Result += "\tlong version;\n";
2220 Result += "\tlong size;\n";
2221 Result += "\tconst char *name;\n";
2222 Result += "\tstruct _objc_symtab *symtab;\n";
2223 Result += "};\n\n";
2224 Result += "static struct _objc_module "
2225 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002226 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2227 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002228 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002229
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002230}
Chris Lattner311ff022007-10-16 22:36:42 +00002231