blob: 81f818a67b4165b4535889abd71ec5634e60bed8 [file] [log] [blame]
Chris Lattnerb429ae42007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb429ae42007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000025#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000026using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000028
Chris Lattnerb429ae42007-10-11 00:43:27 +000029namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Ted Kremenek42730c52008-01-07 19:49:32 +000038 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
40 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
41 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
42 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000054
Steve Naroff0add5d22007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000058
Steve Naroff764c1ae2007-11-15 10:28:18 +000059 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000060 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000061 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000064 public:
Ted Kremenek17861c52007-12-19 22:51:13 +000065 void Initialize(ASTContext &context) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000066 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattnerae43eb72007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
Ted Kremenek17861c52007-12-19 22:51:13 +000084 MainFileID = SM->getMainFileID();
Chris Lattnerae43eb72007-12-02 01:13:47 +000085 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenekb3ee1932007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff8a9b95c2007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-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 Narofffcab7932007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-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 Jahanian1d29b5d2007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroffd3287d82007-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 Jahanian8d9c7352007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000124 "#include <objc/objc.h>\n"
125 "struct __objcFastEnumerationState {\n\t"
126 "unsigned long state;\n\t"
127 "id *itemsPtr;\n\t"
128 "unsigned long *mutationsPtr;\n\t"
129 "unsigned long extra[5];\n};\n";
130
Ted Kremenek17861c52007-12-19 22:51:13 +0000131 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
Steve Naroff0744c472007-11-04 22:37:50 +0000132 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +0000133 }
Chris Lattner569faa62007-10-11 18:38:32 +0000134
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000135 // Top Level Driver code.
136 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000137 void HandleDeclInMainFile(Decl *D);
Chris Lattner258f26c2007-11-30 22:25:36 +0000138 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000139 ~RewriteTest();
140
141 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000142 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000143 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000144 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000145 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
146 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000147 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000148 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
149 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
150 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
151 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
152 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
153 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000154 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000155 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000156 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000157 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000158 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000159
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000160 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000161 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000162 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000163 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000164 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000165 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000166 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000167 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000168 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
169 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
170 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
171 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000172 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000173 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
174 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000175 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
176 void SynthCountByEnumWithState(std::string &buf);
177
Steve Naroff02a82aa2007-10-30 23:14:51 +0000178 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000179 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000180 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000181 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000182 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000183 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000184 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000185 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000186 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000187 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000188
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000189 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000190 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000191 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000192
Ted Kremenek42730c52008-01-07 19:49:32 +0000193 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000194 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000195
Ted Kremenek42730c52008-01-07 19:49:32 +0000196 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
197 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000198 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000199 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000200 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000201 const char *ClassName,
202 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000203
Ted Kremenek42730c52008-01-07 19:49:32 +0000204 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000205 int NumProtocols,
206 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000207 const char *ClassName,
208 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000209 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000210 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000211 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
212 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000213 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000214 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000215 };
216}
217
Chris Lattner258f26c2007-11-30 22:25:36 +0000218ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
219 return new RewriteTest(Diags);
220}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000221
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000222//===----------------------------------------------------------------------===//
223// Top Level Driver Code
224//===----------------------------------------------------------------------===//
225
Chris Lattner569faa62007-10-11 18:38:32 +0000226void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000227 // Two cases: either the decl could be in the main file, or it could be in a
228 // #included file. If the former, rewrite it now. If the later, check to see
229 // if we rewrote the #include/#import.
230 SourceLocation Loc = D->getLocation();
231 Loc = SM->getLogicalLoc(Loc);
232
233 // If this is for a builtin, ignore it.
234 if (Loc.isInvalid()) return;
235
Steve Naroffe9780582007-10-23 23:50:29 +0000236 // Look for built-in declarations that we need to refer during the rewrite.
237 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000238 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000239 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
240 // declared in <Foundation/NSString.h>
241 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
242 ConstantStringClassReference = FVD;
243 return;
244 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000245 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000246 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000247 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000248 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000249 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000250 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000251 } else if (ObjCForwardProtocolDecl *FP =
252 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000253 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000254 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000255 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000256 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
257 return HandleDeclInMainFile(D);
258
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000259 // Otherwise, see if there is a #import in the main file that should be
260 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000261 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000262}
263
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000264/// HandleDeclInMainFile - This is called for each top-level decl defined in the
265/// main file of the input.
266void RewriteTest::HandleDeclInMainFile(Decl *D) {
267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
268 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000269 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000270
Ted Kremenek42730c52008-01-07 19:49:32 +0000271 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000272 if (Stmt *Body = MD->getBody()) {
273 //Body->dump();
274 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000275 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000276 CurMethodDecl = 0;
277 }
Steve Naroff18c83382007-11-13 23:01:27 +0000278 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000279 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000280 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000281 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000282 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000283 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000284 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000285 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000286 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000287 if (VD->getInit())
288 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
289 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000290 // Nothing yet.
291}
292
293RewriteTest::~RewriteTest() {
294 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000295
296 // Rewrite tabs if we care.
297 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000298
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000299 // Rewrite Objective-c meta data*
300 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000301 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000302
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000303 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
304 // we are done.
305 if (const RewriteBuffer *RewriteBuf =
306 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000307 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000308 std::string S(RewriteBuf->begin(), RewriteBuf->end());
309 printf("%s\n", S.c_str());
310 } else {
311 printf("No changes\n");
312 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000313 // Emit metadata.
314 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000315}
316
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000317//===----------------------------------------------------------------------===//
318// Syntactic (non-AST) Rewriting Code
319//===----------------------------------------------------------------------===//
320
Chris Lattner74db1682007-10-16 21:07:07 +0000321void RewriteTest::RewriteInclude(SourceLocation Loc) {
322 // Rip up the #include stack to the main file.
323 SourceLocation IncLoc = Loc, NextLoc = Loc;
324 do {
325 IncLoc = Loc;
326 Loc = SM->getLogicalLoc(NextLoc);
327 NextLoc = SM->getIncludeLoc(Loc);
328 } while (!NextLoc.isInvalid());
329
330 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
331 // IncLoc indicates the header that was included if it is useful.
332 IncLoc = SM->getLogicalLoc(IncLoc);
333 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
334 Loc == LastIncLoc)
335 return;
336 LastIncLoc = Loc;
337
338 unsigned IncCol = SM->getColumnNumber(Loc);
339 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
340
341 // Replace the #import with #include.
342 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
343}
344
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000345void RewriteTest::RewriteTabs() {
346 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
347 const char *MainBufStart = MainBuf.first;
348 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000349
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000350 // Loop over the whole file, looking for tabs.
351 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
352 if (*BufPtr != '\t')
353 continue;
354
355 // Okay, we found a tab. This tab will turn into at least one character,
356 // but it depends on which 'virtual column' it is in. Compute that now.
357 unsigned VCol = 0;
358 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
359 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
360 ++VCol;
361
362 // Okay, now that we know the virtual column, we know how many spaces to
363 // insert. We assume 8-character tab-stops.
364 unsigned Spaces = 8-(VCol & 7);
365
366 // Get the location of the tab.
367 SourceLocation TabLoc =
368 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
369
370 // Rewrite the single tab character into a sequence of spaces.
371 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
372 }
Chris Lattner569faa62007-10-11 18:38:32 +0000373}
374
375
Ted Kremenek42730c52008-01-07 19:49:32 +0000376void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000377 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000378 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000379
380 // Get the start location and compute the semi location.
381 SourceLocation startLoc = ClassDecl->getLocation();
382 const char *startBuf = SM->getCharacterData(startLoc);
383 const char *semiPtr = strchr(startBuf, ';');
384
385 // Translate to typedef's that forward reference structs with the same name
386 // as the class. As a convenience, we include the original declaration
387 // as a comment.
388 std::string typedefString;
389 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000390 typedefString.append(startBuf, semiPtr-startBuf+1);
391 typedefString += "\n";
392 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000393 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000394 typedefString += "#ifndef _REWRITER_typedef_";
395 typedefString += ForwardDecl->getName();
396 typedefString += "\n";
397 typedefString += "#define _REWRITER_typedef_";
398 typedefString += ForwardDecl->getName();
399 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000400 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000401 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000402 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000403 }
404
405 // Replace the @class with typedefs corresponding to the classes.
406 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
407 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000408}
409
Ted Kremenek42730c52008-01-07 19:49:32 +0000410void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000411 SourceLocation LocStart = Method->getLocStart();
412 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000413
Steve Naroff2ce399a2007-12-14 23:37:57 +0000414 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
415 Rewrite.InsertText(LocStart, "/* ", 3);
416 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
417 } else {
418 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000419 }
420}
421
Ted Kremenek42730c52008-01-07 19:49:32 +0000422void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000423{
424 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000425 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000426 SourceLocation Loc = Property->getLocation();
427
428 Rewrite.ReplaceText(Loc, 0, "// ", 3);
429
430 // FIXME: handle properties that are declared across multiple lines.
431 }
432}
433
Ted Kremenek42730c52008-01-07 19:49:32 +0000434void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000435 SourceLocation LocStart = CatDecl->getLocStart();
436
437 // FIXME: handle category headers that are declared across multiple lines.
438 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
439
Ted Kremenek42730c52008-01-07 19:49:32 +0000440 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000441 E = CatDecl->instmeth_end(); I != E; ++I)
442 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000443 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000444 E = CatDecl->classmeth_end(); I != E; ++I)
445 RewriteMethodDeclaration(*I);
446
Steve Naroff667f1682007-10-30 13:30:57 +0000447 // Lastly, comment out the @end.
448 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
449}
450
Ted Kremenek42730c52008-01-07 19:49:32 +0000451void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000452 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000453
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000454 SourceLocation LocStart = PDecl->getLocStart();
455
456 // FIXME: handle protocol headers that are declared across multiple lines.
457 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
458
Ted Kremenek42730c52008-01-07 19:49:32 +0000459 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000460 E = PDecl->instmeth_end(); I != E; ++I)
461 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000462 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000463 E = PDecl->classmeth_end(); I != E; ++I)
464 RewriteMethodDeclaration(*I);
465
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000466 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000467 SourceLocation LocEnd = PDecl->getAtEndLoc();
468 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000469
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000470 // Must comment out @optional/@required
471 const char *startBuf = SM->getCharacterData(LocStart);
472 const char *endBuf = SM->getCharacterData(LocEnd);
473 for (const char *p = startBuf; p < endBuf; p++) {
474 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
475 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000476 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000477 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
478 CommentedOptional.c_str(), CommentedOptional.size());
479
480 }
481 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
482 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000483 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000484 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
485 CommentedRequired.c_str(), CommentedRequired.size());
486
487 }
488 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000489}
490
Ted Kremenek42730c52008-01-07 19:49:32 +0000491void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000492 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000493 if (LocStart.isInvalid())
494 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000495 // FIXME: handle forward protocol that are declared across multiple lines.
496 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
497}
498
Ted Kremenek42730c52008-01-07 19:49:32 +0000499void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000500 std::string &ResultStr) {
501 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000502 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000503 ResultStr += "id";
504 else
505 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000506 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000507
508 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000509 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000510
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000511 if (OMD->isInstance())
512 NameStr += "_I_";
513 else
514 NameStr += "_C_";
515
516 NameStr += OMD->getClassInterface()->getName();
517 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000518
519 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000520 if (ObjCCategoryImplDecl *CID =
521 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000522 NameStr += CID->getName();
523 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000524 }
525 // Append selector names, replacing ':' with '_'
526 const char *selName = OMD->getSelector().getName().c_str();
527 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000528 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000529 else {
530 std::string selString = OMD->getSelector().getName();
531 int len = selString.size();
532 for (int i = 0; i < len; i++)
533 if (selString[i] == ':')
534 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000535 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000536 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000537 // Remember this name for metadata emission
538 MethodInternalNames[OMD] = NameStr;
539 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000540
541 // Rewrite arguments
542 ResultStr += "(";
543
544 // invisible arguments
545 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000546 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000547 selfTy = Context->getPointerType(selfTy);
Ted Kremenek42730c52008-01-07 19:49:32 +0000548 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000549 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000550 ResultStr += selfTy.getAsString();
551 }
552 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000553 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000554
555 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000556 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000557 ResultStr += " _cmd";
558
559 // Method arguments.
560 for (int i = 0; i < OMD->getNumParams(); i++) {
561 ParmVarDecl *PDecl = OMD->getParamDecl(i);
562 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000563 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000564 ResultStr += "id";
565 else
566 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000567 ResultStr += " ";
568 ResultStr += PDecl->getName();
569 }
570 ResultStr += ")";
571
572}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000573void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000574 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
575 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000576
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000577 if (IMD)
578 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
579 else
580 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000581
Ted Kremenek42730c52008-01-07 19:49:32 +0000582 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000583 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
584 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000585 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000586 ObjCMethodDecl *OMD = *I;
587 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000588 SourceLocation LocStart = OMD->getLocStart();
589 SourceLocation LocEnd = OMD->getBody()->getLocStart();
590
591 const char *startBuf = SM->getCharacterData(LocStart);
592 const char *endBuf = SM->getCharacterData(LocEnd);
593 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
594 ResultStr.c_str(), ResultStr.size());
595 }
596
Ted Kremenek42730c52008-01-07 19:49:32 +0000597 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000598 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
599 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000600 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000601 ObjCMethodDecl *OMD = *I;
602 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000603 SourceLocation LocStart = OMD->getLocStart();
604 SourceLocation LocEnd = OMD->getBody()->getLocStart();
605
606 const char *startBuf = SM->getCharacterData(LocStart);
607 const char *endBuf = SM->getCharacterData(LocEnd);
608 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
609 ResultStr.c_str(), ResultStr.size());
610 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000611 if (IMD)
612 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
613 else
614 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000615}
616
Ted Kremenek42730c52008-01-07 19:49:32 +0000617void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000618 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000619 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000620 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000621 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000622 ResultStr += ClassDecl->getName();
623 ResultStr += "\n";
624 ResultStr += "#define _REWRITER_typedef_";
625 ResultStr += ClassDecl->getName();
626 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000627 ResultStr += "typedef struct ";
628 ResultStr += ClassDecl->getName();
629 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000630 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000631 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000632
633 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000634 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000635 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000636 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000637
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000638 RewriteProperties(ClassDecl->getNumPropertyDecl(),
639 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000640 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000641 E = ClassDecl->instmeth_end(); I != E; ++I)
642 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000643 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000644 E = ClassDecl->classmeth_end(); I != E; ++I)
645 RewriteMethodDeclaration(*I);
646
Steve Naroff1ccf4632007-10-30 03:43:13 +0000647 // Lastly, comment out the @end.
648 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000649}
650
Steve Naroff6b759ce2007-11-15 02:58:25 +0000651Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000652 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff6b759ce2007-11-15 02:58:25 +0000653 if (IV->isFreeIvar()) {
654 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
655 IV->getLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000656 if (Rewrite.ReplaceStmt(IV, Replacement)) {
657 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000658 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
659 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000660 SourceRange Range = IV->getSourceRange();
661 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000662 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000663 delete IV;
664 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000665 } else {
666 if (CurMethodDecl) {
667 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000668 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff292b7b92007-11-15 11:33:00 +0000669 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
670 IdentifierInfo *II = intT->getDecl()->getIdentifier();
671 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
672 II, 0);
673 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
674
675 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
676 // Don't forget the parens to enforce the proper binding.
677 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000678 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
679 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000680 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
681 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000682 SourceRange Range = IV->getBase()->getSourceRange();
683 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000684 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000685 delete IV->getBase();
686 return PE;
687 }
688 }
689 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000690 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000691 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000692}
693
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000694//===----------------------------------------------------------------------===//
695// Function Body / Expression rewriting
696//===----------------------------------------------------------------------===//
697
Steve Naroff334fbc22007-11-09 15:20:18 +0000698Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000699 // Otherwise, just rewrite all children.
700 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
701 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000702 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000703 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000704 if (newStmt)
705 *CI = newStmt;
706 }
Steve Naroffe9780582007-10-23 23:50:29 +0000707
708 // Handle specific things.
709 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
710 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000711
712 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
713 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000714
715 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
716 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000717
718 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
719 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000720
Steve Naroff71226032007-10-24 22:48:43 +0000721 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
722 // Before we rewrite it, put the original message expression in a comment.
723 SourceLocation startLoc = MessExpr->getLocStart();
724 SourceLocation endLoc = MessExpr->getLocEnd();
725
726 const char *startBuf = SM->getCharacterData(startLoc);
727 const char *endBuf = SM->getCharacterData(endLoc);
728
729 std::string messString;
730 messString += "// ";
731 messString.append(startBuf, endBuf-startBuf+1);
732 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000733
Steve Naroff71226032007-10-24 22:48:43 +0000734 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
735 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
736 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000737 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000738 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000739 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000740
Ted Kremenek42730c52008-01-07 19:49:32 +0000741 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
742 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000743
Ted Kremenek42730c52008-01-07 19:49:32 +0000744 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
745 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000746
747 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
748 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000749
750 if (ObjCForCollectionStmt *StmtForCollection =
751 dyn_cast<ObjCForCollectionStmt>(S))
752 return RewriteObjCForCollectionStmt(StmtForCollection);
753
Steve Naroff764c1ae2007-11-15 10:28:18 +0000754#if 0
755 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
756 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
757 // Get the new text.
758 std::ostringstream Buf;
759 Replacement->printPretty(Buf);
760 const std::string &Str = Buf.str();
761
762 printf("CAST = %s\n", &Str[0]);
763 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
764 delete S;
765 return Replacement;
766 }
767#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000768 // Return this stmt unmodified.
769 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000770}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000771
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000772/// SynthCountByEnumWithState - To print:
773/// ((unsigned int (*)
774/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
775/// (void *)objc_msgSend)((id)l_collection,
776/// sel_registerName(
777/// "countByEnumeratingWithState:objects:count:"),
778/// &enumState,
779/// (id *)items, (unsigned int)16)
780///
781void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
782 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
783 "id *, unsigned int))(void *)objc_msgSend)";
784 buf += "\n\t\t";
785 buf += "((id)l_collection,\n\t\t";
786 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
787 buf += "\n\t\t";
788 buf += "&enumState, "
789 "(id *)items, (unsigned int)16)";
790}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000791
Fariborz Jahanian72cf3b52008-01-09 01:25:54 +0000792/// RewriteObjCTryStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000793/// It rewrites:
794/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000795
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000796/// Into:
797/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000798/// type elem;
799/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000800/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000801/// id l_collection = (id)collection;
802/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
803/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000804/// if (limit) {
805/// unsigned long startMutations = *enumState.mutationsPtr;
806/// do {
807/// unsigned long counter = 0;
808/// do {
809/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000810/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000811/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000812/// stmts;
813/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000814/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
815/// objects:items count:16]);
816/// elem = nil;
817/// loopend: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000818/// }
819/// else
820/// elem = nil;
821/// }
822///
823Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000824 SourceLocation startLoc = S->getLocStart();
825 SourceLocation collectionLoc = S->getCollection()->getLocStart();
826 const char *startBuf = SM->getCharacterData(startLoc);
827 const char *startCollectionBuf = SM->getCharacterData(collectionLoc);
828 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000829 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000830 std::string buf;
831 buf = "\n{\n\t";
832 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
833 // type elem;
834 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000835 elementTypeAsString = ElementType.getAsString();
836 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000837 buf += " ";
838 elementName = DS->getDecl()->getName();
839 buf += elementName;
840 buf += ";\n\t";
841 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000842 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000843 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000844 elementTypeAsString = DR->getDecl()->getType().getAsString();
845 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000846 else
847 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
848
849 // struct __objcFastEnumerationState enumState = { 0 };
850 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
851 // id items[16];
852 buf += "id items[16];\n\t";
853 // id l_collection = (id)
854 buf += "id l_collection = (id)";
855 // Replace: "for (type element in" with string constructed thus far.
856 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
857 buf.c_str(), buf.size());
858 // Replace ')' in for '(' type elem in collection ')' with ';'
859 SourceLocation endCollectionLoc = S->getCollection()->getLocEnd();
860 const char *endCollectionBuf = SM->getCharacterData(endCollectionLoc);
Fariborz Jahanian09212712008-01-09 17:50:00 +0000861 const char *lparenBuf = strchr(endCollectionBuf+1, ')');
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000862 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(lparenBuf-startBuf);
863 buf = ";\n\t";
864
865 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
866 // objects:items count:16];
867 // which is synthesized into:
868 // unsigned int limit =
869 // ((unsigned int (*)
870 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
871 // (void *)objc_msgSend)((id)l_collection,
872 // sel_registerName(
873 // "countByEnumeratingWithState:objects:count:"),
874 // (struct __objcFastEnumerationState *)&state,
875 // (id *)items, (unsigned int)16);
876 buf += "unsigned long limit =\n\t\t";
877 SynthCountByEnumWithState(buf);
878 buf += ";\n\t";
879 /// if (limit) {
880 /// unsigned long startMutations = *enumState.mutationsPtr;
881 /// do {
882 /// unsigned long counter = 0;
883 /// do {
884 /// if (startMutations != *enumState.mutationsPtr)
885 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000886 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000887 buf += "if (limit) {\n\t";
888 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
889 buf += "do {\n\t\t";
890 buf += "unsigned long counter = 0;\n\t\t";
891 buf += "do {\n\t\t\t";
892 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
893 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
894 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000895 buf += " = (";
896 buf += elementTypeAsString;
897 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000898 // Replace ')' in for '(' type elem in collection ')' with all of these.
899 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
900
901 /// } while (counter < limit);
902 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
903 /// objects:items count:16]);
904 /// elem = nil;
905 /// loopend: ;
906 /// }
907 /// else
908 /// elem = nil;
909 /// }
910 buf = ";\n\t\t";
911 buf += "} while (counter < limit);\n\t";
912 buf += "} while (limit = ";
913 SynthCountByEnumWithState(buf);
914 buf += ");\n\t";
915 buf += elementName;
916 buf += " = nil;\n\t";
917 // TODO: Generate a unique label to exit the for loop on break statement.
918 // buf += "loopend: ;\n\t";
919 buf += "}\n\t";
920 buf += "else\n\t\t";
921 buf += elementName;
922 buf += " = nil;\n";
923 buf += "}\n";
924 // Insert all these *after* the statement body.
925 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
926 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
927 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
928 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
929
930 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000931}
932
Ted Kremenek42730c52008-01-07 19:49:32 +0000933Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000934 // Get the start location and compute the semi location.
935 SourceLocation startLoc = S->getLocStart();
936 const char *startBuf = SM->getCharacterData(startLoc);
937
938 assert((*startBuf == '@') && "bogus @try location");
939
940 std::string buf;
941 // declare a new scope with two variables, _stack and _rethrow.
942 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
943 buf += "int buf[18/*32-bit i386*/];\n";
944 buf += "char *pointers[4];} _stack;\n";
945 buf += "id volatile _rethrow = 0;\n";
946 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000947 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000948
949 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
950
951 startLoc = S->getTryBody()->getLocEnd();
952 startBuf = SM->getCharacterData(startLoc);
953
954 assert((*startBuf == '}') && "bogus @try block");
955
956 SourceLocation lastCurlyLoc = startLoc;
957
958 startLoc = startLoc.getFileLocWithOffset(1);
959 buf = " /* @catch begin */ else {\n";
960 buf += " id _caught = objc_exception_extract(&_stack);\n";
961 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000962 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000963 buf += " _rethrow = objc_exception_extract(&_stack);\n";
964 buf += " else { /* @catch continue */";
965
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000966 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000967
968 bool sawIdTypedCatch = false;
969 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +0000970 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +0000971 while (catchList) {
972 Stmt *catchStmt = catchList->getCatchParamStmt();
973
974 if (catchList == S->getCatchStmts())
975 buf = "if ("; // we are generating code for the first catch clause
976 else
977 buf = "else if (";
978 startLoc = catchList->getLocStart();
979 startBuf = SM->getCharacterData(startLoc);
980
981 assert((*startBuf == '@') && "bogus @catch location");
982
983 const char *lParenLoc = strchr(startBuf, '(');
984
985 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
986 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +0000987 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000988 buf += "1) { ";
989 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
990 buf.c_str(), buf.size());
991 sawIdTypedCatch = true;
992 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000993 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +0000994
Ted Kremenek42730c52008-01-07 19:49:32 +0000995 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +0000996 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000997 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000998 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000999 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +00001000 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1001 buf.c_str(), buf.size());
1002 }
1003 }
1004 // Now rewrite the body...
1005 lastCatchBody = catchList->getCatchBody();
1006 SourceLocation rParenLoc = catchList->getRParenLoc();
1007 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1008 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1009 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1010 assert((*rParenBuf == ')') && "bogus @catch paren location");
1011 assert((*bodyBuf == '{') && "bogus @catch body location");
1012
1013 buf = " = _caught;";
1014 // Here we replace ") {" with "= _caught;" (which initializes and
1015 // declares the @catch parameter).
1016 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1017 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001018 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001019 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001020 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001021 catchList = catchList->getNextCatchStmt();
1022 }
1023 // Complete the catch list...
1024 if (lastCatchBody) {
1025 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1026 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1027 assert((*bodyBuf == '}') && "bogus @catch body location");
1028 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1029 buf = " } } /* @catch end */\n";
1030
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001031 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001032
1033 // Set lastCurlyLoc
1034 lastCurlyLoc = lastCatchBody->getLocEnd();
1035 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001036 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001037 startLoc = finalStmt->getLocStart();
1038 startBuf = SM->getCharacterData(startLoc);
1039 assert((*startBuf == '@') && "bogus @finally start");
1040
1041 buf = "/* @finally */";
1042 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1043
1044 Stmt *body = finalStmt->getFinallyBody();
1045 SourceLocation startLoc = body->getLocStart();
1046 SourceLocation endLoc = body->getLocEnd();
1047 const char *startBuf = SM->getCharacterData(startLoc);
1048 const char *endBuf = SM->getCharacterData(endLoc);
1049 assert((*startBuf == '{') && "bogus @finally body location");
1050 assert((*endBuf == '}') && "bogus @finally body location");
1051
1052 startLoc = startLoc.getFileLocWithOffset(1);
1053 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001054 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001055 endLoc = endLoc.getFileLocWithOffset(-1);
1056 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001057 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001058
1059 // Set lastCurlyLoc
1060 lastCurlyLoc = body->getLocEnd();
1061 }
1062 // Now emit the final closing curly brace...
1063 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1064 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001065 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001066 return 0;
1067}
1068
Ted Kremenek42730c52008-01-07 19:49:32 +00001069Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001070 return 0;
1071}
1072
Ted Kremenek42730c52008-01-07 19:49:32 +00001073Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001074 return 0;
1075}
1076
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001077// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1078// the throw expression is typically a message expression that's already
1079// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001080Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001081 // Get the start location and compute the semi location.
1082 SourceLocation startLoc = S->getLocStart();
1083 const char *startBuf = SM->getCharacterData(startLoc);
1084
1085 assert((*startBuf == '@') && "bogus @throw location");
1086
1087 std::string buf;
1088 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1089 buf = "objc_exception_throw(";
1090 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1091 const char *semiBuf = strchr(startBuf, ';');
1092 assert((*semiBuf == ';') && "@throw: can't find ';'");
1093 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1094 buf = ");";
1095 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1096 return 0;
1097}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001098
Chris Lattner0021f452007-10-24 16:57:36 +00001099Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001100 // Create a new string expression.
1101 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001102 std::string StrEncoding;
Ted Kremenek42730c52008-01-07 19:49:32 +00001103 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001104 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1105 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001106 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +00001107 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1108 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001109 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1110 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner217df512007-12-02 01:09:57 +00001111 SourceRange Range = Exp->getSourceRange();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00001112 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattner258f26c2007-11-30 22:25:36 +00001113 }
1114
Chris Lattner4478db92007-11-30 22:53:43 +00001115 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001116 delete Exp;
1117 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001118}
1119
Steve Naroff296b74f2007-11-05 14:50:49 +00001120Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1121 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1122 // Create a call to sel_registerName("selName").
1123 llvm::SmallVector<Expr*, 8> SelExprs;
1124 QualType argType = Context->getPointerType(Context->CharTy);
1125 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1126 Exp->getSelector().getName().size(),
1127 false, argType, SourceLocation(),
1128 SourceLocation()));
1129 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1130 &SelExprs[0], SelExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001131 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1132 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001133 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1134 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001135 SourceRange Range = Exp->getSourceRange();
1136 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001137 }
Steve Naroff296b74f2007-11-05 14:50:49 +00001138 delete Exp;
1139 return SelExp;
1140}
1141
Steve Naroff71226032007-10-24 22:48:43 +00001142CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1143 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001144 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001145 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001146
1147 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001148 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001149
1150 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001151 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001152 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1153
1154 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001155
Steve Naroff71226032007-10-24 22:48:43 +00001156 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1157}
1158
Steve Naroffc8a92d12007-11-01 13:24:47 +00001159static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1160 const char *&startRef, const char *&endRef) {
1161 while (startBuf < endBuf) {
1162 if (*startBuf == '<')
1163 startRef = startBuf; // mark the start.
1164 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001165 if (startRef && *startRef == '<') {
1166 endRef = startBuf; // mark the end.
1167 return true;
1168 }
1169 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001170 }
1171 startBuf++;
1172 }
1173 return false;
1174}
1175
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001176static void scanToNextArgument(const char *&argRef) {
1177 int angle = 0;
1178 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1179 if (*argRef == '<')
1180 angle++;
1181 else if (*argRef == '>')
1182 angle--;
1183 argRef++;
1184 }
1185 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1186}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001187
Steve Naroffc8a92d12007-11-01 13:24:47 +00001188bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001189
Ted Kremenek42730c52008-01-07 19:49:32 +00001190 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001191 return true;
1192
Ted Kremenek42730c52008-01-07 19:49:32 +00001193 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001194 return true;
1195
Steve Naroffc8a92d12007-11-01 13:24:47 +00001196 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001197 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001198 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001199 return true; // we have "Class <Protocol> *".
1200 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001201 return false;
1202}
1203
Ted Kremenek42730c52008-01-07 19:49:32 +00001204void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001205 SourceLocation Loc;
1206 QualType Type;
1207 const FunctionTypeProto *proto = 0;
1208 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1209 Loc = VD->getLocation();
1210 Type = VD->getType();
1211 }
1212 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1213 Loc = FD->getLocation();
1214 // Check for ObjC 'id' and class types that have been adorned with protocol
1215 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1216 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1217 assert(funcType && "missing function type");
1218 proto = dyn_cast<FunctionTypeProto>(funcType);
1219 if (!proto)
1220 return;
1221 Type = proto->getResultType();
1222 }
1223 else
1224 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001225
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001226 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001227 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001228
1229 const char *endBuf = SM->getCharacterData(Loc);
1230 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001231 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001232 startBuf--; // scan backward (from the decl location) for return type.
1233 const char *startRef = 0, *endRef = 0;
1234 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1235 // Get the locations of the startRef, endRef.
1236 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1237 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1238 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001239 Rewrite.InsertText(LessLoc, "/*", 2);
1240 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001241 }
1242 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001243 if (!proto)
1244 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001245 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001246 const char *startBuf = SM->getCharacterData(Loc);
1247 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001248 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1249 if (needToScanForQualifiers(proto->getArgType(i))) {
1250 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001251
Steve Naroffc8a92d12007-11-01 13:24:47 +00001252 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001253 // scan forward (from the decl location) for argument types.
1254 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001255 const char *startRef = 0, *endRef = 0;
1256 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1257 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001258 SourceLocation LessLoc =
1259 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1260 SourceLocation GreaterLoc =
1261 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001262 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001263 Rewrite.InsertText(LessLoc, "/*", 2);
1264 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001265 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001266 startBuf = ++endBuf;
1267 }
1268 else {
1269 while (*startBuf != ')' && *startBuf != ',')
1270 startBuf++; // scan forward (from the decl location) for argument types.
1271 startBuf++;
1272 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001273 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001274}
1275
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001276// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1277void RewriteTest::SynthSelGetUidFunctionDecl() {
1278 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1279 llvm::SmallVector<QualType, 16> ArgTys;
1280 ArgTys.push_back(Context->getPointerType(
1281 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001282 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001283 &ArgTys[0], ArgTys.size(),
1284 false /*isVariadic*/);
1285 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1286 SelGetUidIdent, getFuncType,
1287 FunctionDecl::Extern, false, 0);
1288}
1289
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001290// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1291void RewriteTest::SynthGetProtocolFunctionDecl() {
1292 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1293 llvm::SmallVector<QualType, 16> ArgTys;
1294 ArgTys.push_back(Context->getPointerType(
1295 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001296 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001297 &ArgTys[0], ArgTys.size(),
1298 false /*isVariadic*/);
1299 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1300 SelGetProtoIdent, getFuncType,
1301 FunctionDecl::Extern, false, 0);
1302}
1303
Steve Naroff02a82aa2007-10-30 23:14:51 +00001304void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1305 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001306 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001307 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001308 return;
1309 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001310 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001311}
1312
1313// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1314void RewriteTest::SynthMsgSendFunctionDecl() {
1315 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1316 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001317 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001318 assert(!argT.isNull() && "Can't find 'id' type");
1319 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001320 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001321 assert(!argT.isNull() && "Can't find 'SEL' type");
1322 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001323 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001324 &ArgTys[0], ArgTys.size(),
1325 true /*isVariadic*/);
1326 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1327 msgSendIdent, msgSendType,
1328 FunctionDecl::Extern, false, 0);
1329}
1330
Steve Naroff764c1ae2007-11-15 10:28:18 +00001331// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1332void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1333 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1334 llvm::SmallVector<QualType, 16> ArgTys;
1335 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1336 &Context->Idents.get("objc_super"), 0);
1337 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1338 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1339 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001340 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001341 assert(!argT.isNull() && "Can't find 'SEL' type");
1342 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001343 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001344 &ArgTys[0], ArgTys.size(),
1345 true /*isVariadic*/);
1346 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1347 msgSendIdent, msgSendType,
1348 FunctionDecl::Extern, false, 0);
1349}
1350
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001351// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1352void RewriteTest::SynthMsgSendStretFunctionDecl() {
1353 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1354 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001355 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001356 assert(!argT.isNull() && "Can't find 'id' type");
1357 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001358 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001359 assert(!argT.isNull() && "Can't find 'SEL' type");
1360 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001361 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001362 &ArgTys[0], ArgTys.size(),
1363 true /*isVariadic*/);
1364 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1365 msgSendIdent, msgSendType,
1366 FunctionDecl::Extern, false, 0);
1367}
1368
1369// SynthMsgSendSuperStretFunctionDecl -
1370// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1371void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1372 IdentifierInfo *msgSendIdent =
1373 &Context->Idents.get("objc_msgSendSuper_stret");
1374 llvm::SmallVector<QualType, 16> ArgTys;
1375 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1376 &Context->Idents.get("objc_super"), 0);
1377 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1378 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1379 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001380 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001381 assert(!argT.isNull() && "Can't find 'SEL' type");
1382 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001383 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001384 &ArgTys[0], ArgTys.size(),
1385 true /*isVariadic*/);
1386 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1387 msgSendIdent, msgSendType,
1388 FunctionDecl::Extern, false, 0);
1389}
1390
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001391// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1392void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1393 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1394 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001395 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001396 assert(!argT.isNull() && "Can't find 'id' type");
1397 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001398 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001399 assert(!argT.isNull() && "Can't find 'SEL' type");
1400 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001401 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001402 &ArgTys[0], ArgTys.size(),
1403 true /*isVariadic*/);
1404 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1405 msgSendIdent, msgSendType,
1406 FunctionDecl::Extern, false, 0);
1407}
1408
Steve Naroff02a82aa2007-10-30 23:14:51 +00001409// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1410void RewriteTest::SynthGetClassFunctionDecl() {
1411 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1412 llvm::SmallVector<QualType, 16> ArgTys;
1413 ArgTys.push_back(Context->getPointerType(
1414 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001415 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001416 &ArgTys[0], ArgTys.size(),
1417 false /*isVariadic*/);
1418 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1419 getClassIdent, getClassType,
1420 FunctionDecl::Extern, false, 0);
1421}
1422
Steve Naroff3b1caac2007-12-07 03:50:46 +00001423// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1424void RewriteTest::SynthGetMetaClassFunctionDecl() {
1425 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1426 llvm::SmallVector<QualType, 16> ArgTys;
1427 ArgTys.push_back(Context->getPointerType(
1428 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001429 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001430 &ArgTys[0], ArgTys.size(),
1431 false /*isVariadic*/);
1432 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1433 getClassIdent, getClassType,
1434 FunctionDecl::Extern, false, 0);
1435}
1436
Steve Naroffabb96362007-11-08 14:30:50 +00001437// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1438void RewriteTest::SynthCFStringFunctionDecl() {
1439 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1440 llvm::SmallVector<QualType, 16> ArgTys;
1441 ArgTys.push_back(Context->getPointerType(
1442 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001443 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffabb96362007-11-08 14:30:50 +00001444 &ArgTys[0], ArgTys.size(),
1445 false /*isVariadic*/);
1446 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1447 getClassIdent, getClassType,
1448 FunctionDecl::Extern, false, 0);
1449}
1450
Steve Naroff0add5d22007-11-03 11:27:19 +00001451Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001452#if 1
1453 // This rewrite is specific to GCC, which has builtin support for CFString.
1454 if (!CFStringFunctionDecl)
1455 SynthCFStringFunctionDecl();
1456 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1457 llvm::SmallVector<Expr*, 8> StrExpr;
1458 StrExpr.push_back(Exp->getString());
1459 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1460 &StrExpr[0], StrExpr.size());
1461 // cast to NSConstantString *
1462 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001463 if (Rewrite.ReplaceStmt(Exp, cast)) {
1464 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001465 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1466 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001467 SourceRange Range = Exp->getSourceRange();
1468 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001469 }
Steve Naroffabb96362007-11-08 14:30:50 +00001470 delete Exp;
1471 return cast;
1472#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001473 assert(ConstantStringClassReference && "Can't find constant string reference");
1474 llvm::SmallVector<Expr*, 4> InitExprs;
1475
1476 // Synthesize "(Class)&_NSConstantStringClassReference"
1477 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1478 ConstantStringClassReference->getType(),
1479 SourceLocation());
1480 QualType expType = Context->getPointerType(ClsRef->getType());
1481 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1482 expType, SourceLocation());
Ted Kremenek42730c52008-01-07 19:49:32 +00001483 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroff0add5d22007-11-03 11:27:19 +00001484 SourceLocation());
1485 InitExprs.push_back(cast); // set the 'isa'.
1486 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1487 unsigned IntSize = static_cast<unsigned>(
1488 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1489 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1490 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1491 Exp->getLocStart());
1492 InitExprs.push_back(len); // set "int numBytes".
1493
1494 // struct NSConstantString
1495 QualType CFConstantStrType = Context->getCFConstantStringType();
1496 // (struct NSConstantString) { <exprs from above> }
1497 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1498 &InitExprs[0], InitExprs.size(),
1499 SourceLocation());
1500 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1501 // struct NSConstantString *
1502 expType = Context->getPointerType(StrRep->getType());
1503 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1504 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001505 // cast to NSConstantString *
1506 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001507 Rewrite.ReplaceStmt(Exp, cast);
1508 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001509 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001510#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001511}
1512
Ted Kremenek42730c52008-01-07 19:49:32 +00001513ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001514 // check if we are sending a message to 'super'
1515 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001516 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1517 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1518 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1519 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001520 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001521 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001522 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001523 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001524 if (ObjCInterfaceType *IT =
1525 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001526 if (IT->getDecl() ==
1527 CurMethodDecl->getClassInterface()->getSuperClass())
1528 return IT->getDecl();
1529 }
1530 }
1531 }
1532 }
1533 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001534 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001535 }
1536 return 0;
1537}
1538
1539// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1540QualType RewriteTest::getSuperStructType() {
1541 if (!SuperStructDecl) {
1542 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1543 &Context->Idents.get("objc_super"), 0);
1544 QualType FieldTypes[2];
1545
1546 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001547 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001548 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001549 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001550 // Create fields
1551 FieldDecl *FieldDecls[2];
1552
1553 for (unsigned i = 0; i < 2; ++i)
1554 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1555
1556 SuperStructDecl->defineBody(FieldDecls, 4);
1557 }
1558 return Context->getTagDeclType(SuperStructDecl);
1559}
1560
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001561Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001562 if (!SelGetUidFunctionDecl)
1563 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001564 if (!MsgSendFunctionDecl)
1565 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001566 if (!MsgSendSuperFunctionDecl)
1567 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001568 if (!MsgSendStretFunctionDecl)
1569 SynthMsgSendStretFunctionDecl();
1570 if (!MsgSendSuperStretFunctionDecl)
1571 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001572 if (!MsgSendFpretFunctionDecl)
1573 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001574 if (!GetClassFunctionDecl)
1575 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001576 if (!GetMetaClassFunctionDecl)
1577 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001578
Steve Naroff764c1ae2007-11-15 10:28:18 +00001579 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001580 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1581 // May need to use objc_msgSend_stret() as well.
1582 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001583 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001584 QualType resultType = mDecl->getResultType();
1585 if (resultType.getCanonicalType()->isStructureType()
1586 || resultType.getCanonicalType()->isUnionType())
1587 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001588 else if (resultType.getCanonicalType()->isRealFloatingType())
1589 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001590 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001591
Steve Naroff71226032007-10-24 22:48:43 +00001592 // Synthesize a call to objc_msgSend().
1593 llvm::SmallVector<Expr*, 8> MsgExprs;
1594 IdentifierInfo *clsName = Exp->getClassName();
1595
1596 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1597 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001598 if (!strcmp(clsName->getName(), "super")) {
1599 MsgSendFlavor = MsgSendSuperFunctionDecl;
1600 if (MsgSendStretFlavor)
1601 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1602 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1603
Ted Kremenek42730c52008-01-07 19:49:32 +00001604 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001605 CurMethodDecl->getClassInterface()->getSuperClass();
1606
1607 llvm::SmallVector<Expr*, 4> InitExprs;
1608
1609 // set the receiver to self, the first argument to all methods.
1610 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001611 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001612 SourceLocation()));
1613 llvm::SmallVector<Expr*, 8> ClsExprs;
1614 QualType argType = Context->getPointerType(Context->CharTy);
1615 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1616 SuperDecl->getIdentifier()->getLength(),
1617 false, argType, SourceLocation(),
1618 SourceLocation()));
1619 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1620 &ClsExprs[0],
1621 ClsExprs.size());
1622 // To turn off a warning, type-cast to 'id'
1623 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001624 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001625 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1626 // struct objc_super
1627 QualType superType = getSuperStructType();
1628 // (struct objc_super) { <exprs from above> }
1629 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1630 &InitExprs[0], InitExprs.size(),
1631 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001632 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1633 superType, ILE);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001634 // struct objc_super *
1635 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1636 Context->getPointerType(SuperRep->getType()),
1637 SourceLocation());
1638 MsgExprs.push_back(Unop);
1639 } else {
1640 llvm::SmallVector<Expr*, 8> ClsExprs;
1641 QualType argType = Context->getPointerType(Context->CharTy);
1642 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1643 clsName->getLength(),
1644 false, argType, SourceLocation(),
1645 SourceLocation()));
1646 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1647 &ClsExprs[0],
1648 ClsExprs.size());
1649 MsgExprs.push_back(Cls);
1650 }
Steve Naroff885e2122007-11-14 23:54:14 +00001651 } else { // instance message.
1652 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001653
Ted Kremenek42730c52008-01-07 19:49:32 +00001654 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001655 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001656 if (MsgSendStretFlavor)
1657 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001658 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1659
1660 llvm::SmallVector<Expr*, 4> InitExprs;
1661
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001662 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001663 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001664 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001665
1666 llvm::SmallVector<Expr*, 8> ClsExprs;
1667 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001668 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1669 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001670 false, argType, SourceLocation(),
1671 SourceLocation()));
1672 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001673 &ClsExprs[0],
1674 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001675 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001676 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001677 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001678 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001679 // struct objc_super
1680 QualType superType = getSuperStructType();
1681 // (struct objc_super) { <exprs from above> }
1682 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1683 &InitExprs[0], InitExprs.size(),
1684 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001685 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1686 superType, ILE);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001687 // struct objc_super *
1688 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1689 Context->getPointerType(SuperRep->getType()),
1690 SourceLocation());
1691 MsgExprs.push_back(Unop);
1692 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001693 // Remove all type-casts because it may contain objc-style types; e.g.
1694 // Foo<Proto> *.
1695 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1696 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001697 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001698 MsgExprs.push_back(recExpr);
1699 }
Steve Naroff885e2122007-11-14 23:54:14 +00001700 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001701 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001702 llvm::SmallVector<Expr*, 8> SelExprs;
1703 QualType argType = Context->getPointerType(Context->CharTy);
1704 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1705 Exp->getSelector().getName().size(),
1706 false, argType, SourceLocation(),
1707 SourceLocation()));
1708 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1709 &SelExprs[0], SelExprs.size());
1710 MsgExprs.push_back(SelExp);
1711
1712 // Now push any user supplied arguments.
1713 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001714 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001715 // Make all implicit casts explicit...ICE comes in handy:-)
1716 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1717 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00001718 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1719 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001720 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001721 }
1722 // Make id<P...> cast into an 'id' cast.
1723 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001724 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001725 while ((CE = dyn_cast<CastExpr>(userExpr)))
1726 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001727 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001728 userExpr, SourceLocation());
1729 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001730 }
Steve Naroff885e2122007-11-14 23:54:14 +00001731 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001732 // We've transferred the ownership to MsgExprs. Null out the argument in
1733 // the original expression, since we will delete it below.
1734 Exp->setArg(i, 0);
1735 }
Steve Naroff0744c472007-11-04 22:37:50 +00001736 // Generate the funky cast.
1737 CastExpr *cast;
1738 llvm::SmallVector<QualType, 8> ArgTypes;
1739 QualType returnType;
1740
1741 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001742 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1743 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1744 else
Ted Kremenek42730c52008-01-07 19:49:32 +00001745 ArgTypes.push_back(Context->getObjCIdType());
1746 ArgTypes.push_back(Context->getObjCSelType());
1747 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00001748 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001749 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001750 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1751 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001752 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001753 ArgTypes.push_back(t);
1754 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001755 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1756 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00001757 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00001758 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00001759 }
1760 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001761 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001762
1763 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001764 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1765 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001766
1767 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1768 // If we don't do this cast, we get the following bizarre warning/note:
1769 // xx.m:13: warning: function called through a non-compatible type
1770 // xx.m:13: note: if this code is reached, the program will abort
1771 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1772 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001773
Steve Naroff0744c472007-11-04 22:37:50 +00001774 // Now do the "normal" pointer to function cast.
1775 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001776 &ArgTypes[0], ArgTypes.size(),
1777 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001778 castType = Context->getPointerType(castType);
1779 cast = new CastExpr(castType, cast, SourceLocation());
1780
1781 // Don't forget the parens to enforce the proper binding.
1782 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1783
1784 const FunctionType *FT = msgSendType->getAsFunctionType();
1785 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1786 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001787 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001788 if (MsgSendStretFlavor) {
1789 // We have the method which returns a struct/union. Must also generate
1790 // call to objc_msgSend_stret and hang both varieties on a conditional
1791 // expression which dictate which one to envoke depending on size of
1792 // method's return type.
1793
1794 // Create a reference to the objc_msgSend_stret() declaration.
1795 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1796 SourceLocation());
1797 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1798 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1799 SourceLocation());
1800 // Now do the "normal" pointer to function cast.
1801 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001802 &ArgTypes[0], ArgTypes.size(),
1803 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001804 castType = Context->getPointerType(castType);
1805 cast = new CastExpr(castType, cast, SourceLocation());
1806
1807 // Don't forget the parens to enforce the proper binding.
1808 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1809
1810 FT = msgSendType->getAsFunctionType();
1811 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1812 FT->getResultType(), SourceLocation());
1813
1814 // Build sizeof(returnType)
1815 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1816 returnType, Context->getSizeType(),
1817 SourceLocation(), SourceLocation());
1818 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1819 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1820 // For X86 it is more complicated and some kind of target specific routine
1821 // is needed to decide what to do.
1822 unsigned IntSize = static_cast<unsigned>(
1823 Context->getTypeSize(Context->IntTy, SourceLocation()));
1824
1825 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1826 Context->IntTy,
1827 SourceLocation());
1828 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1829 BinaryOperator::LE,
1830 Context->IntTy,
1831 SourceLocation());
1832 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1833 ConditionalOperator *CondExpr =
1834 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001835 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001836 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001837 return ReplacingStmt;
1838}
1839
1840Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
1841 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00001842 // Now do the actual rewrite.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001843 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroffe4e5e262007-12-19 14:32:56 +00001844 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001845 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1846 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001847 SourceRange Range = Exp->getSourceRange();
1848 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001849 }
Steve Naroff71226032007-10-24 22:48:43 +00001850
Chris Lattner0021f452007-10-24 16:57:36 +00001851 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001852 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00001853}
1854
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001855/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1856/// call to objc_getProtocol("proto-name").
1857Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1858 if (!GetProtocolFunctionDecl)
1859 SynthGetProtocolFunctionDecl();
1860 // Create a call to objc_getProtocol("ProtocolName").
1861 llvm::SmallVector<Expr*, 8> ProtoExprs;
1862 QualType argType = Context->getPointerType(Context->CharTy);
1863 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1864 strlen(Exp->getProtocol()->getName()),
1865 false, argType, SourceLocation(),
1866 SourceLocation()));
1867 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1868 &ProtoExprs[0],
1869 ProtoExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001870 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1871 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001872 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1873 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001874 SourceRange Range = Exp->getSourceRange();
1875 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001876 }
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001877 delete Exp;
1878 return ProtoExp;
1879
1880}
1881
Ted Kremenek42730c52008-01-07 19:49:32 +00001882/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001883/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00001884void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001885 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001886 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
1887 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001888 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00001889 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001890 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00001891 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001892 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001893 SourceLocation LocStart = CDecl->getLocStart();
1894 SourceLocation LocEnd = CDecl->getLocEnd();
1895
1896 const char *startBuf = SM->getCharacterData(LocStart);
1897 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001898 // If no ivars and no root or if its root, directly or indirectly,
1899 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00001900 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001901 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1902 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1903 Result.c_str(), Result.size());
1904 return;
1905 }
1906
1907 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00001908 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001909 Result += "\nstruct ";
1910 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001911
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001912 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001913 const char *cursor = strchr(startBuf, '{');
1914 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00001915 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001916
1917 // rewrite the original header *without* disturbing the '{'
1918 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1919 Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00001920 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001921 Result = "\n struct ";
1922 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001923 // Note: We don't name the field decl. This simplifies the "codegen" for
1924 // accessing a superclasses instance variables (and is similar to what gcc
1925 // does internally). The unnamed struct field feature is enabled with
1926 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1927 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001928 Result += ";\n";
1929
1930 // insert the super class structure definition.
1931 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1932 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1933 }
1934 cursor++; // past '{'
1935
1936 // Now comment out any visibility specifiers.
1937 while (cursor < endBuf) {
1938 if (*cursor == '@') {
1939 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001940 // Skip whitespace.
1941 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1942 /*scan*/;
1943
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001944 // FIXME: presence of @public, etc. inside comment results in
1945 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001946 if (!strncmp(cursor, "public", strlen("public")) ||
1947 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001948 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001949 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001950 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001951 // FIXME: If there are cases where '<' is used in ivar declaration part
1952 // of user code, then scan the ivar list and use needToScanForQualifiers
1953 // for type checking.
1954 else if (*cursor == '<') {
1955 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1956 Rewrite.InsertText(atLoc, "/* ", 3);
1957 cursor = strchr(cursor, '>');
1958 cursor++;
1959 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1960 Rewrite.InsertText(atLoc, " */", 3);
1961 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001962 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001963 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001964 // Don't forget to add a ';'!!
1965 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1966 } else { // we don't have any instance variables - insert super struct.
1967 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1968 Result += " {\n struct ";
1969 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001970 // Note: We don't name the field decl. This simplifies the "codegen" for
1971 // accessing a superclasses instance variables (and is similar to what gcc
1972 // does internally). The unnamed struct field feature is enabled with
1973 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1974 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001975 Result += ";\n};\n";
1976 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1977 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001978 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001979 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00001980 if (!ObjCSynthesizedStructs.insert(CDecl))
1981 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001982}
1983
Ted Kremenek42730c52008-01-07 19:49:32 +00001984// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001985/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00001986void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001987 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001988 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001989 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001990 const char *ClassName,
1991 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001992 if (MethodBegin == MethodEnd) return;
1993
Fariborz Jahanian04455192007-10-22 21:41:37 +00001994 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001995 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001996 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001997 SEL _cmd;
1998 char *method_types;
1999 void *_imp;
2000 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002001 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002002 Result += "\nstruct _objc_method {\n";
2003 Result += "\tSEL _cmd;\n";
2004 Result += "\tchar *method_types;\n";
2005 Result += "\tvoid *_imp;\n";
2006 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002007
2008 /* struct _objc_method_list {
2009 struct _objc_method_list *next_method;
2010 int method_count;
2011 struct _objc_method method_list[];
2012 }
2013 */
2014 Result += "\nstruct _objc_method_list {\n";
2015 Result += "\tstruct _objc_method_list *next_method;\n";
2016 Result += "\tint method_count;\n";
2017 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002018 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002019 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002020
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002021 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002022 Result += "\nstatic struct _objc_method_list _OBJC_";
2023 Result += prefix;
2024 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2025 Result += "_METHODS_";
2026 Result += ClassName;
2027 Result += " __attribute__ ((section (\"__OBJC, __";
2028 Result += IsInstanceMethod ? "inst" : "cls";
2029 Result += "_meth\")))= ";
2030 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002031
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002032 Result += "\t,{{(SEL)\"";
2033 Result += (*MethodBegin)->getSelector().getName().c_str();
2034 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002035 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002036 Result += "\", \"";
2037 Result += MethodTypeString;
2038 Result += "\", ";
2039 Result += MethodInternalNames[*MethodBegin];
2040 Result += "}\n";
2041 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2042 Result += "\t ,{(SEL)\"";
2043 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002044 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002045 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002046 Result += "\", \"";
2047 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002048 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002049 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002050 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002051 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002052 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002053}
2054
Ted Kremenek42730c52008-01-07 19:49:32 +00002055/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2056void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002057 int NumProtocols,
2058 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002059 const char *ClassName,
2060 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002061 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002062 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002063 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002064 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002065 // Output struct protocol_methods holder of method selector and type.
2066 if (!objc_protocol_methods &&
2067 (PDecl->getNumInstanceMethods() > 0
2068 || PDecl->getNumClassMethods() > 0)) {
2069 /* struct protocol_methods {
2070 SEL _cmd;
2071 char *method_types;
2072 }
2073 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002074 Result += "\nstruct protocol_methods {\n";
2075 Result += "\tSEL _cmd;\n";
2076 Result += "\tchar *method_types;\n";
2077 Result += "};\n";
2078
2079 /* struct _objc_protocol_method_list {
2080 int protocol_method_count;
2081 struct protocol_methods protocols[];
2082 }
2083 */
2084 Result += "\nstruct _objc_protocol_method_list {\n";
2085 Result += "\tint protocol_method_count;\n";
2086 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002087 objc_protocol_methods = true;
2088 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002089
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002090 int NumMethods = PDecl->getNumInstanceMethods();
2091 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002092 Result += "\nstatic struct _objc_protocol_method_list "
2093 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2094 Result += PDecl->getName();
2095 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2096 "{\n\t" + utostr(NumMethods) + "\n";
2097
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002098 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002099 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002100 E = PDecl->instmeth_end(); I != E; ++I) {
2101 if (I == PDecl->instmeth_begin())
2102 Result += "\t ,{{(SEL)\"";
2103 else
2104 Result += "\t ,{(SEL)\"";
2105 Result += (*I)->getSelector().getName().c_str();
2106 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002107 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002108 Result += "\", \"";
2109 Result += MethodTypeString;
2110 Result += "\"}\n";
2111 }
2112 Result += "\t }\n};\n";
2113 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002114
2115 // Output class methods declared in this protocol.
2116 NumMethods = PDecl->getNumClassMethods();
2117 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002118 Result += "\nstatic struct _objc_protocol_method_list "
2119 "_OBJC_PROTOCOL_CLASS_METHODS_";
2120 Result += PDecl->getName();
2121 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2122 "{\n\t";
2123 Result += utostr(NumMethods);
2124 Result += "\n";
2125
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002126 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002127 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002128 E = PDecl->classmeth_end(); I != E; ++I) {
2129 if (I == PDecl->classmeth_begin())
2130 Result += "\t ,{{(SEL)\"";
2131 else
2132 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002133 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002134 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002135 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002136 Result += "\", \"";
2137 Result += MethodTypeString;
2138 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002139 }
2140 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002141 }
2142 // Output:
2143 /* struct _objc_protocol {
2144 // Objective-C 1.0 extensions
2145 struct _objc_protocol_extension *isa;
2146 char *protocol_name;
2147 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002148 struct _objc_protocol_method_list *instance_methods;
2149 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002150 };
2151 */
2152 static bool objc_protocol = false;
2153 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002154 Result += "\nstruct _objc_protocol {\n";
2155 Result += "\tstruct _objc_protocol_extension *isa;\n";
2156 Result += "\tchar *protocol_name;\n";
2157 Result += "\tstruct _objc_protocol **protocol_list;\n";
2158 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2159 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2160 Result += "};\n";
2161
2162 /* struct _objc_protocol_list {
2163 struct _objc_protocol_list *next;
2164 int protocol_count;
2165 struct _objc_protocol *class_protocols[];
2166 }
2167 */
2168 Result += "\nstruct _objc_protocol_list {\n";
2169 Result += "\tstruct _objc_protocol_list *next;\n";
2170 Result += "\tint protocol_count;\n";
2171 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2172 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002173 objc_protocol = true;
2174 }
2175
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002176 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2177 Result += PDecl->getName();
2178 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2179 "{\n\t0, \"";
2180 Result += PDecl->getName();
2181 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002182 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002183 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2184 Result += PDecl->getName();
2185 Result += ", ";
2186 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002187 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002188 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002189 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002190 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2191 Result += PDecl->getName();
2192 Result += "\n";
2193 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002194 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002195 Result += "0\n";
2196 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002197 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002198 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002199 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2200 Result += prefix;
2201 Result += "_PROTOCOLS_";
2202 Result += ClassName;
2203 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2204 "{\n\t0, ";
2205 Result += utostr(NumProtocols);
2206 Result += "\n";
2207
2208 Result += "\t,{&_OBJC_PROTOCOL_";
2209 Result += Protocols[0]->getName();
2210 Result += " \n";
2211
2212 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002213 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002214 Result += "\t ,&_OBJC_PROTOCOL_";
2215 Result += PDecl->getName();
2216 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002217 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002218 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002219 }
2220}
2221
Ted Kremenek42730c52008-01-07 19:49:32 +00002222/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002223/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002224void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002225 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002226 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002227 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002228 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002229 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2230 CDecl = CDecl->getNextClassCategory())
2231 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2232 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002233
Chris Lattnera661a4d2007-12-23 01:40:15 +00002234 std::string FullCategoryName = ClassDecl->getName();
2235 FullCategoryName += '_';
2236 FullCategoryName += IDecl->getName();
2237
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002238 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002239 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002240 true, "CATEGORY_", FullCategoryName.c_str(),
2241 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002242
2243 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002244 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002245 false, "CATEGORY_", FullCategoryName.c_str(),
2246 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002247
2248 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002249 // Null CDecl is case of a category implementation with no category interface
2250 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002251 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002252 CDecl->getNumReferencedProtocols(),
2253 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002254 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002255
2256 /* struct _objc_category {
2257 char *category_name;
2258 char *class_name;
2259 struct _objc_method_list *instance_methods;
2260 struct _objc_method_list *class_methods;
2261 struct _objc_protocol_list *protocols;
2262 // Objective-C 1.0 extensions
2263 uint32_t size; // sizeof (struct _objc_category)
2264 struct _objc_property_list *instance_properties; // category's own
2265 // @property decl.
2266 };
2267 */
2268
2269 static bool objc_category = false;
2270 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002271 Result += "\nstruct _objc_category {\n";
2272 Result += "\tchar *category_name;\n";
2273 Result += "\tchar *class_name;\n";
2274 Result += "\tstruct _objc_method_list *instance_methods;\n";
2275 Result += "\tstruct _objc_method_list *class_methods;\n";
2276 Result += "\tstruct _objc_protocol_list *protocols;\n";
2277 Result += "\tunsigned int size;\n";
2278 Result += "\tstruct _objc_property_list *instance_properties;\n";
2279 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002280 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002281 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002282 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2283 Result += FullCategoryName;
2284 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2285 Result += IDecl->getName();
2286 Result += "\"\n\t, \"";
2287 Result += ClassDecl->getName();
2288 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002289
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002290 if (IDecl->getNumInstanceMethods() > 0) {
2291 Result += "\t, (struct _objc_method_list *)"
2292 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2293 Result += FullCategoryName;
2294 Result += "\n";
2295 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002296 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002297 Result += "\t, 0\n";
2298 if (IDecl->getNumClassMethods() > 0) {
2299 Result += "\t, (struct _objc_method_list *)"
2300 "&_OBJC_CATEGORY_CLASS_METHODS_";
2301 Result += FullCategoryName;
2302 Result += "\n";
2303 }
2304 else
2305 Result += "\t, 0\n";
2306
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002307 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002308 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2309 Result += FullCategoryName;
2310 Result += "\n";
2311 }
2312 else
2313 Result += "\t, 0\n";
2314 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002315}
2316
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002317/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2318/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002319void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2320 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002321 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002322 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002323 Result += IDecl->getName();
2324 Result += ", ";
2325 Result += ivar->getName();
2326 Result += ")";
2327}
2328
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002329//===----------------------------------------------------------------------===//
2330// Meta Data Emission
2331//===----------------------------------------------------------------------===//
2332
Ted Kremenek42730c52008-01-07 19:49:32 +00002333void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002334 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002335 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002336
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002337 // Explictly declared @interface's are already synthesized.
2338 if (CDecl->ImplicitInterfaceDecl()) {
2339 // FIXME: Implementation of a class with no @interface (legacy) doese not
2340 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002341 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002342 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002343
Chris Lattnerc7b06752007-12-12 07:56:42 +00002344 // Build _objc_ivar_list metadata for classes ivars if needed
2345 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2346 ? IDecl->getImplDeclNumIvars()
2347 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002348 if (NumIvars > 0) {
2349 static bool objc_ivar = false;
2350 if (!objc_ivar) {
2351 /* struct _objc_ivar {
2352 char *ivar_name;
2353 char *ivar_type;
2354 int ivar_offset;
2355 };
2356 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002357 Result += "\nstruct _objc_ivar {\n";
2358 Result += "\tchar *ivar_name;\n";
2359 Result += "\tchar *ivar_type;\n";
2360 Result += "\tint ivar_offset;\n";
2361 Result += "};\n";
2362
2363 /* struct _objc_ivar_list {
2364 int ivar_count;
2365 struct _objc_ivar ivar_list[];
2366 };
2367 */
2368 Result += "\nstruct _objc_ivar_list {\n";
2369 Result += "\tint ivar_count;\n";
2370 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002371 objc_ivar = true;
2372 }
2373
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002374 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2375 Result += IDecl->getName();
2376 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2377 "{\n\t";
2378 Result += utostr(NumIvars);
2379 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002380
Ted Kremenek42730c52008-01-07 19:49:32 +00002381 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002382 if (IDecl->getImplDeclNumIvars() > 0) {
2383 IVI = IDecl->ivar_begin();
2384 IVE = IDecl->ivar_end();
2385 } else {
2386 IVI = CDecl->ivar_begin();
2387 IVE = CDecl->ivar_end();
2388 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002389 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002390 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002391 Result += "\", \"";
2392 std::string StrEncoding;
Ted Kremenek42730c52008-01-07 19:49:32 +00002393 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002394 Result += StrEncoding;
2395 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002396 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002397 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002398 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002399 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002400 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002401 Result += "\", \"";
2402 std::string StrEncoding;
Ted Kremenek42730c52008-01-07 19:49:32 +00002403 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002404 Result += StrEncoding;
2405 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002406 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002407 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002408 }
2409
2410 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002411 }
2412
2413 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002414 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002415 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002416
2417 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002418 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002419 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002420
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002421 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002422 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002423 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002424 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002425
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002426
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002427 // Declaration of class/meta-class metadata
2428 /* struct _objc_class {
2429 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002430 const char *super_class_name;
2431 char *name;
2432 long version;
2433 long info;
2434 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002435 struct _objc_ivar_list *ivars;
2436 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002437 struct objc_cache *cache;
2438 struct objc_protocol_list *protocols;
2439 const char *ivar_layout;
2440 struct _objc_class_ext *ext;
2441 };
2442 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002443 static bool objc_class = false;
2444 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002445 Result += "\nstruct _objc_class {\n";
2446 Result += "\tstruct _objc_class *isa;\n";
2447 Result += "\tconst char *super_class_name;\n";
2448 Result += "\tchar *name;\n";
2449 Result += "\tlong version;\n";
2450 Result += "\tlong info;\n";
2451 Result += "\tlong instance_size;\n";
2452 Result += "\tstruct _objc_ivar_list *ivars;\n";
2453 Result += "\tstruct _objc_method_list *methods;\n";
2454 Result += "\tstruct objc_cache *cache;\n";
2455 Result += "\tstruct _objc_protocol_list *protocols;\n";
2456 Result += "\tconst char *ivar_layout;\n";
2457 Result += "\tstruct _objc_class_ext *ext;\n";
2458 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002459 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002460 }
2461
2462 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002463 ObjCInterfaceDecl *RootClass = 0;
2464 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002465 while (SuperClass) {
2466 RootClass = SuperClass;
2467 SuperClass = SuperClass->getSuperClass();
2468 }
2469 SuperClass = CDecl->getSuperClass();
2470
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002471 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2472 Result += CDecl->getName();
2473 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2474 "{\n\t(struct _objc_class *)\"";
2475 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2476 Result += "\"";
2477
2478 if (SuperClass) {
2479 Result += ", \"";
2480 Result += SuperClass->getName();
2481 Result += "\", \"";
2482 Result += CDecl->getName();
2483 Result += "\"";
2484 }
2485 else {
2486 Result += ", 0, \"";
2487 Result += CDecl->getName();
2488 Result += "\"";
2489 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002490 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002491 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002492 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002493 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002494 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002495 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002496 Result += "\n";
2497 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002498 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002499 Result += ", 0\n";
2500 if (CDecl->getNumIntfRefProtocols() > 0) {
2501 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2502 Result += CDecl->getName();
2503 Result += ",0,0\n";
2504 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002505 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002506 Result += "\t,0,0,0,0\n";
2507 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002508
2509 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002510 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2511 Result += CDecl->getName();
2512 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2513 "{\n\t&_OBJC_METACLASS_";
2514 Result += CDecl->getName();
2515 if (SuperClass) {
2516 Result += ", \"";
2517 Result += SuperClass->getName();
2518 Result += "\", \"";
2519 Result += CDecl->getName();
2520 Result += "\"";
2521 }
2522 else {
2523 Result += ", 0, \"";
2524 Result += CDecl->getName();
2525 Result += "\"";
2526 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002527 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002528 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002529 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002530 Result += ",0";
2531 else {
2532 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002533 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002534 Result += CDecl->getName();
2535 Result += ")";
2536 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002537 if (NumIvars > 0) {
2538 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2539 Result += CDecl->getName();
2540 Result += "\n\t";
2541 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002542 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002543 Result += ",0";
2544 if (IDecl->getNumInstanceMethods() > 0) {
2545 Result += ", &_OBJC_INSTANCE_METHODS_";
2546 Result += CDecl->getName();
2547 Result += ", 0\n\t";
2548 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002549 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002550 Result += ",0,0";
2551 if (CDecl->getNumIntfRefProtocols() > 0) {
2552 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2553 Result += CDecl->getName();
2554 Result += ", 0,0\n";
2555 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002556 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002557 Result += ",0,0,0\n";
2558 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002559}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002560
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002561/// RewriteImplementations - This routine rewrites all method implementations
2562/// and emits meta-data.
2563
2564void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002565 int ClsDefCount = ClassImplementation.size();
2566 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002567
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002568 if (ClsDefCount == 0 && CatDefCount == 0)
2569 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002570 // Rewrite implemented methods
2571 for (int i = 0; i < ClsDefCount; i++)
2572 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002573
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002574 for (int i = 0; i < CatDefCount; i++)
2575 RewriteImplementationDecl(CategoryImplementation[i]);
2576
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002577 // This is needed for use of offsetof
2578 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002579
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002580 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002581 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002582 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002583
2584 // For each implemented category, write out all its meta data.
2585 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002586 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002587
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002588 // Write objc_symtab metadata
2589 /*
2590 struct _objc_symtab
2591 {
2592 long sel_ref_cnt;
2593 SEL *refs;
2594 short cls_def_cnt;
2595 short cat_def_cnt;
2596 void *defs[cls_def_cnt + cat_def_cnt];
2597 };
2598 */
2599
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002600 Result += "\nstruct _objc_symtab {\n";
2601 Result += "\tlong sel_ref_cnt;\n";
2602 Result += "\tSEL *refs;\n";
2603 Result += "\tshort cls_def_cnt;\n";
2604 Result += "\tshort cat_def_cnt;\n";
2605 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2606 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002607
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002608 Result += "static struct _objc_symtab "
2609 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2610 Result += "\t0, 0, " + utostr(ClsDefCount)
2611 + ", " + utostr(CatDefCount) + "\n";
2612 for (int i = 0; i < ClsDefCount; i++) {
2613 Result += "\t,&_OBJC_CLASS_";
2614 Result += ClassImplementation[i]->getName();
2615 Result += "\n";
2616 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002617
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002618 for (int i = 0; i < CatDefCount; i++) {
2619 Result += "\t,&_OBJC_CATEGORY_";
2620 Result += CategoryImplementation[i]->getClassInterface()->getName();
2621 Result += "_";
2622 Result += CategoryImplementation[i]->getName();
2623 Result += "\n";
2624 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002625
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002626 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002627
2628 // Write objc_module metadata
2629
2630 /*
2631 struct _objc_module {
2632 long version;
2633 long size;
2634 const char *name;
2635 struct _objc_symtab *symtab;
2636 }
2637 */
2638
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002639 Result += "\nstruct _objc_module {\n";
2640 Result += "\tlong version;\n";
2641 Result += "\tlong size;\n";
2642 Result += "\tconst char *name;\n";
2643 Result += "\tstruct _objc_symtab *symtab;\n";
2644 Result += "};\n\n";
2645 Result += "static struct _objc_module "
2646 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002647 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2648 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002649 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002650
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002651}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002652