blob: cb839ba2bda682042c82b6c192f55d2864f97017 [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 Naroff9bcb5fc2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000054
Steve Naroffbeaf2992007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000058
Steve Naroff874e2322007-11-15 10:28:18 +000059 // Needed for super.
60 ObjcMethodDecl *CurMethodDecl;
61 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 public:
Chris Lattner01c57482007-10-17 22:35:30 +000065 void Initialize(ASTContext &context, unsigned mainFileID) {
66 Context = &context;
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffebf2b562007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattner26de4652007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
84 MainFileID = mainFileID;
85 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffe3abbf52007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff3cadd032007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000094 "#ifndef OBJC_SUPER\n"
95 "struct objc_super { struct objc_object *o; "
96 "struct objc_object *superClass; };\n"
97 "#define OBJC_SUPER\n"
98 "#endif\n"
99 "#ifndef _REWRITER_typedef_Protocol\n"
100 "typedef struct objc_object Protocol;\n"
101 "#define _REWRITER_typedef_Protocol\n"
102 "#endif\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000107 "extern struct objc_object *objc_msgSend_stret"
108 "(struct objc_object *, struct objc_selector *, ...);\n"
109 "extern struct objc_object *objc_msgSendSuper_stret"
110 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroff21867b12007-11-07 18:43:40 +0000117 "extern void objc_exception_throw(struct objc_object *);\n"
118 "extern void objc_exception_try_enter(void *);\n"
119 "extern void objc_exception_try_exit(void *);\n"
120 "extern struct objc_object *objc_exception_extract(void *);\n"
121 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian2c1e9c72007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000125
Steve Naroffab972d32007-11-04 22:37:50 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
127 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000128 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000129
Chris Lattnerf04da132007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000139 void RewriteTabs();
140 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroffbef11852007-10-26 20:53:56 +0000141 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000143 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff423cb562007-10-30 13:30:57 +0000144 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000145 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000146 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000147 void RewriteMethodDeclaration(ObjcMethodDecl *Method);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000148 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahaniane66894c2007-12-11 19:56:36 +0000150 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000152 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
153 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000163 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
164 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
165 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff2bd03922007-11-07 15:32:26 +0000166 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000179
Chris Lattnerf04da132007-10-24 17:06:59 +0000180 // Metadata emission.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000181 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
182 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000183
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000184 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
185 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000186
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000187 typedef ObjcCategoryImplDecl::instmeth_iterator instmeth_iterator;
188 void RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
189 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000190 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000191 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000192 const char *ClassName,
193 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000194
195 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
196 int NumProtocols,
197 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000198 const char *ClassName,
199 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000200 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
201 std::string &Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000202 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
203 ObjcIvarDecl *ivar,
204 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000205 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000206 };
207}
208
Chris Lattnere365c502007-11-30 22:25:36 +0000209ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
210 return new RewriteTest(Diags);
211}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000212
Chris Lattnerf04da132007-10-24 17:06:59 +0000213//===----------------------------------------------------------------------===//
214// Top Level Driver Code
215//===----------------------------------------------------------------------===//
216
Chris Lattner8a12c272007-10-11 18:38:32 +0000217void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000218 // Two cases: either the decl could be in the main file, or it could be in a
219 // #included file. If the former, rewrite it now. If the later, check to see
220 // if we rewrote the #include/#import.
221 SourceLocation Loc = D->getLocation();
222 Loc = SM->getLogicalLoc(Loc);
223
224 // If this is for a builtin, ignore it.
225 if (Loc.isInvalid()) return;
226
Steve Naroffebf2b562007-10-23 23:50:29 +0000227 // Look for built-in declarations that we need to refer during the rewrite.
228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000229 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000230 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
231 // declared in <Foundation/NSString.h>
232 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
233 ConstantStringClassReference = FVD;
234 return;
235 }
Steve Naroffbef11852007-10-26 20:53:56 +0000236 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
237 RewriteInterfaceDecl(MD);
Steve Naroff423cb562007-10-30 13:30:57 +0000238 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
239 RewriteCategoryDecl(CD);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000240 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
241 RewriteProtocolDecl(PD);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000242 } else if (ObjcForwardProtocolDecl *FP =
243 dyn_cast<ObjcForwardProtocolDecl>(D)){
244 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000245 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000246 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000247 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
248 return HandleDeclInMainFile(D);
249
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 // Otherwise, see if there is a #import in the main file that should be
251 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000252 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000253}
254
Chris Lattnerf04da132007-10-24 17:06:59 +0000255/// HandleDeclInMainFile - This is called for each top-level decl defined in the
256/// main file of the input.
257void RewriteTest::HandleDeclInMainFile(Decl *D) {
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
259 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000260 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000261
262 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000263 if (Stmt *Body = MD->getBody()) {
264 //Body->dump();
265 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000266 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000267 CurMethodDecl = 0;
268 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000269 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000270 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
271 ClassImplementation.push_back(CI);
272 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
273 CategoryImplementation.push_back(CI);
274 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
275 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000276 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +0000277 RewriteObjcQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000278 if (VD->getInit())
279 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
280 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000281 // Nothing yet.
282}
283
284RewriteTest::~RewriteTest() {
285 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000286
287 // Rewrite tabs if we care.
288 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000289
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000290 // Rewrite Objective-c meta data*
291 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000292 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000293
Chris Lattnerf04da132007-10-24 17:06:59 +0000294 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
295 // we are done.
296 if (const RewriteBuffer *RewriteBuf =
297 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000298 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000299 std::string S(RewriteBuf->begin(), RewriteBuf->end());
300 printf("%s\n", S.c_str());
301 } else {
302 printf("No changes\n");
303 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000304 // Emit metadata.
305 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306}
307
Chris Lattnerf04da132007-10-24 17:06:59 +0000308//===----------------------------------------------------------------------===//
309// Syntactic (non-AST) Rewriting Code
310//===----------------------------------------------------------------------===//
311
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000312void RewriteTest::RewriteInclude(SourceLocation Loc) {
313 // Rip up the #include stack to the main file.
314 SourceLocation IncLoc = Loc, NextLoc = Loc;
315 do {
316 IncLoc = Loc;
317 Loc = SM->getLogicalLoc(NextLoc);
318 NextLoc = SM->getIncludeLoc(Loc);
319 } while (!NextLoc.isInvalid());
320
321 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
322 // IncLoc indicates the header that was included if it is useful.
323 IncLoc = SM->getLogicalLoc(IncLoc);
324 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
325 Loc == LastIncLoc)
326 return;
327 LastIncLoc = Loc;
328
329 unsigned IncCol = SM->getColumnNumber(Loc);
330 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
331
332 // Replace the #import with #include.
333 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
334}
335
Chris Lattnerf04da132007-10-24 17:06:59 +0000336void RewriteTest::RewriteTabs() {
337 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
338 const char *MainBufStart = MainBuf.first;
339 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000340
Chris Lattnerf04da132007-10-24 17:06:59 +0000341 // Loop over the whole file, looking for tabs.
342 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
343 if (*BufPtr != '\t')
344 continue;
345
346 // Okay, we found a tab. This tab will turn into at least one character,
347 // but it depends on which 'virtual column' it is in. Compute that now.
348 unsigned VCol = 0;
349 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
350 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
351 ++VCol;
352
353 // Okay, now that we know the virtual column, we know how many spaces to
354 // insert. We assume 8-character tab-stops.
355 unsigned Spaces = 8-(VCol & 7);
356
357 // Get the location of the tab.
358 SourceLocation TabLoc =
359 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
360
361 // Rewrite the single tab character into a sequence of spaces.
362 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
363 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000364}
365
366
Chris Lattnerf04da132007-10-24 17:06:59 +0000367void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
368 int numDecls = ClassDecl->getNumForwardDecls();
369 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
370
371 // Get the start location and compute the semi location.
372 SourceLocation startLoc = ClassDecl->getLocation();
373 const char *startBuf = SM->getCharacterData(startLoc);
374 const char *semiPtr = strchr(startBuf, ';');
375
376 // Translate to typedef's that forward reference structs with the same name
377 // as the class. As a convenience, we include the original declaration
378 // as a comment.
379 std::string typedefString;
380 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000381 typedefString.append(startBuf, semiPtr-startBuf+1);
382 typedefString += "\n";
383 for (int i = 0; i < numDecls; i++) {
384 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000385 typedefString += "#ifndef _REWRITER_typedef_";
386 typedefString += ForwardDecl->getName();
387 typedefString += "\n";
388 typedefString += "#define _REWRITER_typedef_";
389 typedefString += ForwardDecl->getName();
390 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000391 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000392 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000393 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000394 }
395
396 // Replace the @class with typedefs corresponding to the classes.
397 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
398 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000399}
400
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000401void RewriteTest::RewriteMethodDeclaration(ObjcMethodDecl *Method) {
402 SourceLocation LocStart = Method->getLocStart();
403 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000404
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000405 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
406 Rewrite.InsertText(LocStart, "/* ", 3);
407 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
408 } else {
409 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000410 }
411}
412
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000413void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
414{
415 for (int i = 0; i < nProperties; i++) {
416 ObjcPropertyDecl *Property = Properties[i];
417 SourceLocation Loc = Property->getLocation();
418
419 Rewrite.ReplaceText(Loc, 0, "// ", 3);
420
421 // FIXME: handle properties that are declared across multiple lines.
422 }
423}
424
Steve Naroff423cb562007-10-30 13:30:57 +0000425void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
426 SourceLocation LocStart = CatDecl->getLocStart();
427
428 // FIXME: handle category headers that are declared across multiple lines.
429 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
430
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000431 for (ObjcCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
432 E = CatDecl->instmeth_end(); I != E; ++I)
433 RewriteMethodDeclaration(*I);
434 for (ObjcCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
435 E = CatDecl->classmeth_end(); I != E; ++I)
436 RewriteMethodDeclaration(*I);
437
Steve Naroff423cb562007-10-30 13:30:57 +0000438 // Lastly, comment out the @end.
439 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
440}
441
Steve Naroff752d6ef2007-10-30 16:42:30 +0000442void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000443 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000444
Steve Naroff752d6ef2007-10-30 16:42:30 +0000445 SourceLocation LocStart = PDecl->getLocStart();
446
447 // FIXME: handle protocol headers that are declared across multiple lines.
448 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
449
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000450 for (ObjcProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
451 E = PDecl->instmeth_end(); I != E; ++I)
452 RewriteMethodDeclaration(*I);
453 for (ObjcProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
454 E = PDecl->classmeth_end(); I != E; ++I)
455 RewriteMethodDeclaration(*I);
456
Steve Naroff752d6ef2007-10-30 16:42:30 +0000457 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000458 SourceLocation LocEnd = PDecl->getAtEndLoc();
459 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000460
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000461 // Must comment out @optional/@required
462 const char *startBuf = SM->getCharacterData(LocStart);
463 const char *endBuf = SM->getCharacterData(LocEnd);
464 for (const char *p = startBuf; p < endBuf; p++) {
465 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
466 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000467 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000468 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
469 CommentedOptional.c_str(), CommentedOptional.size());
470
471 }
472 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
473 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000474 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000475 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
476 CommentedRequired.c_str(), CommentedRequired.size());
477
478 }
479 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000480}
481
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000482void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
483 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000484 if (LocStart.isInvalid())
485 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000486 // FIXME: handle forward protocol that are declared across multiple lines.
487 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
488}
489
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000490void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
491 std::string &ResultStr) {
492 ResultStr += "\nstatic ";
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +0000493 if (OMD->getResultType()->isObjcQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000494 ResultStr += "id";
495 else
496 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000497 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000498
499 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000500 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000501
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000502 if (OMD->isInstance())
503 NameStr += "_I_";
504 else
505 NameStr += "_C_";
506
507 NameStr += OMD->getClassInterface()->getName();
508 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000509
510 NamedDecl *MethodContext = OMD->getMethodContext();
511 if (ObjcCategoryImplDecl *CID =
512 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000513 NameStr += CID->getName();
514 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000515 }
516 // Append selector names, replacing ':' with '_'
517 const char *selName = OMD->getSelector().getName().c_str();
518 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000519 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000520 else {
521 std::string selString = OMD->getSelector().getName();
522 int len = selString.size();
523 for (int i = 0; i < len; i++)
524 if (selString[i] == ':')
525 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000526 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000527 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000528 // Remember this name for metadata emission
529 MethodInternalNames[OMD] = NameStr;
530 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000531
532 // Rewrite arguments
533 ResultStr += "(";
534
535 // invisible arguments
536 if (OMD->isInstance()) {
537 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
538 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000539 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
540 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000541 ResultStr += selfTy.getAsString();
542 }
543 else
544 ResultStr += Context->getObjcIdType().getAsString();
545
546 ResultStr += " self, ";
547 ResultStr += Context->getObjcSelType().getAsString();
548 ResultStr += " _cmd";
549
550 // Method arguments.
551 for (int i = 0; i < OMD->getNumParams(); i++) {
552 ParmVarDecl *PDecl = OMD->getParamDecl(i);
553 ResultStr += ", ";
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +0000554 if (PDecl->getType()->isObjcQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000555 ResultStr += "id";
556 else
557 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000558 ResultStr += " ";
559 ResultStr += PDecl->getName();
560 }
561 ResultStr += ")";
562
563}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000564void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
565 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
566 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000567
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000568 if (IMD)
569 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
570 else
571 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000572
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000573 for (ObjcCategoryImplDecl::instmeth_iterator
574 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
575 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000576 std::string ResultStr;
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000577 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000578 RewriteObjcMethodDecl(OMD, ResultStr);
579 SourceLocation LocStart = OMD->getLocStart();
580 SourceLocation LocEnd = OMD->getBody()->getLocStart();
581
582 const char *startBuf = SM->getCharacterData(LocStart);
583 const char *endBuf = SM->getCharacterData(LocEnd);
584 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
585 ResultStr.c_str(), ResultStr.size());
586 }
587
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000588 for (ObjcCategoryImplDecl::classmeth_iterator
589 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
590 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000591 std::string ResultStr;
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000592 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000593 RewriteObjcMethodDecl(OMD, ResultStr);
594 SourceLocation LocStart = OMD->getLocStart();
595 SourceLocation LocEnd = OMD->getBody()->getLocStart();
596
597 const char *startBuf = SM->getCharacterData(LocStart);
598 const char *endBuf = SM->getCharacterData(LocEnd);
599 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
600 ResultStr.c_str(), ResultStr.size());
601 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000602 if (IMD)
603 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
604 else
605 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000606}
607
Steve Naroffbef11852007-10-26 20:53:56 +0000608void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000609 std::string ResultStr;
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000610 if (!ObjcForwardDecls.count(ClassDecl)) {
611 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000612 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000613 ResultStr += ClassDecl->getName();
614 ResultStr += "\n";
615 ResultStr += "#define _REWRITER_typedef_";
616 ResultStr += ClassDecl->getName();
617 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000618 ResultStr += "typedef struct ";
619 ResultStr += ClassDecl->getName();
620 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000621 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000622 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000623
624 // Mark this typedef as having been generated.
625 ObjcForwardDecls.insert(ClassDecl);
626 }
Steve Narofff908a872007-10-30 02:23:23 +0000627 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
628
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000629 RewriteProperties(ClassDecl->getNumPropertyDecl(),
630 ClassDecl->getPropertyDecl());
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000631 for (ObjcInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
632 E = ClassDecl->instmeth_end(); I != E; ++I)
633 RewriteMethodDeclaration(*I);
634 for (ObjcInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
635 E = ClassDecl->classmeth_end(); I != E; ++I)
636 RewriteMethodDeclaration(*I);
637
Steve Naroff2feac5e2007-10-30 03:43:13 +0000638 // Lastly, comment out the @end.
639 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000640}
641
Steve Naroff7e3411b2007-11-15 02:58:25 +0000642Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
643 ObjcIvarDecl *D = IV->getDecl();
644 if (IV->isFreeIvar()) {
645 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
646 IV->getLocation());
647 Rewrite.ReplaceStmt(IV, Replacement);
648 delete IV;
649 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000650 } else {
651 if (CurMethodDecl) {
652 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
653 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
654 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
655 IdentifierInfo *II = intT->getDecl()->getIdentifier();
656 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
657 II, 0);
658 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
659
660 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
661 // Don't forget the parens to enforce the proper binding.
662 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
663 Rewrite.ReplaceStmt(IV->getBase(), PE);
664 delete IV->getBase();
665 return PE;
666 }
667 }
668 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000669 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000670 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000671}
672
Chris Lattnerf04da132007-10-24 17:06:59 +0000673//===----------------------------------------------------------------------===//
674// Function Body / Expression rewriting
675//===----------------------------------------------------------------------===//
676
Steve Narofff3473a72007-11-09 15:20:18 +0000677Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000678 // Otherwise, just rewrite all children.
679 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
680 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000681 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000682 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000683 if (newStmt)
684 *CI = newStmt;
685 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000686
687 // Handle specific things.
688 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
689 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000690
691 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
692 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000693
694 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
695 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000696
697 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
698 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000699
Steve Naroff934f2762007-10-24 22:48:43 +0000700 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
701 // Before we rewrite it, put the original message expression in a comment.
702 SourceLocation startLoc = MessExpr->getLocStart();
703 SourceLocation endLoc = MessExpr->getLocEnd();
704
705 const char *startBuf = SM->getCharacterData(startLoc);
706 const char *endBuf = SM->getCharacterData(endLoc);
707
708 std::string messString;
709 messString += "// ";
710 messString.append(startBuf, endBuf-startBuf+1);
711 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000712
Steve Naroff934f2762007-10-24 22:48:43 +0000713 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
714 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
715 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000716 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000717 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000718 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000719
720 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
721 return RewriteObjcTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000722
723 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
724 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000725
726 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
727 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff874e2322007-11-15 10:28:18 +0000728#if 0
729 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
730 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
731 // Get the new text.
732 std::ostringstream Buf;
733 Replacement->printPretty(Buf);
734 const std::string &Str = Buf.str();
735
736 printf("CAST = %s\n", &Str[0]);
737 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
738 delete S;
739 return Replacement;
740 }
741#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000742 // Return this stmt unmodified.
743 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000744}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000745
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000746Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000747 // Get the start location and compute the semi location.
748 SourceLocation startLoc = S->getLocStart();
749 const char *startBuf = SM->getCharacterData(startLoc);
750
751 assert((*startBuf == '@') && "bogus @try location");
752
753 std::string buf;
754 // declare a new scope with two variables, _stack and _rethrow.
755 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
756 buf += "int buf[18/*32-bit i386*/];\n";
757 buf += "char *pointers[4];} _stack;\n";
758 buf += "id volatile _rethrow = 0;\n";
759 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000760 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000761
762 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
763
764 startLoc = S->getTryBody()->getLocEnd();
765 startBuf = SM->getCharacterData(startLoc);
766
767 assert((*startBuf == '}') && "bogus @try block");
768
769 SourceLocation lastCurlyLoc = startLoc;
770
771 startLoc = startLoc.getFileLocWithOffset(1);
772 buf = " /* @catch begin */ else {\n";
773 buf += " id _caught = objc_exception_extract(&_stack);\n";
774 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000775 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000776 buf += " _rethrow = objc_exception_extract(&_stack);\n";
777 buf += " else { /* @catch continue */";
778
Chris Lattner28d1fe82007-11-08 04:41:51 +0000779 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000780
781 bool sawIdTypedCatch = false;
782 Stmt *lastCatchBody = 0;
783 ObjcAtCatchStmt *catchList = S->getCatchStmts();
784 while (catchList) {
785 Stmt *catchStmt = catchList->getCatchParamStmt();
786
787 if (catchList == S->getCatchStmts())
788 buf = "if ("; // we are generating code for the first catch clause
789 else
790 buf = "else if (";
791 startLoc = catchList->getLocStart();
792 startBuf = SM->getCharacterData(startLoc);
793
794 assert((*startBuf == '@') && "bogus @catch location");
795
796 const char *lParenLoc = strchr(startBuf, '(');
797
798 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
799 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
800 if (t == Context->getObjcIdType()) {
801 buf += "1) { ";
802 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
803 buf.c_str(), buf.size());
804 sawIdTypedCatch = true;
805 } else if (const PointerType *pType = t->getAsPointerType()) {
806 ObjcInterfaceType *cls; // Should be a pointer to a class.
807
808 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
809 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000810 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000811 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000812 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000813 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
814 buf.c_str(), buf.size());
815 }
816 }
817 // Now rewrite the body...
818 lastCatchBody = catchList->getCatchBody();
819 SourceLocation rParenLoc = catchList->getRParenLoc();
820 SourceLocation bodyLoc = lastCatchBody->getLocStart();
821 const char *bodyBuf = SM->getCharacterData(bodyLoc);
822 const char *rParenBuf = SM->getCharacterData(rParenLoc);
823 assert((*rParenBuf == ')') && "bogus @catch paren location");
824 assert((*bodyBuf == '{') && "bogus @catch body location");
825
826 buf = " = _caught;";
827 // Here we replace ") {" with "= _caught;" (which initializes and
828 // declares the @catch parameter).
829 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
830 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000831 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000832 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000833 }
Steve Naroff75730982007-11-07 04:08:17 +0000834 catchList = catchList->getNextCatchStmt();
835 }
836 // Complete the catch list...
837 if (lastCatchBody) {
838 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
839 const char *bodyBuf = SM->getCharacterData(bodyLoc);
840 assert((*bodyBuf == '}') && "bogus @catch body location");
841 bodyLoc = bodyLoc.getFileLocWithOffset(1);
842 buf = " } } /* @catch end */\n";
843
Chris Lattner28d1fe82007-11-08 04:41:51 +0000844 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000845
846 // Set lastCurlyLoc
847 lastCurlyLoc = lastCatchBody->getLocEnd();
848 }
849 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
850 startLoc = finalStmt->getLocStart();
851 startBuf = SM->getCharacterData(startLoc);
852 assert((*startBuf == '@') && "bogus @finally start");
853
854 buf = "/* @finally */";
855 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
856
857 Stmt *body = finalStmt->getFinallyBody();
858 SourceLocation startLoc = body->getLocStart();
859 SourceLocation endLoc = body->getLocEnd();
860 const char *startBuf = SM->getCharacterData(startLoc);
861 const char *endBuf = SM->getCharacterData(endLoc);
862 assert((*startBuf == '{') && "bogus @finally body location");
863 assert((*endBuf == '}') && "bogus @finally body location");
864
865 startLoc = startLoc.getFileLocWithOffset(1);
866 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000867 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000868 endLoc = endLoc.getFileLocWithOffset(-1);
869 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000870 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000871
872 // Set lastCurlyLoc
873 lastCurlyLoc = body->getLocEnd();
874 }
875 // Now emit the final closing curly brace...
876 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
877 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000878 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000879 return 0;
880}
881
882Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
883 return 0;
884}
885
886Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
887 return 0;
888}
889
Steve Naroff2bd03922007-11-07 15:32:26 +0000890// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
891// the throw expression is typically a message expression that's already
892// been rewritten! (which implies the SourceLocation's are invalid).
893Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
894 // Get the start location and compute the semi location.
895 SourceLocation startLoc = S->getLocStart();
896 const char *startBuf = SM->getCharacterData(startLoc);
897
898 assert((*startBuf == '@') && "bogus @throw location");
899
900 std::string buf;
901 /* void objc_exception_throw(id) __attribute__((noreturn)); */
902 buf = "objc_exception_throw(";
903 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
904 const char *semiBuf = strchr(startBuf, ';');
905 assert((*semiBuf == ';') && "@throw: can't find ';'");
906 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
907 buf = ");";
908 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
909 return 0;
910}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000911
Chris Lattnere64b7772007-10-24 16:57:36 +0000912Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000913 // Create a new string expression.
914 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000915 std::string StrEncoding;
916 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
917 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
918 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000919 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000920 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
921 // replacement failed.
Chris Lattner182745a2007-12-02 01:09:57 +0000922 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
923 "rewriter could not replace sub-expression due to macros");
924 SourceRange Range = Exp->getSourceRange();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000925 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattner182745a2007-12-02 01:09:57 +0000926 delete Replacement;
Chris Lattnere365c502007-11-30 22:25:36 +0000927 return Exp;
928 }
929
Chris Lattner07506182007-11-30 22:53:43 +0000930 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000931 delete Exp;
932 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000933}
934
Steve Naroffb42f8412007-11-05 14:50:49 +0000935Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
936 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
937 // Create a call to sel_registerName("selName").
938 llvm::SmallVector<Expr*, 8> SelExprs;
939 QualType argType = Context->getPointerType(Context->CharTy);
940 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
941 Exp->getSelector().getName().size(),
942 false, argType, SourceLocation(),
943 SourceLocation()));
944 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
945 &SelExprs[0], SelExprs.size());
946 Rewrite.ReplaceStmt(Exp, SelExp);
947 delete Exp;
948 return SelExp;
949}
950
Steve Naroff934f2762007-10-24 22:48:43 +0000951CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
952 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000953 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000954 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000955
956 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000957 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000958
959 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000960 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000961 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
962
963 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000964
Steve Naroff934f2762007-10-24 22:48:43 +0000965 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
966}
967
Steve Naroffd5255f52007-11-01 13:24:47 +0000968static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
969 const char *&startRef, const char *&endRef) {
970 while (startBuf < endBuf) {
971 if (*startBuf == '<')
972 startRef = startBuf; // mark the start.
973 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000974 if (startRef && *startRef == '<') {
975 endRef = startBuf; // mark the end.
976 return true;
977 }
978 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000979 }
980 startBuf++;
981 }
982 return false;
983}
984
Fariborz Jahanian61477f72007-12-11 22:50:14 +0000985static void scanToNextArgument(const char *&argRef) {
986 int angle = 0;
987 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
988 if (*argRef == '<')
989 angle++;
990 else if (*argRef == '>')
991 angle--;
992 argRef++;
993 }
994 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
995}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +0000996
Steve Naroffd5255f52007-11-01 13:24:47 +0000997bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000998
Steve Naroffd5255f52007-11-01 13:24:47 +0000999 if (T == Context->getObjcIdType())
1000 return true;
1001
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001002 if (T->isObjcQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001003 return true;
1004
Steve Naroffd5255f52007-11-01 13:24:47 +00001005 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001006 Type *pointeeType = pType->getPointeeType().getTypePtr();
1007 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
1008 return true; // we have "Class <Protocol> *".
1009 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001010 return false;
1011}
1012
Fariborz Jahaniane66894c2007-12-11 19:56:36 +00001013void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001014 SourceLocation Loc;
1015 QualType Type;
1016 const FunctionTypeProto *proto = 0;
1017 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1018 Loc = VD->getLocation();
1019 Type = VD->getType();
1020 }
1021 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1022 Loc = FD->getLocation();
1023 // Check for ObjC 'id' and class types that have been adorned with protocol
1024 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1025 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1026 assert(funcType && "missing function type");
1027 proto = dyn_cast<FunctionTypeProto>(funcType);
1028 if (!proto)
1029 return;
1030 Type = proto->getResultType();
1031 }
1032 else
1033 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001034
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001035 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001036 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001037
1038 const char *endBuf = SM->getCharacterData(Loc);
1039 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001040 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001041 startBuf--; // scan backward (from the decl location) for return type.
1042 const char *startRef = 0, *endRef = 0;
1043 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1044 // Get the locations of the startRef, endRef.
1045 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1046 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1047 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001048 Rewrite.InsertText(LessLoc, "/*", 2);
1049 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001050 }
1051 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001052 if (!proto)
1053 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001054 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001055 const char *startBuf = SM->getCharacterData(Loc);
1056 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001057 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1058 if (needToScanForQualifiers(proto->getArgType(i))) {
1059 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001060
Steve Naroffd5255f52007-11-01 13:24:47 +00001061 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001062 // scan forward (from the decl location) for argument types.
1063 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001064 const char *startRef = 0, *endRef = 0;
1065 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1066 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001067 SourceLocation LessLoc =
1068 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1069 SourceLocation GreaterLoc =
1070 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001071 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001072 Rewrite.InsertText(LessLoc, "/*", 2);
1073 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001074 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001075 startBuf = ++endBuf;
1076 }
1077 else {
1078 while (*startBuf != ')' && *startBuf != ',')
1079 startBuf++; // scan forward (from the decl location) for argument types.
1080 startBuf++;
1081 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001082 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001083}
1084
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001085// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1086void RewriteTest::SynthSelGetUidFunctionDecl() {
1087 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1088 llvm::SmallVector<QualType, 16> ArgTys;
1089 ArgTys.push_back(Context->getPointerType(
1090 Context->CharTy.getQualifiedType(QualType::Const)));
1091 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1092 &ArgTys[0], ArgTys.size(),
1093 false /*isVariadic*/);
1094 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1095 SelGetUidIdent, getFuncType,
1096 FunctionDecl::Extern, false, 0);
1097}
1098
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001099// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1100void RewriteTest::SynthGetProtocolFunctionDecl() {
1101 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1102 llvm::SmallVector<QualType, 16> ArgTys;
1103 ArgTys.push_back(Context->getPointerType(
1104 Context->CharTy.getQualifiedType(QualType::Const)));
1105 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1106 &ArgTys[0], ArgTys.size(),
1107 false /*isVariadic*/);
1108 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1109 SelGetProtoIdent, getFuncType,
1110 FunctionDecl::Extern, false, 0);
1111}
1112
Steve Naroff09b266e2007-10-30 23:14:51 +00001113void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1114 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001115 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001116 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001117 return;
1118 }
Fariborz Jahaniane66894c2007-12-11 19:56:36 +00001119 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001120}
1121
1122// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1123void RewriteTest::SynthMsgSendFunctionDecl() {
1124 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1125 llvm::SmallVector<QualType, 16> ArgTys;
1126 QualType argT = Context->getObjcIdType();
1127 assert(!argT.isNull() && "Can't find 'id' type");
1128 ArgTys.push_back(argT);
1129 argT = Context->getObjcSelType();
1130 assert(!argT.isNull() && "Can't find 'SEL' type");
1131 ArgTys.push_back(argT);
1132 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1133 &ArgTys[0], ArgTys.size(),
1134 true /*isVariadic*/);
1135 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1136 msgSendIdent, msgSendType,
1137 FunctionDecl::Extern, false, 0);
1138}
1139
Steve Naroff874e2322007-11-15 10:28:18 +00001140// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1141void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1142 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1143 llvm::SmallVector<QualType, 16> ArgTys;
1144 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1145 &Context->Idents.get("objc_super"), 0);
1146 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1147 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1148 ArgTys.push_back(argT);
1149 argT = Context->getObjcSelType();
1150 assert(!argT.isNull() && "Can't find 'SEL' type");
1151 ArgTys.push_back(argT);
1152 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1153 &ArgTys[0], ArgTys.size(),
1154 true /*isVariadic*/);
1155 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1156 msgSendIdent, msgSendType,
1157 FunctionDecl::Extern, false, 0);
1158}
1159
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001160// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1161void RewriteTest::SynthMsgSendStretFunctionDecl() {
1162 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1163 llvm::SmallVector<QualType, 16> ArgTys;
1164 QualType argT = Context->getObjcIdType();
1165 assert(!argT.isNull() && "Can't find 'id' type");
1166 ArgTys.push_back(argT);
1167 argT = Context->getObjcSelType();
1168 assert(!argT.isNull() && "Can't find 'SEL' type");
1169 ArgTys.push_back(argT);
1170 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1171 &ArgTys[0], ArgTys.size(),
1172 true /*isVariadic*/);
1173 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1174 msgSendIdent, msgSendType,
1175 FunctionDecl::Extern, false, 0);
1176}
1177
1178// SynthMsgSendSuperStretFunctionDecl -
1179// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1180void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1181 IdentifierInfo *msgSendIdent =
1182 &Context->Idents.get("objc_msgSendSuper_stret");
1183 llvm::SmallVector<QualType, 16> ArgTys;
1184 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1185 &Context->Idents.get("objc_super"), 0);
1186 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1187 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1188 ArgTys.push_back(argT);
1189 argT = Context->getObjcSelType();
1190 assert(!argT.isNull() && "Can't find 'SEL' type");
1191 ArgTys.push_back(argT);
1192 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1193 &ArgTys[0], ArgTys.size(),
1194 true /*isVariadic*/);
1195 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1196 msgSendIdent, msgSendType,
1197 FunctionDecl::Extern, false, 0);
1198}
1199
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001200// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1201void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1202 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1203 llvm::SmallVector<QualType, 16> ArgTys;
1204 QualType argT = Context->getObjcIdType();
1205 assert(!argT.isNull() && "Can't find 'id' type");
1206 ArgTys.push_back(argT);
1207 argT = Context->getObjcSelType();
1208 assert(!argT.isNull() && "Can't find 'SEL' type");
1209 ArgTys.push_back(argT);
1210 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1211 &ArgTys[0], ArgTys.size(),
1212 true /*isVariadic*/);
1213 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1214 msgSendIdent, msgSendType,
1215 FunctionDecl::Extern, false, 0);
1216}
1217
Steve Naroff09b266e2007-10-30 23:14:51 +00001218// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1219void RewriteTest::SynthGetClassFunctionDecl() {
1220 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1221 llvm::SmallVector<QualType, 16> ArgTys;
1222 ArgTys.push_back(Context->getPointerType(
1223 Context->CharTy.getQualifiedType(QualType::Const)));
1224 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1225 &ArgTys[0], ArgTys.size(),
1226 false /*isVariadic*/);
1227 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1228 getClassIdent, getClassType,
1229 FunctionDecl::Extern, false, 0);
1230}
1231
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001232// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1233void RewriteTest::SynthGetMetaClassFunctionDecl() {
1234 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1235 llvm::SmallVector<QualType, 16> ArgTys;
1236 ArgTys.push_back(Context->getPointerType(
1237 Context->CharTy.getQualifiedType(QualType::Const)));
1238 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1239 &ArgTys[0], ArgTys.size(),
1240 false /*isVariadic*/);
1241 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1242 getClassIdent, getClassType,
1243 FunctionDecl::Extern, false, 0);
1244}
1245
Steve Naroff96984642007-11-08 14:30:50 +00001246// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1247void RewriteTest::SynthCFStringFunctionDecl() {
1248 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1249 llvm::SmallVector<QualType, 16> ArgTys;
1250 ArgTys.push_back(Context->getPointerType(
1251 Context->CharTy.getQualifiedType(QualType::Const)));
1252 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1253 &ArgTys[0], ArgTys.size(),
1254 false /*isVariadic*/);
1255 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1256 getClassIdent, getClassType,
1257 FunctionDecl::Extern, false, 0);
1258}
1259
Steve Naroffbeaf2992007-11-03 11:27:19 +00001260Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001261#if 1
1262 // This rewrite is specific to GCC, which has builtin support for CFString.
1263 if (!CFStringFunctionDecl)
1264 SynthCFStringFunctionDecl();
1265 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1266 llvm::SmallVector<Expr*, 8> StrExpr;
1267 StrExpr.push_back(Exp->getString());
1268 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1269 &StrExpr[0], StrExpr.size());
1270 // cast to NSConstantString *
1271 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1272 Rewrite.ReplaceStmt(Exp, cast);
1273 delete Exp;
1274 return cast;
1275#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001276 assert(ConstantStringClassReference && "Can't find constant string reference");
1277 llvm::SmallVector<Expr*, 4> InitExprs;
1278
1279 // Synthesize "(Class)&_NSConstantStringClassReference"
1280 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1281 ConstantStringClassReference->getType(),
1282 SourceLocation());
1283 QualType expType = Context->getPointerType(ClsRef->getType());
1284 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1285 expType, SourceLocation());
1286 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1287 SourceLocation());
1288 InitExprs.push_back(cast); // set the 'isa'.
1289 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1290 unsigned IntSize = static_cast<unsigned>(
1291 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1292 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1293 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1294 Exp->getLocStart());
1295 InitExprs.push_back(len); // set "int numBytes".
1296
1297 // struct NSConstantString
1298 QualType CFConstantStrType = Context->getCFConstantStringType();
1299 // (struct NSConstantString) { <exprs from above> }
1300 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1301 &InitExprs[0], InitExprs.size(),
1302 SourceLocation());
1303 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1304 // struct NSConstantString *
1305 expType = Context->getPointerType(StrRep->getType());
1306 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1307 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001308 // cast to NSConstantString *
1309 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001310 Rewrite.ReplaceStmt(Exp, cast);
1311 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001312 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001313#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001314}
1315
Steve Naroff874e2322007-11-15 10:28:18 +00001316ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001317 // check if we are sending a message to 'super'
1318 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001319 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1320 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1321 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1322 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001323 // is this id<P1..> type?
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001324 if (CE->getType()->isObjcQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001325 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001326 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1327 if (ObjcInterfaceType *IT =
1328 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1329 if (IT->getDecl() ==
1330 CurMethodDecl->getClassInterface()->getSuperClass())
1331 return IT->getDecl();
1332 }
1333 }
1334 }
1335 }
1336 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001337 }
Steve Naroff874e2322007-11-15 10:28:18 +00001338 }
1339 return 0;
1340}
1341
1342// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1343QualType RewriteTest::getSuperStructType() {
1344 if (!SuperStructDecl) {
1345 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1346 &Context->Idents.get("objc_super"), 0);
1347 QualType FieldTypes[2];
1348
1349 // struct objc_object *receiver;
1350 FieldTypes[0] = Context->getObjcIdType();
1351 // struct objc_class *super;
1352 FieldTypes[1] = Context->getObjcClassType();
1353 // Create fields
1354 FieldDecl *FieldDecls[2];
1355
1356 for (unsigned i = 0; i < 2; ++i)
1357 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1358
1359 SuperStructDecl->defineBody(FieldDecls, 4);
1360 }
1361 return Context->getTagDeclType(SuperStructDecl);
1362}
1363
Steve Naroff934f2762007-10-24 22:48:43 +00001364Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001365 if (!SelGetUidFunctionDecl)
1366 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001367 if (!MsgSendFunctionDecl)
1368 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001369 if (!MsgSendSuperFunctionDecl)
1370 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001371 if (!MsgSendStretFunctionDecl)
1372 SynthMsgSendStretFunctionDecl();
1373 if (!MsgSendSuperStretFunctionDecl)
1374 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001375 if (!MsgSendFpretFunctionDecl)
1376 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001377 if (!GetClassFunctionDecl)
1378 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001379 if (!GetMetaClassFunctionDecl)
1380 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001381
Steve Naroff874e2322007-11-15 10:28:18 +00001382 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001383 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1384 // May need to use objc_msgSend_stret() as well.
1385 FunctionDecl *MsgSendStretFlavor = 0;
1386 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1387 QualType resultType = mDecl->getResultType();
1388 if (resultType.getCanonicalType()->isStructureType()
1389 || resultType.getCanonicalType()->isUnionType())
1390 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001391 else if (resultType.getCanonicalType()->isRealFloatingType())
1392 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001393 }
Steve Naroff874e2322007-11-15 10:28:18 +00001394
Steve Naroff934f2762007-10-24 22:48:43 +00001395 // Synthesize a call to objc_msgSend().
1396 llvm::SmallVector<Expr*, 8> MsgExprs;
1397 IdentifierInfo *clsName = Exp->getClassName();
1398
1399 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1400 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001401 if (!strcmp(clsName->getName(), "super")) {
1402 MsgSendFlavor = MsgSendSuperFunctionDecl;
1403 if (MsgSendStretFlavor)
1404 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1405 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1406
1407 ObjcInterfaceDecl *SuperDecl =
1408 CurMethodDecl->getClassInterface()->getSuperClass();
1409
1410 llvm::SmallVector<Expr*, 4> InitExprs;
1411
1412 // set the receiver to self, the first argument to all methods.
1413 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1414 Context->getObjcIdType(),
1415 SourceLocation()));
1416 llvm::SmallVector<Expr*, 8> ClsExprs;
1417 QualType argType = Context->getPointerType(Context->CharTy);
1418 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1419 SuperDecl->getIdentifier()->getLength(),
1420 false, argType, SourceLocation(),
1421 SourceLocation()));
1422 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1423 &ClsExprs[0],
1424 ClsExprs.size());
1425 // To turn off a warning, type-cast to 'id'
1426 InitExprs.push_back(
1427 new CastExpr(Context->getObjcIdType(),
1428 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1429 // struct objc_super
1430 QualType superType = getSuperStructType();
1431 // (struct objc_super) { <exprs from above> }
1432 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1433 &InitExprs[0], InitExprs.size(),
1434 SourceLocation());
1435 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1436 // struct objc_super *
1437 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1438 Context->getPointerType(SuperRep->getType()),
1439 SourceLocation());
1440 MsgExprs.push_back(Unop);
1441 } else {
1442 llvm::SmallVector<Expr*, 8> ClsExprs;
1443 QualType argType = Context->getPointerType(Context->CharTy);
1444 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1445 clsName->getLength(),
1446 false, argType, SourceLocation(),
1447 SourceLocation()));
1448 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1449 &ClsExprs[0],
1450 ClsExprs.size());
1451 MsgExprs.push_back(Cls);
1452 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001453 } else { // instance message.
1454 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001455
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001456 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001457 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001458 if (MsgSendStretFlavor)
1459 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001460 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1461
1462 llvm::SmallVector<Expr*, 4> InitExprs;
1463
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001464 InitExprs.push_back(
1465 new CastExpr(Context->getObjcIdType(),
1466 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001467
1468 llvm::SmallVector<Expr*, 8> ClsExprs;
1469 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001470 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1471 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001472 false, argType, SourceLocation(),
1473 SourceLocation()));
1474 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001475 &ClsExprs[0],
1476 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001477 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001478 InitExprs.push_back(
Fariborz Jahanian71274312007-12-05 17:29:46 +00001479 new CastExpr(Context->getObjcIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001480 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001481 // struct objc_super
1482 QualType superType = getSuperStructType();
1483 // (struct objc_super) { <exprs from above> }
1484 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1485 &InitExprs[0], InitExprs.size(),
1486 SourceLocation());
1487 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1488 // struct objc_super *
1489 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1490 Context->getPointerType(SuperRep->getType()),
1491 SourceLocation());
1492 MsgExprs.push_back(Unop);
1493 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001494 // Remove all type-casts because it may contain objc-style types; e.g.
1495 // Foo<Proto> *.
1496 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1497 recExpr = CE->getSubExpr();
Steve Naroff874e2322007-11-15 10:28:18 +00001498 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1499 MsgExprs.push_back(recExpr);
1500 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001501 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001502 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001503 llvm::SmallVector<Expr*, 8> SelExprs;
1504 QualType argType = Context->getPointerType(Context->CharTy);
1505 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1506 Exp->getSelector().getName().size(),
1507 false, argType, SourceLocation(),
1508 SourceLocation()));
1509 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1510 &SelExprs[0], SelExprs.size());
1511 MsgExprs.push_back(SelExp);
1512
1513 // Now push any user supplied arguments.
1514 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001515 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001516 // Make all implicit casts explicit...ICE comes in handy:-)
1517 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1518 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001519 userExpr = new CastExpr(ICE->getType()->isObjcQualifiedIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001520 ? Context->getObjcIdType()
1521 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001522 }
1523 // Make id<P...> cast into an 'id' cast.
1524 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
1525 if (CE->getType()->isObjcQualifiedIdType()) {
1526 while ((CE = dyn_cast<CastExpr>(userExpr)))
1527 userExpr = CE->getSubExpr();
1528 userExpr = new CastExpr(Context->getObjcIdType(),
1529 userExpr, SourceLocation());
1530 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001531 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001532 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001533 // We've transferred the ownership to MsgExprs. Null out the argument in
1534 // the original expression, since we will delete it below.
1535 Exp->setArg(i, 0);
1536 }
Steve Naroffab972d32007-11-04 22:37:50 +00001537 // Generate the funky cast.
1538 CastExpr *cast;
1539 llvm::SmallVector<QualType, 8> ArgTypes;
1540 QualType returnType;
1541
1542 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001543 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1544 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1545 else
1546 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroffab972d32007-11-04 22:37:50 +00001547 ArgTypes.push_back(Context->getObjcSelType());
1548 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1549 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001550 for (int i = 0; i < mDecl->getNumParams(); i++) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001551 QualType t = mDecl->getParamDecl(i)->getType()->isObjcQualifiedIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001552 ? Context->getObjcIdType()
1553 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001554 ArgTypes.push_back(t);
1555 }
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001556 returnType = mDecl->getResultType()->isObjcQualifiedIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001557 ? Context->getObjcIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001558 } else {
1559 returnType = Context->getObjcIdType();
1560 }
1561 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001562 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001563
1564 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001565 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1566 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001567
1568 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1569 // If we don't do this cast, we get the following bizarre warning/note:
1570 // xx.m:13: warning: function called through a non-compatible type
1571 // xx.m:13: note: if this code is reached, the program will abort
1572 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1573 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001574
Steve Naroffab972d32007-11-04 22:37:50 +00001575 // Now do the "normal" pointer to function cast.
1576 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001577 &ArgTypes[0], ArgTypes.size(),
1578 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001579 castType = Context->getPointerType(castType);
1580 cast = new CastExpr(castType, cast, SourceLocation());
1581
1582 // Don't forget the parens to enforce the proper binding.
1583 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1584
1585 const FunctionType *FT = msgSendType->getAsFunctionType();
1586 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1587 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001588 if (MsgSendStretFlavor) {
1589 // We have the method which returns a struct/union. Must also generate
1590 // call to objc_msgSend_stret and hang both varieties on a conditional
1591 // expression which dictate which one to envoke depending on size of
1592 // method's return type.
1593
1594 // Create a reference to the objc_msgSend_stret() declaration.
1595 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1596 SourceLocation());
1597 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1598 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1599 SourceLocation());
1600 // Now do the "normal" pointer to function cast.
1601 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001602 &ArgTypes[0], ArgTypes.size(),
1603 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001604 castType = Context->getPointerType(castType);
1605 cast = new CastExpr(castType, cast, SourceLocation());
1606
1607 // Don't forget the parens to enforce the proper binding.
1608 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1609
1610 FT = msgSendType->getAsFunctionType();
1611 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1612 FT->getResultType(), SourceLocation());
1613
1614 // Build sizeof(returnType)
1615 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1616 returnType, Context->getSizeType(),
1617 SourceLocation(), SourceLocation());
1618 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1619 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1620 // For X86 it is more complicated and some kind of target specific routine
1621 // is needed to decide what to do.
1622 unsigned IntSize = static_cast<unsigned>(
1623 Context->getTypeSize(Context->IntTy, SourceLocation()));
1624
1625 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1626 Context->IntTy,
1627 SourceLocation());
1628 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1629 BinaryOperator::LE,
1630 Context->IntTy,
1631 SourceLocation());
1632 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1633 ConditionalOperator *CondExpr =
1634 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1635 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1636 // Now do the actual rewrite.
1637 Rewrite.ReplaceStmt(Exp, PE);
1638 delete Exp;
1639 return PE;
1640 }
Steve Naroff934f2762007-10-24 22:48:43 +00001641 // Now do the actual rewrite.
Steve Naroffab972d32007-11-04 22:37:50 +00001642 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff934f2762007-10-24 22:48:43 +00001643
Chris Lattnere64b7772007-10-24 16:57:36 +00001644 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001645 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001646}
1647
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001648/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1649/// call to objc_getProtocol("proto-name").
1650Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1651 if (!GetProtocolFunctionDecl)
1652 SynthGetProtocolFunctionDecl();
1653 // Create a call to objc_getProtocol("ProtocolName").
1654 llvm::SmallVector<Expr*, 8> ProtoExprs;
1655 QualType argType = Context->getPointerType(Context->CharTy);
1656 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1657 strlen(Exp->getProtocol()->getName()),
1658 false, argType, SourceLocation(),
1659 SourceLocation()));
1660 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1661 &ProtoExprs[0],
1662 ProtoExprs.size());
1663 Rewrite.ReplaceStmt(Exp, ProtoExp);
1664 delete Exp;
1665 return ProtoExp;
1666
1667}
1668
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001669/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1670/// an objective-c class with ivars.
1671void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1672 std::string &Result) {
1673 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1674 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001675 // Do not synthesize more than once.
1676 if (ObjcSynthesizedStructs.count(CDecl))
1677 return;
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001678 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001679 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001680 SourceLocation LocStart = CDecl->getLocStart();
1681 SourceLocation LocEnd = CDecl->getLocEnd();
1682
1683 const char *startBuf = SM->getCharacterData(LocStart);
1684 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001685 // If no ivars and no root or if its root, directly or indirectly,
1686 // have no ivars (thus not synthesized) then no need to synthesize this class.
1687 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001688 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1689 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1690 Result.c_str(), Result.size());
1691 return;
1692 }
1693
1694 // FIXME: This has potential of causing problem. If
1695 // SynthesizeObjcInternalStruct is ever called recursively.
1696 Result += "\nstruct ";
1697 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001698
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001699 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001700 const char *cursor = strchr(startBuf, '{');
1701 assert((cursor && endBuf)
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001702 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001703
1704 // rewrite the original header *without* disturbing the '{'
1705 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1706 Result.c_str(), Result.size());
1707 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1708 Result = "\n struct ";
1709 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001710 // Note: We don't name the field decl. This simplifies the "codegen" for
1711 // accessing a superclasses instance variables (and is similar to what gcc
1712 // does internally). The unnamed struct field feature is enabled with
1713 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1714 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001715 Result += ";\n";
1716
1717 // insert the super class structure definition.
1718 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1719 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1720 }
1721 cursor++; // past '{'
1722
1723 // Now comment out any visibility specifiers.
1724 while (cursor < endBuf) {
1725 if (*cursor == '@') {
1726 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001727 // Skip whitespace.
1728 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1729 /*scan*/;
1730
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001731 // FIXME: presence of @public, etc. inside comment results in
1732 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001733 if (!strncmp(cursor, "public", strlen("public")) ||
1734 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001735 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001736 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001737 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001738 // FIXME: If there are cases where '<' is used in ivar declaration part
1739 // of user code, then scan the ivar list and use needToScanForQualifiers
1740 // for type checking.
1741 else if (*cursor == '<') {
1742 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1743 Rewrite.InsertText(atLoc, "/* ", 3);
1744 cursor = strchr(cursor, '>');
1745 cursor++;
1746 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1747 Rewrite.InsertText(atLoc, " */", 3);
1748 }
Steve Narofffea763e82007-11-14 19:25:57 +00001749 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001750 }
Steve Narofffea763e82007-11-14 19:25:57 +00001751 // Don't forget to add a ';'!!
1752 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1753 } else { // we don't have any instance variables - insert super struct.
1754 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1755 Result += " {\n struct ";
1756 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001757 // Note: We don't name the field decl. This simplifies the "codegen" for
1758 // accessing a superclasses instance variables (and is similar to what gcc
1759 // does internally). The unnamed struct field feature is enabled with
1760 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1761 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001762 Result += ";\n};\n";
1763 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1764 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001765 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001766 // Mark this struct as having been generated.
1767 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanianaff56d02007-10-31 22:57:04 +00001768 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001769}
1770
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001771// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1772/// class methods.
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001773void RewriteTest::RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
1774 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001775 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001776 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001777 const char *ClassName,
1778 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001779 if (MethodBegin == MethodEnd) return;
1780
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001781 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001782 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001783 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001784 SEL _cmd;
1785 char *method_types;
1786 void *_imp;
1787 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001788 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001789 Result += "\nstruct _objc_method {\n";
1790 Result += "\tSEL _cmd;\n";
1791 Result += "\tchar *method_types;\n";
1792 Result += "\tvoid *_imp;\n";
1793 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001794
1795 /* struct _objc_method_list {
1796 struct _objc_method_list *next_method;
1797 int method_count;
1798 struct _objc_method method_list[];
1799 }
1800 */
1801 Result += "\nstruct _objc_method_list {\n";
1802 Result += "\tstruct _objc_method_list *next_method;\n";
1803 Result += "\tint method_count;\n";
1804 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001805 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001806 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001807
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001808 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001809 Result += "\nstatic struct _objc_method_list _OBJC_";
1810 Result += prefix;
1811 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1812 Result += "_METHODS_";
1813 Result += ClassName;
1814 Result += " __attribute__ ((section (\"__OBJC, __";
1815 Result += IsInstanceMethod ? "inst" : "cls";
1816 Result += "_meth\")))= ";
1817 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001818
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001819 Result += "\t,{{(SEL)\"";
1820 Result += (*MethodBegin)->getSelector().getName().c_str();
1821 std::string MethodTypeString;
1822 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
1823 Result += "\", \"";
1824 Result += MethodTypeString;
1825 Result += "\", ";
1826 Result += MethodInternalNames[*MethodBegin];
1827 Result += "}\n";
1828 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
1829 Result += "\t ,{(SEL)\"";
1830 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001831 std::string MethodTypeString;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001832 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001833 Result += "\", \"";
1834 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001835 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001836 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001837 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001838 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001839 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001840}
1841
1842/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1843void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1844 int NumProtocols,
1845 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001846 const char *ClassName,
1847 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001848 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001849 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001850 for (int i = 0; i < NumProtocols; i++) {
1851 ObjcProtocolDecl *PDecl = Protocols[i];
1852 // Output struct protocol_methods holder of method selector and type.
1853 if (!objc_protocol_methods &&
1854 (PDecl->getNumInstanceMethods() > 0
1855 || PDecl->getNumClassMethods() > 0)) {
1856 /* struct protocol_methods {
1857 SEL _cmd;
1858 char *method_types;
1859 }
1860 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001861 Result += "\nstruct protocol_methods {\n";
1862 Result += "\tSEL _cmd;\n";
1863 Result += "\tchar *method_types;\n";
1864 Result += "};\n";
1865
1866 /* struct _objc_protocol_method_list {
1867 int protocol_method_count;
1868 struct protocol_methods protocols[];
1869 }
1870 */
1871 Result += "\nstruct _objc_protocol_method_list {\n";
1872 Result += "\tint protocol_method_count;\n";
1873 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001874 objc_protocol_methods = true;
1875 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001876
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00001877 int NumMethods = PDecl->getNumInstanceMethods();
1878 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001879 Result += "\nstatic struct _objc_protocol_method_list "
1880 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1881 Result += PDecl->getName();
1882 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1883 "{\n\t" + utostr(NumMethods) + "\n";
1884
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00001885 // Output instance methods declared in this protocol.
1886 for (ObjcProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1887 E = PDecl->instmeth_end(); I != E; ++I) {
1888 if (I == PDecl->instmeth_begin())
1889 Result += "\t ,{{(SEL)\"";
1890 else
1891 Result += "\t ,{(SEL)\"";
1892 Result += (*I)->getSelector().getName().c_str();
1893 std::string MethodTypeString;
1894 Context->getObjcEncodingForMethodDecl((*I), MethodTypeString);
1895 Result += "\", \"";
1896 Result += MethodTypeString;
1897 Result += "\"}\n";
1898 }
1899 Result += "\t }\n};\n";
1900 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001901
1902 // Output class methods declared in this protocol.
1903 NumMethods = PDecl->getNumClassMethods();
1904 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001905 Result += "\nstatic struct _objc_protocol_method_list "
1906 "_OBJC_PROTOCOL_CLASS_METHODS_";
1907 Result += PDecl->getName();
1908 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1909 "{\n\t";
1910 Result += utostr(NumMethods);
1911 Result += "\n";
1912
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00001913 // Output instance methods declared in this protocol.
1914 for (ObjcProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
1915 E = PDecl->classmeth_end(); I != E; ++I) {
1916 if (I == PDecl->classmeth_begin())
1917 Result += "\t ,{{(SEL)\"";
1918 else
1919 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001920 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001921 std::string MethodTypeString;
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001922 Context->getObjcEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001923 Result += "\", \"";
1924 Result += MethodTypeString;
1925 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001926 }
1927 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001928 }
1929 // Output:
1930 /* struct _objc_protocol {
1931 // Objective-C 1.0 extensions
1932 struct _objc_protocol_extension *isa;
1933 char *protocol_name;
1934 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001935 struct _objc_protocol_method_list *instance_methods;
1936 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001937 };
1938 */
1939 static bool objc_protocol = false;
1940 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001941 Result += "\nstruct _objc_protocol {\n";
1942 Result += "\tstruct _objc_protocol_extension *isa;\n";
1943 Result += "\tchar *protocol_name;\n";
1944 Result += "\tstruct _objc_protocol **protocol_list;\n";
1945 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1946 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1947 Result += "};\n";
1948
1949 /* struct _objc_protocol_list {
1950 struct _objc_protocol_list *next;
1951 int protocol_count;
1952 struct _objc_protocol *class_protocols[];
1953 }
1954 */
1955 Result += "\nstruct _objc_protocol_list {\n";
1956 Result += "\tstruct _objc_protocol_list *next;\n";
1957 Result += "\tint protocol_count;\n";
1958 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1959 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001960 objc_protocol = true;
1961 }
1962
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001963 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1964 Result += PDecl->getName();
1965 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1966 "{\n\t0, \"";
1967 Result += PDecl->getName();
1968 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001969 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001970 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1971 Result += PDecl->getName();
1972 Result += ", ";
1973 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001974 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001975 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001976 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001977 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1978 Result += PDecl->getName();
1979 Result += "\n";
1980 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001981 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001982 Result += "0\n";
1983 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001984 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001985 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001986 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1987 Result += prefix;
1988 Result += "_PROTOCOLS_";
1989 Result += ClassName;
1990 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1991 "{\n\t0, ";
1992 Result += utostr(NumProtocols);
1993 Result += "\n";
1994
1995 Result += "\t,{&_OBJC_PROTOCOL_";
1996 Result += Protocols[0]->getName();
1997 Result += " \n";
1998
1999 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002000 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002001 Result += "\t ,&_OBJC_PROTOCOL_";
2002 Result += PDecl->getName();
2003 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002004 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002005 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002006 }
2007}
2008
2009/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
2010/// implementation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002011void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
2012 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002013 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
2014 // Find category declaration for this implementation.
2015 ObjcCategoryDecl *CDecl;
2016 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2017 CDecl = CDecl->getNextClassCategory())
2018 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2019 break;
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002020
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002021 char *FullCategoryName = (char*)alloca(
2022 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
2023 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
2024
2025 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002026 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2027 true, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002028
2029 // Build _objc_method_list for class's class methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002030 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2031 false, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002032
2033 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002034 // Null CDecl is case of a category implementation with no category interface
2035 if (CDecl)
2036 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2037 CDecl->getNumReferencedProtocols(),
2038 "CATEGORY",
2039 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002040
2041 /* struct _objc_category {
2042 char *category_name;
2043 char *class_name;
2044 struct _objc_method_list *instance_methods;
2045 struct _objc_method_list *class_methods;
2046 struct _objc_protocol_list *protocols;
2047 // Objective-C 1.0 extensions
2048 uint32_t size; // sizeof (struct _objc_category)
2049 struct _objc_property_list *instance_properties; // category's own
2050 // @property decl.
2051 };
2052 */
2053
2054 static bool objc_category = false;
2055 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002056 Result += "\nstruct _objc_category {\n";
2057 Result += "\tchar *category_name;\n";
2058 Result += "\tchar *class_name;\n";
2059 Result += "\tstruct _objc_method_list *instance_methods;\n";
2060 Result += "\tstruct _objc_method_list *class_methods;\n";
2061 Result += "\tstruct _objc_protocol_list *protocols;\n";
2062 Result += "\tunsigned int size;\n";
2063 Result += "\tstruct _objc_property_list *instance_properties;\n";
2064 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002065 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002066 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002067 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2068 Result += FullCategoryName;
2069 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2070 Result += IDecl->getName();
2071 Result += "\"\n\t, \"";
2072 Result += ClassDecl->getName();
2073 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002074
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002075 if (IDecl->getNumInstanceMethods() > 0) {
2076 Result += "\t, (struct _objc_method_list *)"
2077 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2078 Result += FullCategoryName;
2079 Result += "\n";
2080 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002081 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002082 Result += "\t, 0\n";
2083 if (IDecl->getNumClassMethods() > 0) {
2084 Result += "\t, (struct _objc_method_list *)"
2085 "&_OBJC_CATEGORY_CLASS_METHODS_";
2086 Result += FullCategoryName;
2087 Result += "\n";
2088 }
2089 else
2090 Result += "\t, 0\n";
2091
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002092 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002093 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2094 Result += FullCategoryName;
2095 Result += "\n";
2096 }
2097 else
2098 Result += "\t, 0\n";
2099 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002100}
2101
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002102/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2103/// ivar offset.
2104void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2105 ObjcIvarDecl *ivar,
2106 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002107 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002108 Result += IDecl->getName();
2109 Result += ", ";
2110 Result += ivar->getName();
2111 Result += ")";
2112}
2113
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002114//===----------------------------------------------------------------------===//
2115// Meta Data Emission
2116//===----------------------------------------------------------------------===//
2117
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002118void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2119 std::string &Result) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002120 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2121
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002122 // Explictly declared @interface's are already synthesized.
2123 if (CDecl->ImplicitInterfaceDecl()) {
2124 // FIXME: Implementation of a class with no @interface (legacy) doese not
2125 // produce correct synthesis as yet.
2126 SynthesizeObjcInternalStruct(CDecl, Result);
2127 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002128
Chris Lattnerbe6df082007-12-12 07:56:42 +00002129 // Build _objc_ivar_list metadata for classes ivars if needed
2130 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2131 ? IDecl->getImplDeclNumIvars()
2132 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002133 if (NumIvars > 0) {
2134 static bool objc_ivar = false;
2135 if (!objc_ivar) {
2136 /* struct _objc_ivar {
2137 char *ivar_name;
2138 char *ivar_type;
2139 int ivar_offset;
2140 };
2141 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002142 Result += "\nstruct _objc_ivar {\n";
2143 Result += "\tchar *ivar_name;\n";
2144 Result += "\tchar *ivar_type;\n";
2145 Result += "\tint ivar_offset;\n";
2146 Result += "};\n";
2147
2148 /* struct _objc_ivar_list {
2149 int ivar_count;
2150 struct _objc_ivar ivar_list[];
2151 };
2152 */
2153 Result += "\nstruct _objc_ivar_list {\n";
2154 Result += "\tint ivar_count;\n";
2155 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002156 objc_ivar = true;
2157 }
2158
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002159 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2160 Result += IDecl->getName();
2161 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2162 "{\n\t";
2163 Result += utostr(NumIvars);
2164 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002165
2166 ObjcInterfaceDecl::ivar_iterator IVI, IVE;
2167 if (IDecl->getImplDeclNumIvars() > 0) {
2168 IVI = IDecl->ivar_begin();
2169 IVE = IDecl->ivar_end();
2170 } else {
2171 IVI = CDecl->ivar_begin();
2172 IVE = CDecl->ivar_end();
2173 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002174 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002175 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002176 Result += "\", \"";
2177 std::string StrEncoding;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002178 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002179 Result += StrEncoding;
2180 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002181 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002182 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002183 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002184 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002185 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002186 Result += "\", \"";
2187 std::string StrEncoding;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002188 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002189 Result += StrEncoding;
2190 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002191 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002192 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002193 }
2194
2195 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002196 }
2197
2198 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002199 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2200 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002201
2202 // Build _objc_method_list for class's class methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002203 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2204 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002205
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002206 // Protocols referenced in class declaration?
2207 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2208 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002209 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002210
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002211
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002212 // Declaration of class/meta-class metadata
2213 /* struct _objc_class {
2214 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002215 const char *super_class_name;
2216 char *name;
2217 long version;
2218 long info;
2219 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002220 struct _objc_ivar_list *ivars;
2221 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002222 struct objc_cache *cache;
2223 struct objc_protocol_list *protocols;
2224 const char *ivar_layout;
2225 struct _objc_class_ext *ext;
2226 };
2227 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002228 static bool objc_class = false;
2229 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002230 Result += "\nstruct _objc_class {\n";
2231 Result += "\tstruct _objc_class *isa;\n";
2232 Result += "\tconst char *super_class_name;\n";
2233 Result += "\tchar *name;\n";
2234 Result += "\tlong version;\n";
2235 Result += "\tlong info;\n";
2236 Result += "\tlong instance_size;\n";
2237 Result += "\tstruct _objc_ivar_list *ivars;\n";
2238 Result += "\tstruct _objc_method_list *methods;\n";
2239 Result += "\tstruct objc_cache *cache;\n";
2240 Result += "\tstruct _objc_protocol_list *protocols;\n";
2241 Result += "\tconst char *ivar_layout;\n";
2242 Result += "\tstruct _objc_class_ext *ext;\n";
2243 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002244 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002245 }
2246
2247 // Meta-class metadata generation.
2248 ObjcInterfaceDecl *RootClass = 0;
2249 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2250 while (SuperClass) {
2251 RootClass = SuperClass;
2252 SuperClass = SuperClass->getSuperClass();
2253 }
2254 SuperClass = CDecl->getSuperClass();
2255
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002256 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2257 Result += CDecl->getName();
2258 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2259 "{\n\t(struct _objc_class *)\"";
2260 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2261 Result += "\"";
2262
2263 if (SuperClass) {
2264 Result += ", \"";
2265 Result += SuperClass->getName();
2266 Result += "\", \"";
2267 Result += CDecl->getName();
2268 Result += "\"";
2269 }
2270 else {
2271 Result += ", 0, \"";
2272 Result += CDecl->getName();
2273 Result += "\"";
2274 }
Fariborz Jahanian04b38242007-12-04 19:31:56 +00002275 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002276 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002277 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002278 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002279 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002280 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002281 Result += "\n";
2282 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002283 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002284 Result += ", 0\n";
2285 if (CDecl->getNumIntfRefProtocols() > 0) {
2286 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2287 Result += CDecl->getName();
2288 Result += ",0,0\n";
2289 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002290 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002291 Result += "\t,0,0,0,0\n";
2292 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002293
2294 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002295 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2296 Result += CDecl->getName();
2297 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2298 "{\n\t&_OBJC_METACLASS_";
2299 Result += CDecl->getName();
2300 if (SuperClass) {
2301 Result += ", \"";
2302 Result += SuperClass->getName();
2303 Result += "\", \"";
2304 Result += CDecl->getName();
2305 Result += "\"";
2306 }
2307 else {
2308 Result += ", 0, \"";
2309 Result += CDecl->getName();
2310 Result += "\"";
2311 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002312 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002313 Result += ", 0,1";
2314 if (!ObjcSynthesizedStructs.count(CDecl))
2315 Result += ",0";
2316 else {
2317 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002318 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002319 Result += CDecl->getName();
2320 Result += ")";
2321 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002322 if (NumIvars > 0) {
2323 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2324 Result += CDecl->getName();
2325 Result += "\n\t";
2326 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002327 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002328 Result += ",0";
2329 if (IDecl->getNumInstanceMethods() > 0) {
2330 Result += ", &_OBJC_INSTANCE_METHODS_";
2331 Result += CDecl->getName();
2332 Result += ", 0\n\t";
2333 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002334 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002335 Result += ",0,0";
2336 if (CDecl->getNumIntfRefProtocols() > 0) {
2337 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2338 Result += CDecl->getName();
2339 Result += ", 0,0\n";
2340 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002341 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002342 Result += ",0,0,0\n";
2343 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002344}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002345
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002346/// RewriteImplementations - This routine rewrites all method implementations
2347/// and emits meta-data.
2348
2349void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002350 int ClsDefCount = ClassImplementation.size();
2351 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002352
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002353 if (ClsDefCount == 0 && CatDefCount == 0)
2354 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002355 // Rewrite implemented methods
2356 for (int i = 0; i < ClsDefCount; i++)
2357 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002358
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002359 for (int i = 0; i < CatDefCount; i++)
2360 RewriteImplementationDecl(CategoryImplementation[i]);
2361
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002362 // This is needed for use of offsetof
2363 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002364
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002365 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002366 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002367 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002368
2369 // For each implemented category, write out all its meta data.
2370 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002371 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002372
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002373 // Write objc_symtab metadata
2374 /*
2375 struct _objc_symtab
2376 {
2377 long sel_ref_cnt;
2378 SEL *refs;
2379 short cls_def_cnt;
2380 short cat_def_cnt;
2381 void *defs[cls_def_cnt + cat_def_cnt];
2382 };
2383 */
2384
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002385 Result += "\nstruct _objc_symtab {\n";
2386 Result += "\tlong sel_ref_cnt;\n";
2387 Result += "\tSEL *refs;\n";
2388 Result += "\tshort cls_def_cnt;\n";
2389 Result += "\tshort cat_def_cnt;\n";
2390 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2391 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002392
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002393 Result += "static struct _objc_symtab "
2394 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2395 Result += "\t0, 0, " + utostr(ClsDefCount)
2396 + ", " + utostr(CatDefCount) + "\n";
2397 for (int i = 0; i < ClsDefCount; i++) {
2398 Result += "\t,&_OBJC_CLASS_";
2399 Result += ClassImplementation[i]->getName();
2400 Result += "\n";
2401 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002402
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002403 for (int i = 0; i < CatDefCount; i++) {
2404 Result += "\t,&_OBJC_CATEGORY_";
2405 Result += CategoryImplementation[i]->getClassInterface()->getName();
2406 Result += "_";
2407 Result += CategoryImplementation[i]->getName();
2408 Result += "\n";
2409 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002410
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002411 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002412
2413 // Write objc_module metadata
2414
2415 /*
2416 struct _objc_module {
2417 long version;
2418 long size;
2419 const char *name;
2420 struct _objc_symtab *symtab;
2421 }
2422 */
2423
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002424 Result += "\nstruct _objc_module {\n";
2425 Result += "\tlong version;\n";
2426 Result += "\tlong size;\n";
2427 Result += "\tconst char *name;\n";
2428 Result += "\tstruct _objc_symtab *symtab;\n";
2429 Result += "};\n\n";
2430 Result += "static struct _objc_module "
2431 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002432 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2433 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002434 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002435
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002436}
Chris Lattner311ff022007-10-16 22:36:42 +00002437