blob: 4cb0dce91e2b69cb973cc86629562188518381e7 [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//
5// This file was developed by Chris Lattner and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris 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"
Anton Korobeynikovb6011472007-12-23 01:19:32 +000024#include "llvm/Config/alloca.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000025#include "llvm/Support/MemoryBuffer.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000026#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000027using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000028using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000029
Chris Lattnerb429ae42007-10-11 00:43:27 +000030namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000031 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000032 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000033 Diagnostic &Diags;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000034 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000035 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000036 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000037 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000038 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000039 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
40 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000042 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +000043 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000044
45 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000046 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000047 FunctionDecl *MsgSendStretFunctionDecl;
48 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000049 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000050 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000051 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000052 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000053 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000054 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000055
Steve Naroff0add5d22007-11-03 11:27:19 +000056 // ObjC string constant support.
57 FileVarDecl *ConstantStringClassReference;
58 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000059
Steve Naroff764c1ae2007-11-15 10:28:18 +000060 // Needed for super.
61 ObjcMethodDecl *CurMethodDecl;
62 RecordDecl *SuperStructDecl;
63
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000064 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000065 public:
Ted Kremenek17861c52007-12-19 22:51:13 +000066 void Initialize(ASTContext &context) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000067 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000068 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000069 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000070 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000071 MsgSendStretFunctionDecl = 0;
72 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000073 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000074 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000075 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000076 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000077 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000078 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000079 ConstantStringClassReference = 0;
80 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000081 CurMethodDecl = 0;
82 SuperStructDecl = 0;
83
Chris Lattnerae43eb72007-12-02 01:13:47 +000084 // Get the ID and start/end of the main file.
Ted Kremenek17861c52007-12-19 22:51:13 +000085 MainFileID = SM->getMainFileID();
Chris Lattnerae43eb72007-12-02 01:13:47 +000086 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
87 MainFileStart = MainBuf->getBufferStart();
88 MainFileEnd = MainBuf->getBufferEnd();
89
90
Ted Kremenekb3ee1932007-12-11 21:27:55 +000091 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +000092 // declaring objc_selector outside the parameter list removes a silly
93 // scope related warning...
Steve Naroff8a9b95c2007-12-04 23:59:30 +000094 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000095 "#ifndef OBJC_SUPER\n"
96 "struct objc_super { struct objc_object *o; "
97 "struct objc_object *superClass; };\n"
98 "#define OBJC_SUPER\n"
99 "#endif\n"
100 "#ifndef _REWRITER_typedef_Protocol\n"
101 "typedef struct objc_object Protocol;\n"
102 "#define _REWRITER_typedef_Protocol\n"
103 "#endif\n"
Steve Narofffcab7932007-11-05 14:55:35 +0000104 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000105 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000106 "extern struct objc_object *objc_msgSendSuper"
107 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000108 "extern struct objc_object *objc_msgSend_stret"
109 "(struct objc_object *, struct objc_selector *, ...);\n"
110 "extern struct objc_object *objc_msgSendSuper_stret"
111 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000112 "extern struct objc_object *objc_msgSend_fpret"
113 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000114 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000115 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000116 "extern struct objc_object *objc_getMetaClass"
117 "(const char *);\n"
Steve Naroffd3287d82007-11-07 18:43:40 +0000118 "extern void objc_exception_throw(struct objc_object *);\n"
119 "extern void objc_exception_try_enter(void *);\n"
120 "extern void objc_exception_try_exit(void *);\n"
121 "extern struct objc_object *objc_exception_extract(void *);\n"
122 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000123 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000124 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian0079f292007-12-03 23:04:29 +0000125 "#include <objc/objc.h>\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000126
Ted Kremenek17861c52007-12-19 22:51:13 +0000127 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
Steve Naroff0744c472007-11-04 22:37:50 +0000128 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +0000129 }
Chris Lattner569faa62007-10-11 18:38:32 +0000130
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000131 // Top Level Driver code.
132 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000133 void HandleDeclInMainFile(Decl *D);
Chris Lattner258f26c2007-11-30 22:25:36 +0000134 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000135 ~RewriteTest();
136
137 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000138 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000139 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000140 void RewriteTabs();
141 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +0000142 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000143 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000144 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +0000145 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000146 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000147 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000148 void RewriteMethodDeclaration(ObjcMethodDecl *Method);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000149 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000150 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000151 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000152 bool needToScanForQualifiers(QualType T);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000153 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
154 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000155
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000156 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000157 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000158 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000159 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000160 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000161 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000162 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000163 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000164 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
165 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
166 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000167 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000168 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
169 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000170 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000171 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000172 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000173 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000174 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000175 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000176 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000177 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000178 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000179 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000180
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000181 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000182 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
183 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000184
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000185 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
186 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000187
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000188 typedef ObjcCategoryImplDecl::instmeth_iterator instmeth_iterator;
189 void RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
190 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000191 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000192 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000193 const char *ClassName,
194 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000195
196 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
197 int NumProtocols,
198 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000199 const char *ClassName,
200 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000201 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
202 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000203 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
204 ObjcIvarDecl *ivar,
205 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000206 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000207 };
208}
209
Chris Lattner258f26c2007-11-30 22:25:36 +0000210ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
211 return new RewriteTest(Diags);
212}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000213
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000214//===----------------------------------------------------------------------===//
215// Top Level Driver Code
216//===----------------------------------------------------------------------===//
217
Chris Lattner569faa62007-10-11 18:38:32 +0000218void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000219 // Two cases: either the decl could be in the main file, or it could be in a
220 // #included file. If the former, rewrite it now. If the later, check to see
221 // if we rewrote the #include/#import.
222 SourceLocation Loc = D->getLocation();
223 Loc = SM->getLogicalLoc(Loc);
224
225 // If this is for a builtin, ignore it.
226 if (Loc.isInvalid()) return;
227
Steve Naroffe9780582007-10-23 23:50:29 +0000228 // Look for built-in declarations that we need to refer during the rewrite.
229 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000230 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000231 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
232 // declared in <Foundation/NSString.h>
233 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
234 ConstantStringClassReference = FVD;
235 return;
236 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000237 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
238 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000239 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
240 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000241 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
242 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000243 } else if (ObjcForwardProtocolDecl *FP =
244 dyn_cast<ObjcForwardProtocolDecl>(D)){
245 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000246 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000247 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000248 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
249 return HandleDeclInMainFile(D);
250
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000251 // Otherwise, see if there is a #import in the main file that should be
252 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000253 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000254}
255
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000256/// HandleDeclInMainFile - This is called for each top-level decl defined in the
257/// main file of the input.
258void RewriteTest::HandleDeclInMainFile(Decl *D) {
259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
260 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000261 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000262
263 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000264 if (Stmt *Body = MD->getBody()) {
265 //Body->dump();
266 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000267 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000268 CurMethodDecl = 0;
269 }
Steve Naroff18c83382007-11-13 23:01:27 +0000270 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000271 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
272 ClassImplementation.push_back(CI);
273 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
274 CategoryImplementation.push_back(CI);
275 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
276 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000277 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +0000278 RewriteObjcQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000279 if (VD->getInit())
280 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
281 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000282 // Nothing yet.
283}
284
285RewriteTest::~RewriteTest() {
286 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000287
288 // Rewrite tabs if we care.
289 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000290
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000291 // Rewrite Objective-c meta data*
292 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000293 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000294
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000295 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
296 // we are done.
297 if (const RewriteBuffer *RewriteBuf =
298 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000299 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000300 std::string S(RewriteBuf->begin(), RewriteBuf->end());
301 printf("%s\n", S.c_str());
302 } else {
303 printf("No changes\n");
304 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000305 // Emit metadata.
306 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000307}
308
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000309//===----------------------------------------------------------------------===//
310// Syntactic (non-AST) Rewriting Code
311//===----------------------------------------------------------------------===//
312
Chris Lattner74db1682007-10-16 21:07:07 +0000313void RewriteTest::RewriteInclude(SourceLocation Loc) {
314 // Rip up the #include stack to the main file.
315 SourceLocation IncLoc = Loc, NextLoc = Loc;
316 do {
317 IncLoc = Loc;
318 Loc = SM->getLogicalLoc(NextLoc);
319 NextLoc = SM->getIncludeLoc(Loc);
320 } while (!NextLoc.isInvalid());
321
322 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
323 // IncLoc indicates the header that was included if it is useful.
324 IncLoc = SM->getLogicalLoc(IncLoc);
325 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
326 Loc == LastIncLoc)
327 return;
328 LastIncLoc = Loc;
329
330 unsigned IncCol = SM->getColumnNumber(Loc);
331 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
332
333 // Replace the #import with #include.
334 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
335}
336
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000337void RewriteTest::RewriteTabs() {
338 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
339 const char *MainBufStart = MainBuf.first;
340 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000341
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000342 // Loop over the whole file, looking for tabs.
343 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
344 if (*BufPtr != '\t')
345 continue;
346
347 // Okay, we found a tab. This tab will turn into at least one character,
348 // but it depends on which 'virtual column' it is in. Compute that now.
349 unsigned VCol = 0;
350 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
351 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
352 ++VCol;
353
354 // Okay, now that we know the virtual column, we know how many spaces to
355 // insert. We assume 8-character tab-stops.
356 unsigned Spaces = 8-(VCol & 7);
357
358 // Get the location of the tab.
359 SourceLocation TabLoc =
360 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
361
362 // Rewrite the single tab character into a sequence of spaces.
363 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
364 }
Chris Lattner569faa62007-10-11 18:38:32 +0000365}
366
367
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000368void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
369 int numDecls = ClassDecl->getNumForwardDecls();
370 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
371
372 // Get the start location and compute the semi location.
373 SourceLocation startLoc = ClassDecl->getLocation();
374 const char *startBuf = SM->getCharacterData(startLoc);
375 const char *semiPtr = strchr(startBuf, ';');
376
377 // Translate to typedef's that forward reference structs with the same name
378 // as the class. As a convenience, we include the original declaration
379 // as a comment.
380 std::string typedefString;
381 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000382 typedefString.append(startBuf, semiPtr-startBuf+1);
383 typedefString += "\n";
384 for (int i = 0; i < numDecls; i++) {
385 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000386 typedefString += "#ifndef _REWRITER_typedef_";
387 typedefString += ForwardDecl->getName();
388 typedefString += "\n";
389 typedefString += "#define _REWRITER_typedef_";
390 typedefString += ForwardDecl->getName();
391 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000392 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000393 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000394 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000395 }
396
397 // Replace the @class with typedefs corresponding to the classes.
398 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
399 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000400}
401
Steve Naroff2ce399a2007-12-14 23:37:57 +0000402void RewriteTest::RewriteMethodDeclaration(ObjcMethodDecl *Method) {
403 SourceLocation LocStart = Method->getLocStart();
404 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000405
Steve Naroff2ce399a2007-12-14 23:37:57 +0000406 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
407 Rewrite.InsertText(LocStart, "/* ", 3);
408 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
409 } else {
410 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000411 }
412}
413
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000414void RewriteTest::RewriteProperties(int nProperties, ObjcPropertyDecl **Properties)
415{
416 for (int i = 0; i < nProperties; i++) {
417 ObjcPropertyDecl *Property = Properties[i];
418 SourceLocation Loc = Property->getLocation();
419
420 Rewrite.ReplaceText(Loc, 0, "// ", 3);
421
422 // FIXME: handle properties that are declared across multiple lines.
423 }
424}
425
Steve Naroff667f1682007-10-30 13:30:57 +0000426void RewriteTest::RewriteCategoryDecl(ObjcCategoryDecl *CatDecl) {
427 SourceLocation LocStart = CatDecl->getLocStart();
428
429 // FIXME: handle category headers that are declared across multiple lines.
430 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
431
Steve Naroff2ce399a2007-12-14 23:37:57 +0000432 for (ObjcCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
433 E = CatDecl->instmeth_end(); I != E; ++I)
434 RewriteMethodDeclaration(*I);
435 for (ObjcCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
436 E = CatDecl->classmeth_end(); I != E; ++I)
437 RewriteMethodDeclaration(*I);
438
Steve Naroff667f1682007-10-30 13:30:57 +0000439 // Lastly, comment out the @end.
440 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
441}
442
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000443void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000444 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000445
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000446 SourceLocation LocStart = PDecl->getLocStart();
447
448 // FIXME: handle protocol headers that are declared across multiple lines.
449 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
450
Steve Naroff2ce399a2007-12-14 23:37:57 +0000451 for (ObjcProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
452 E = PDecl->instmeth_end(); I != E; ++I)
453 RewriteMethodDeclaration(*I);
454 for (ObjcProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
455 E = PDecl->classmeth_end(); I != E; ++I)
456 RewriteMethodDeclaration(*I);
457
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000458 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000459 SourceLocation LocEnd = PDecl->getAtEndLoc();
460 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000461
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000462 // Must comment out @optional/@required
463 const char *startBuf = SM->getCharacterData(LocStart);
464 const char *endBuf = SM->getCharacterData(LocEnd);
465 for (const char *p = startBuf; p < endBuf; p++) {
466 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
467 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000468 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000469 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
470 CommentedOptional.c_str(), CommentedOptional.size());
471
472 }
473 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
474 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000475 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000476 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
477 CommentedRequired.c_str(), CommentedRequired.size());
478
479 }
480 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000481}
482
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000483void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
484 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000485 if (LocStart.isInvalid())
486 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000487 // FIXME: handle forward protocol that are declared across multiple lines.
488 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
489}
490
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000491void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
492 std::string &ResultStr) {
493 ResultStr += "\nstatic ";
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +0000494 if (OMD->getResultType()->isObjcQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000495 ResultStr += "id";
496 else
497 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000498 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000499
500 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000501 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000502
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000503 if (OMD->isInstance())
504 NameStr += "_I_";
505 else
506 NameStr += "_C_";
507
508 NameStr += OMD->getClassInterface()->getName();
509 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000510
511 NamedDecl *MethodContext = OMD->getMethodContext();
512 if (ObjcCategoryImplDecl *CID =
513 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000514 NameStr += CID->getName();
515 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000516 }
517 // Append selector names, replacing ':' with '_'
518 const char *selName = OMD->getSelector().getName().c_str();
519 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000520 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000521 else {
522 std::string selString = OMD->getSelector().getName();
523 int len = selString.size();
524 for (int i = 0; i < len; i++)
525 if (selString[i] == ':')
526 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000527 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000528 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000529 // Remember this name for metadata emission
530 MethodInternalNames[OMD] = NameStr;
531 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000532
533 // Rewrite arguments
534 ResultStr += "(";
535
536 // invisible arguments
537 if (OMD->isInstance()) {
538 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
539 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000540 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
541 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000542 ResultStr += selfTy.getAsString();
543 }
544 else
545 ResultStr += Context->getObjcIdType().getAsString();
546
547 ResultStr += " self, ";
548 ResultStr += Context->getObjcSelType().getAsString();
549 ResultStr += " _cmd";
550
551 // Method arguments.
552 for (int i = 0; i < OMD->getNumParams(); i++) {
553 ParmVarDecl *PDecl = OMD->getParamDecl(i);
554 ResultStr += ", ";
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +0000555 if (PDecl->getType()->isObjcQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000556 ResultStr += "id";
557 else
558 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000559 ResultStr += " ";
560 ResultStr += PDecl->getName();
561 }
562 ResultStr += ")";
563
564}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000565void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
566 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
567 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000568
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000569 if (IMD)
570 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
571 else
572 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000573
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000574 for (ObjcCategoryImplDecl::instmeth_iterator
575 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
576 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000577 std::string ResultStr;
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000578 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000579 RewriteObjcMethodDecl(OMD, ResultStr);
580 SourceLocation LocStart = OMD->getLocStart();
581 SourceLocation LocEnd = OMD->getBody()->getLocStart();
582
583 const char *startBuf = SM->getCharacterData(LocStart);
584 const char *endBuf = SM->getCharacterData(LocEnd);
585 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
586 ResultStr.c_str(), ResultStr.size());
587 }
588
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000589 for (ObjcCategoryImplDecl::classmeth_iterator
590 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
591 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000592 std::string ResultStr;
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000593 ObjcMethodDecl *OMD = *I;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000594 RewriteObjcMethodDecl(OMD, ResultStr);
595 SourceLocation LocStart = OMD->getLocStart();
596 SourceLocation LocEnd = OMD->getBody()->getLocStart();
597
598 const char *startBuf = SM->getCharacterData(LocStart);
599 const char *endBuf = SM->getCharacterData(LocEnd);
600 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
601 ResultStr.c_str(), ResultStr.size());
602 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000603 if (IMD)
604 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
605 else
606 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000607}
608
Steve Naroff3774dd92007-10-26 20:53:56 +0000609void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000610 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000611 if (!ObjcForwardDecls.count(ClassDecl)) {
612 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000613 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000614 ResultStr += ClassDecl->getName();
615 ResultStr += "\n";
616 ResultStr += "#define _REWRITER_typedef_";
617 ResultStr += ClassDecl->getName();
618 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000619 ResultStr += "typedef struct ";
620 ResultStr += ClassDecl->getName();
621 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000622 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000623 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000624
625 // Mark this typedef as having been generated.
626 ObjcForwardDecls.insert(ClassDecl);
627 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000628 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
629
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000630 RewriteProperties(ClassDecl->getNumPropertyDecl(),
631 ClassDecl->getPropertyDecl());
Steve Naroff2ce399a2007-12-14 23:37:57 +0000632 for (ObjcInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
633 E = ClassDecl->instmeth_end(); I != E; ++I)
634 RewriteMethodDeclaration(*I);
635 for (ObjcInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
636 E = ClassDecl->classmeth_end(); I != E; ++I)
637 RewriteMethodDeclaration(*I);
638
Steve Naroff1ccf4632007-10-30 03:43:13 +0000639 // Lastly, comment out the @end.
640 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000641}
642
Steve Naroff6b759ce2007-11-15 02:58:25 +0000643Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
644 ObjcIvarDecl *D = IV->getDecl();
645 if (IV->isFreeIvar()) {
646 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
647 IV->getLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000648 if (Rewrite.ReplaceStmt(IV, Replacement)) {
649 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000650 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
651 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000652 SourceRange Range = IV->getSourceRange();
653 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000654 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000655 delete IV;
656 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000657 } else {
658 if (CurMethodDecl) {
659 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
660 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
661 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
662 IdentifierInfo *II = intT->getDecl()->getIdentifier();
663 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
664 II, 0);
665 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
666
667 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
668 // Don't forget the parens to enforce the proper binding.
669 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000670 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
671 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000672 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
673 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000674 SourceRange Range = IV->getBase()->getSourceRange();
675 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000676 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000677 delete IV->getBase();
678 return PE;
679 }
680 }
681 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000682 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000683 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000684}
685
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000686//===----------------------------------------------------------------------===//
687// Function Body / Expression rewriting
688//===----------------------------------------------------------------------===//
689
Steve Naroff334fbc22007-11-09 15:20:18 +0000690Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000691 // Otherwise, just rewrite all children.
692 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
693 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000694 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000695 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000696 if (newStmt)
697 *CI = newStmt;
698 }
Steve Naroffe9780582007-10-23 23:50:29 +0000699
700 // Handle specific things.
701 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
702 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000703
704 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
705 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000706
707 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
708 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000709
710 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
711 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000712
Steve Naroff71226032007-10-24 22:48:43 +0000713 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
714 // Before we rewrite it, put the original message expression in a comment.
715 SourceLocation startLoc = MessExpr->getLocStart();
716 SourceLocation endLoc = MessExpr->getLocEnd();
717
718 const char *startBuf = SM->getCharacterData(startLoc);
719 const char *endBuf = SM->getCharacterData(endLoc);
720
721 std::string messString;
722 messString += "// ";
723 messString.append(startBuf, endBuf-startBuf+1);
724 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000725
Steve Naroff71226032007-10-24 22:48:43 +0000726 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
727 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
728 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000729 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000730 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000731 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000732
733 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
734 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000735
736 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
737 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000738
739 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
740 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000741#if 0
742 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
743 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
744 // Get the new text.
745 std::ostringstream Buf;
746 Replacement->printPretty(Buf);
747 const std::string &Str = Buf.str();
748
749 printf("CAST = %s\n", &Str[0]);
750 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
751 delete S;
752 return Replacement;
753 }
754#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000755 // Return this stmt unmodified.
756 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000757}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000758
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000759Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000760 // Get the start location and compute the semi location.
761 SourceLocation startLoc = S->getLocStart();
762 const char *startBuf = SM->getCharacterData(startLoc);
763
764 assert((*startBuf == '@') && "bogus @try location");
765
766 std::string buf;
767 // declare a new scope with two variables, _stack and _rethrow.
768 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
769 buf += "int buf[18/*32-bit i386*/];\n";
770 buf += "char *pointers[4];} _stack;\n";
771 buf += "id volatile _rethrow = 0;\n";
772 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000773 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000774
775 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
776
777 startLoc = S->getTryBody()->getLocEnd();
778 startBuf = SM->getCharacterData(startLoc);
779
780 assert((*startBuf == '}') && "bogus @try block");
781
782 SourceLocation lastCurlyLoc = startLoc;
783
784 startLoc = startLoc.getFileLocWithOffset(1);
785 buf = " /* @catch begin */ else {\n";
786 buf += " id _caught = objc_exception_extract(&_stack);\n";
787 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000788 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000789 buf += " _rethrow = objc_exception_extract(&_stack);\n";
790 buf += " else { /* @catch continue */";
791
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000792 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000793
794 bool sawIdTypedCatch = false;
795 Stmt *lastCatchBody = 0;
796 ObjcAtCatchStmt *catchList = S->getCatchStmts();
797 while (catchList) {
798 Stmt *catchStmt = catchList->getCatchParamStmt();
799
800 if (catchList == S->getCatchStmts())
801 buf = "if ("; // we are generating code for the first catch clause
802 else
803 buf = "else if (";
804 startLoc = catchList->getLocStart();
805 startBuf = SM->getCharacterData(startLoc);
806
807 assert((*startBuf == '@') && "bogus @catch location");
808
809 const char *lParenLoc = strchr(startBuf, '(');
810
811 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
812 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
813 if (t == Context->getObjcIdType()) {
814 buf += "1) { ";
815 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
816 buf.c_str(), buf.size());
817 sawIdTypedCatch = true;
818 } else if (const PointerType *pType = t->getAsPointerType()) {
819 ObjcInterfaceType *cls; // Should be a pointer to a class.
820
821 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
822 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000823 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000824 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000825 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000826 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
827 buf.c_str(), buf.size());
828 }
829 }
830 // Now rewrite the body...
831 lastCatchBody = catchList->getCatchBody();
832 SourceLocation rParenLoc = catchList->getRParenLoc();
833 SourceLocation bodyLoc = lastCatchBody->getLocStart();
834 const char *bodyBuf = SM->getCharacterData(bodyLoc);
835 const char *rParenBuf = SM->getCharacterData(rParenLoc);
836 assert((*rParenBuf == ')') && "bogus @catch paren location");
837 assert((*bodyBuf == '{') && "bogus @catch body location");
838
839 buf = " = _caught;";
840 // Here we replace ") {" with "= _caught;" (which initializes and
841 // declares the @catch parameter).
842 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
843 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000844 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000845 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000846 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000847 catchList = catchList->getNextCatchStmt();
848 }
849 // Complete the catch list...
850 if (lastCatchBody) {
851 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
852 const char *bodyBuf = SM->getCharacterData(bodyLoc);
853 assert((*bodyBuf == '}') && "bogus @catch body location");
854 bodyLoc = bodyLoc.getFileLocWithOffset(1);
855 buf = " } } /* @catch end */\n";
856
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000857 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000858
859 // Set lastCurlyLoc
860 lastCurlyLoc = lastCatchBody->getLocEnd();
861 }
862 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
863 startLoc = finalStmt->getLocStart();
864 startBuf = SM->getCharacterData(startLoc);
865 assert((*startBuf == '@') && "bogus @finally start");
866
867 buf = "/* @finally */";
868 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
869
870 Stmt *body = finalStmt->getFinallyBody();
871 SourceLocation startLoc = body->getLocStart();
872 SourceLocation endLoc = body->getLocEnd();
873 const char *startBuf = SM->getCharacterData(startLoc);
874 const char *endBuf = SM->getCharacterData(endLoc);
875 assert((*startBuf == '{') && "bogus @finally body location");
876 assert((*endBuf == '}') && "bogus @finally body location");
877
878 startLoc = startLoc.getFileLocWithOffset(1);
879 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000880 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000881 endLoc = endLoc.getFileLocWithOffset(-1);
882 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000883 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000884
885 // Set lastCurlyLoc
886 lastCurlyLoc = body->getLocEnd();
887 }
888 // Now emit the final closing curly brace...
889 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
890 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000891 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000892 return 0;
893}
894
895Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
896 return 0;
897}
898
899Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
900 return 0;
901}
902
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000903// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
904// the throw expression is typically a message expression that's already
905// been rewritten! (which implies the SourceLocation's are invalid).
906Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
907 // Get the start location and compute the semi location.
908 SourceLocation startLoc = S->getLocStart();
909 const char *startBuf = SM->getCharacterData(startLoc);
910
911 assert((*startBuf == '@') && "bogus @throw location");
912
913 std::string buf;
914 /* void objc_exception_throw(id) __attribute__((noreturn)); */
915 buf = "objc_exception_throw(";
916 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
917 const char *semiBuf = strchr(startBuf, ';');
918 assert((*semiBuf == ';') && "@throw: can't find ';'");
919 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
920 buf = ");";
921 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
922 return 0;
923}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000924
Chris Lattner0021f452007-10-24 16:57:36 +0000925Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000926 // Create a new string expression.
927 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000928 std::string StrEncoding;
929 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
930 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
931 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000932 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000933 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
934 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000935 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
936 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner217df512007-12-02 01:09:57 +0000937 SourceRange Range = Exp->getSourceRange();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000938 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattner258f26c2007-11-30 22:25:36 +0000939 }
940
Chris Lattner4478db92007-11-30 22:53:43 +0000941 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000942 delete Exp;
943 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000944}
945
Steve Naroff296b74f2007-11-05 14:50:49 +0000946Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
947 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
948 // Create a call to sel_registerName("selName").
949 llvm::SmallVector<Expr*, 8> SelExprs;
950 QualType argType = Context->getPointerType(Context->CharTy);
951 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
952 Exp->getSelector().getName().size(),
953 false, argType, SourceLocation(),
954 SourceLocation()));
955 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
956 &SelExprs[0], SelExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000957 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
958 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +0000959 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
960 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +0000961 SourceRange Range = Exp->getSourceRange();
962 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000963 }
Steve Naroff296b74f2007-11-05 14:50:49 +0000964 delete Exp;
965 return SelExp;
966}
967
Steve Naroff71226032007-10-24 22:48:43 +0000968CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
969 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000970 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000971 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000972
973 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000974 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000975
976 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000977 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000978 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
979
980 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000981
Steve Naroff71226032007-10-24 22:48:43 +0000982 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
983}
984
Steve Naroffc8a92d12007-11-01 13:24:47 +0000985static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
986 const char *&startRef, const char *&endRef) {
987 while (startBuf < endBuf) {
988 if (*startBuf == '<')
989 startRef = startBuf; // mark the start.
990 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000991 if (startRef && *startRef == '<') {
992 endRef = startBuf; // mark the end.
993 return true;
994 }
995 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000996 }
997 startBuf++;
998 }
999 return false;
1000}
1001
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001002static void scanToNextArgument(const char *&argRef) {
1003 int angle = 0;
1004 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1005 if (*argRef == '<')
1006 angle++;
1007 else if (*argRef == '>')
1008 angle--;
1009 argRef++;
1010 }
1011 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1012}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001013
Steve Naroffc8a92d12007-11-01 13:24:47 +00001014bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001015
Steve Naroffc8a92d12007-11-01 13:24:47 +00001016 if (T == Context->getObjcIdType())
1017 return true;
1018
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001019 if (T->isObjcQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001020 return true;
1021
Steve Naroffc8a92d12007-11-01 13:24:47 +00001022 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001023 Type *pointeeType = pType->getPointeeType().getTypePtr();
1024 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
1025 return true; // we have "Class <Protocol> *".
1026 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001027 return false;
1028}
1029
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001030void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001031 SourceLocation Loc;
1032 QualType Type;
1033 const FunctionTypeProto *proto = 0;
1034 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1035 Loc = VD->getLocation();
1036 Type = VD->getType();
1037 }
1038 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1039 Loc = FD->getLocation();
1040 // Check for ObjC 'id' and class types that have been adorned with protocol
1041 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1042 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1043 assert(funcType && "missing function type");
1044 proto = dyn_cast<FunctionTypeProto>(funcType);
1045 if (!proto)
1046 return;
1047 Type = proto->getResultType();
1048 }
1049 else
1050 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001051
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001052 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001053 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001054
1055 const char *endBuf = SM->getCharacterData(Loc);
1056 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001057 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001058 startBuf--; // scan backward (from the decl location) for return type.
1059 const char *startRef = 0, *endRef = 0;
1060 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1061 // Get the locations of the startRef, endRef.
1062 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1063 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1064 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001065 Rewrite.InsertText(LessLoc, "/*", 2);
1066 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001067 }
1068 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001069 if (!proto)
1070 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001071 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001072 const char *startBuf = SM->getCharacterData(Loc);
1073 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001074 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1075 if (needToScanForQualifiers(proto->getArgType(i))) {
1076 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001077
Steve Naroffc8a92d12007-11-01 13:24:47 +00001078 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001079 // scan forward (from the decl location) for argument types.
1080 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001081 const char *startRef = 0, *endRef = 0;
1082 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1083 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001084 SourceLocation LessLoc =
1085 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1086 SourceLocation GreaterLoc =
1087 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001088 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001089 Rewrite.InsertText(LessLoc, "/*", 2);
1090 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001091 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001092 startBuf = ++endBuf;
1093 }
1094 else {
1095 while (*startBuf != ')' && *startBuf != ',')
1096 startBuf++; // scan forward (from the decl location) for argument types.
1097 startBuf++;
1098 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001099 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001100}
1101
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001102// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1103void RewriteTest::SynthSelGetUidFunctionDecl() {
1104 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1105 llvm::SmallVector<QualType, 16> ArgTys;
1106 ArgTys.push_back(Context->getPointerType(
1107 Context->CharTy.getQualifiedType(QualType::Const)));
1108 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1109 &ArgTys[0], ArgTys.size(),
1110 false /*isVariadic*/);
1111 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1112 SelGetUidIdent, getFuncType,
1113 FunctionDecl::Extern, false, 0);
1114}
1115
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001116// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1117void RewriteTest::SynthGetProtocolFunctionDecl() {
1118 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1119 llvm::SmallVector<QualType, 16> ArgTys;
1120 ArgTys.push_back(Context->getPointerType(
1121 Context->CharTy.getQualifiedType(QualType::Const)));
1122 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1123 &ArgTys[0], ArgTys.size(),
1124 false /*isVariadic*/);
1125 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1126 SelGetProtoIdent, getFuncType,
1127 FunctionDecl::Extern, false, 0);
1128}
1129
Steve Naroff02a82aa2007-10-30 23:14:51 +00001130void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1131 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001132 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001133 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001134 return;
1135 }
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001136 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001137}
1138
1139// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1140void RewriteTest::SynthMsgSendFunctionDecl() {
1141 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1142 llvm::SmallVector<QualType, 16> ArgTys;
1143 QualType argT = Context->getObjcIdType();
1144 assert(!argT.isNull() && "Can't find 'id' type");
1145 ArgTys.push_back(argT);
1146 argT = Context->getObjcSelType();
1147 assert(!argT.isNull() && "Can't find 'SEL' type");
1148 ArgTys.push_back(argT);
1149 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1150 &ArgTys[0], ArgTys.size(),
1151 true /*isVariadic*/);
1152 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1153 msgSendIdent, msgSendType,
1154 FunctionDecl::Extern, false, 0);
1155}
1156
Steve Naroff764c1ae2007-11-15 10:28:18 +00001157// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1158void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1159 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1160 llvm::SmallVector<QualType, 16> ArgTys;
1161 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1162 &Context->Idents.get("objc_super"), 0);
1163 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1164 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1165 ArgTys.push_back(argT);
1166 argT = Context->getObjcSelType();
1167 assert(!argT.isNull() && "Can't find 'SEL' type");
1168 ArgTys.push_back(argT);
1169 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1170 &ArgTys[0], ArgTys.size(),
1171 true /*isVariadic*/);
1172 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1173 msgSendIdent, msgSendType,
1174 FunctionDecl::Extern, false, 0);
1175}
1176
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001177// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1178void RewriteTest::SynthMsgSendStretFunctionDecl() {
1179 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1180 llvm::SmallVector<QualType, 16> ArgTys;
1181 QualType argT = Context->getObjcIdType();
1182 assert(!argT.isNull() && "Can't find 'id' type");
1183 ArgTys.push_back(argT);
1184 argT = Context->getObjcSelType();
1185 assert(!argT.isNull() && "Can't find 'SEL' type");
1186 ArgTys.push_back(argT);
1187 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1188 &ArgTys[0], ArgTys.size(),
1189 true /*isVariadic*/);
1190 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1191 msgSendIdent, msgSendType,
1192 FunctionDecl::Extern, false, 0);
1193}
1194
1195// SynthMsgSendSuperStretFunctionDecl -
1196// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1197void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1198 IdentifierInfo *msgSendIdent =
1199 &Context->Idents.get("objc_msgSendSuper_stret");
1200 llvm::SmallVector<QualType, 16> ArgTys;
1201 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1202 &Context->Idents.get("objc_super"), 0);
1203 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1204 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1205 ArgTys.push_back(argT);
1206 argT = Context->getObjcSelType();
1207 assert(!argT.isNull() && "Can't find 'SEL' type");
1208 ArgTys.push_back(argT);
1209 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1210 &ArgTys[0], ArgTys.size(),
1211 true /*isVariadic*/);
1212 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1213 msgSendIdent, msgSendType,
1214 FunctionDecl::Extern, false, 0);
1215}
1216
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001217// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1218void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1219 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1220 llvm::SmallVector<QualType, 16> ArgTys;
1221 QualType argT = Context->getObjcIdType();
1222 assert(!argT.isNull() && "Can't find 'id' type");
1223 ArgTys.push_back(argT);
1224 argT = Context->getObjcSelType();
1225 assert(!argT.isNull() && "Can't find 'SEL' type");
1226 ArgTys.push_back(argT);
1227 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1228 &ArgTys[0], ArgTys.size(),
1229 true /*isVariadic*/);
1230 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1231 msgSendIdent, msgSendType,
1232 FunctionDecl::Extern, false, 0);
1233}
1234
Steve Naroff02a82aa2007-10-30 23:14:51 +00001235// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1236void RewriteTest::SynthGetClassFunctionDecl() {
1237 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1238 llvm::SmallVector<QualType, 16> ArgTys;
1239 ArgTys.push_back(Context->getPointerType(
1240 Context->CharTy.getQualifiedType(QualType::Const)));
1241 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1242 &ArgTys[0], ArgTys.size(),
1243 false /*isVariadic*/);
1244 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1245 getClassIdent, getClassType,
1246 FunctionDecl::Extern, false, 0);
1247}
1248
Steve Naroff3b1caac2007-12-07 03:50:46 +00001249// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1250void RewriteTest::SynthGetMetaClassFunctionDecl() {
1251 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1252 llvm::SmallVector<QualType, 16> ArgTys;
1253 ArgTys.push_back(Context->getPointerType(
1254 Context->CharTy.getQualifiedType(QualType::Const)));
1255 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1256 &ArgTys[0], ArgTys.size(),
1257 false /*isVariadic*/);
1258 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1259 getClassIdent, getClassType,
1260 FunctionDecl::Extern, false, 0);
1261}
1262
Steve Naroffabb96362007-11-08 14:30:50 +00001263// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1264void RewriteTest::SynthCFStringFunctionDecl() {
1265 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1266 llvm::SmallVector<QualType, 16> ArgTys;
1267 ArgTys.push_back(Context->getPointerType(
1268 Context->CharTy.getQualifiedType(QualType::Const)));
1269 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1270 &ArgTys[0], ArgTys.size(),
1271 false /*isVariadic*/);
1272 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1273 getClassIdent, getClassType,
1274 FunctionDecl::Extern, false, 0);
1275}
1276
Steve Naroff0add5d22007-11-03 11:27:19 +00001277Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001278#if 1
1279 // This rewrite is specific to GCC, which has builtin support for CFString.
1280 if (!CFStringFunctionDecl)
1281 SynthCFStringFunctionDecl();
1282 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1283 llvm::SmallVector<Expr*, 8> StrExpr;
1284 StrExpr.push_back(Exp->getString());
1285 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1286 &StrExpr[0], StrExpr.size());
1287 // cast to NSConstantString *
1288 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001289 if (Rewrite.ReplaceStmt(Exp, cast)) {
1290 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001291 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1292 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001293 SourceRange Range = Exp->getSourceRange();
1294 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001295 }
Steve Naroffabb96362007-11-08 14:30:50 +00001296 delete Exp;
1297 return cast;
1298#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001299 assert(ConstantStringClassReference && "Can't find constant string reference");
1300 llvm::SmallVector<Expr*, 4> InitExprs;
1301
1302 // Synthesize "(Class)&_NSConstantStringClassReference"
1303 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1304 ConstantStringClassReference->getType(),
1305 SourceLocation());
1306 QualType expType = Context->getPointerType(ClsRef->getType());
1307 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1308 expType, SourceLocation());
1309 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1310 SourceLocation());
1311 InitExprs.push_back(cast); // set the 'isa'.
1312 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1313 unsigned IntSize = static_cast<unsigned>(
1314 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1315 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1316 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1317 Exp->getLocStart());
1318 InitExprs.push_back(len); // set "int numBytes".
1319
1320 // struct NSConstantString
1321 QualType CFConstantStrType = Context->getCFConstantStringType();
1322 // (struct NSConstantString) { <exprs from above> }
1323 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1324 &InitExprs[0], InitExprs.size(),
1325 SourceLocation());
1326 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1327 // struct NSConstantString *
1328 expType = Context->getPointerType(StrRep->getType());
1329 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1330 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001331 // cast to NSConstantString *
1332 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001333 Rewrite.ReplaceStmt(Exp, cast);
1334 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001335 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001336#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001337}
1338
Steve Naroff764c1ae2007-11-15 10:28:18 +00001339ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001340 // check if we are sending a message to 'super'
1341 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001342 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1343 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1344 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1345 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001346 // is this id<P1..> type?
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001347 if (CE->getType()->isObjcQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001348 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001349 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1350 if (ObjcInterfaceType *IT =
1351 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1352 if (IT->getDecl() ==
1353 CurMethodDecl->getClassInterface()->getSuperClass())
1354 return IT->getDecl();
1355 }
1356 }
1357 }
1358 }
1359 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001360 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001361 }
1362 return 0;
1363}
1364
1365// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1366QualType RewriteTest::getSuperStructType() {
1367 if (!SuperStructDecl) {
1368 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1369 &Context->Idents.get("objc_super"), 0);
1370 QualType FieldTypes[2];
1371
1372 // struct objc_object *receiver;
1373 FieldTypes[0] = Context->getObjcIdType();
1374 // struct objc_class *super;
1375 FieldTypes[1] = Context->getObjcClassType();
1376 // Create fields
1377 FieldDecl *FieldDecls[2];
1378
1379 for (unsigned i = 0; i < 2; ++i)
1380 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1381
1382 SuperStructDecl->defineBody(FieldDecls, 4);
1383 }
1384 return Context->getTagDeclType(SuperStructDecl);
1385}
1386
Steve Naroff71226032007-10-24 22:48:43 +00001387Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001388 if (!SelGetUidFunctionDecl)
1389 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001390 if (!MsgSendFunctionDecl)
1391 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001392 if (!MsgSendSuperFunctionDecl)
1393 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001394 if (!MsgSendStretFunctionDecl)
1395 SynthMsgSendStretFunctionDecl();
1396 if (!MsgSendSuperStretFunctionDecl)
1397 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001398 if (!MsgSendFpretFunctionDecl)
1399 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001400 if (!GetClassFunctionDecl)
1401 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001402 if (!GetMetaClassFunctionDecl)
1403 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001404
Steve Naroff764c1ae2007-11-15 10:28:18 +00001405 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001406 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1407 // May need to use objc_msgSend_stret() as well.
1408 FunctionDecl *MsgSendStretFlavor = 0;
1409 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1410 QualType resultType = mDecl->getResultType();
1411 if (resultType.getCanonicalType()->isStructureType()
1412 || resultType.getCanonicalType()->isUnionType())
1413 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001414 else if (resultType.getCanonicalType()->isRealFloatingType())
1415 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001416 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001417
Steve Naroff71226032007-10-24 22:48:43 +00001418 // Synthesize a call to objc_msgSend().
1419 llvm::SmallVector<Expr*, 8> MsgExprs;
1420 IdentifierInfo *clsName = Exp->getClassName();
1421
1422 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1423 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001424 if (!strcmp(clsName->getName(), "super")) {
1425 MsgSendFlavor = MsgSendSuperFunctionDecl;
1426 if (MsgSendStretFlavor)
1427 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1428 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1429
1430 ObjcInterfaceDecl *SuperDecl =
1431 CurMethodDecl->getClassInterface()->getSuperClass();
1432
1433 llvm::SmallVector<Expr*, 4> InitExprs;
1434
1435 // set the receiver to self, the first argument to all methods.
1436 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1437 Context->getObjcIdType(),
1438 SourceLocation()));
1439 llvm::SmallVector<Expr*, 8> ClsExprs;
1440 QualType argType = Context->getPointerType(Context->CharTy);
1441 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1442 SuperDecl->getIdentifier()->getLength(),
1443 false, argType, SourceLocation(),
1444 SourceLocation()));
1445 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1446 &ClsExprs[0],
1447 ClsExprs.size());
1448 // To turn off a warning, type-cast to 'id'
1449 InitExprs.push_back(
1450 new CastExpr(Context->getObjcIdType(),
1451 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1452 // struct objc_super
1453 QualType superType = getSuperStructType();
1454 // (struct objc_super) { <exprs from above> }
1455 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1456 &InitExprs[0], InitExprs.size(),
1457 SourceLocation());
1458 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1459 // struct objc_super *
1460 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1461 Context->getPointerType(SuperRep->getType()),
1462 SourceLocation());
1463 MsgExprs.push_back(Unop);
1464 } else {
1465 llvm::SmallVector<Expr*, 8> ClsExprs;
1466 QualType argType = Context->getPointerType(Context->CharTy);
1467 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1468 clsName->getLength(),
1469 false, argType, SourceLocation(),
1470 SourceLocation()));
1471 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1472 &ClsExprs[0],
1473 ClsExprs.size());
1474 MsgExprs.push_back(Cls);
1475 }
Steve Naroff885e2122007-11-14 23:54:14 +00001476 } else { // instance message.
1477 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001478
Steve Naroff3b1caac2007-12-07 03:50:46 +00001479 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001480 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001481 if (MsgSendStretFlavor)
1482 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001483 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1484
1485 llvm::SmallVector<Expr*, 4> InitExprs;
1486
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001487 InitExprs.push_back(
1488 new CastExpr(Context->getObjcIdType(),
1489 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001490
1491 llvm::SmallVector<Expr*, 8> ClsExprs;
1492 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001493 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1494 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001495 false, argType, SourceLocation(),
1496 SourceLocation()));
1497 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001498 &ClsExprs[0],
1499 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001500 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001501 InitExprs.push_back(
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001502 new CastExpr(Context->getObjcIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001503 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001504 // struct objc_super
1505 QualType superType = getSuperStructType();
1506 // (struct objc_super) { <exprs from above> }
1507 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1508 &InitExprs[0], InitExprs.size(),
1509 SourceLocation());
1510 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1511 // struct objc_super *
1512 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1513 Context->getPointerType(SuperRep->getType()),
1514 SourceLocation());
1515 MsgExprs.push_back(Unop);
1516 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001517 // Remove all type-casts because it may contain objc-style types; e.g.
1518 // Foo<Proto> *.
1519 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1520 recExpr = CE->getSubExpr();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001521 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1522 MsgExprs.push_back(recExpr);
1523 }
Steve Naroff885e2122007-11-14 23:54:14 +00001524 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001525 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001526 llvm::SmallVector<Expr*, 8> SelExprs;
1527 QualType argType = Context->getPointerType(Context->CharTy);
1528 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1529 Exp->getSelector().getName().size(),
1530 false, argType, SourceLocation(),
1531 SourceLocation()));
1532 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1533 &SelExprs[0], SelExprs.size());
1534 MsgExprs.push_back(SelExp);
1535
1536 // Now push any user supplied arguments.
1537 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001538 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001539 // Make all implicit casts explicit...ICE comes in handy:-)
1540 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1541 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001542 userExpr = new CastExpr(ICE->getType()->isObjcQualifiedIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001543 ? Context->getObjcIdType()
1544 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001545 }
1546 // Make id<P...> cast into an 'id' cast.
1547 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
1548 if (CE->getType()->isObjcQualifiedIdType()) {
1549 while ((CE = dyn_cast<CastExpr>(userExpr)))
1550 userExpr = CE->getSubExpr();
1551 userExpr = new CastExpr(Context->getObjcIdType(),
1552 userExpr, SourceLocation());
1553 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001554 }
Steve Naroff885e2122007-11-14 23:54:14 +00001555 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001556 // We've transferred the ownership to MsgExprs. Null out the argument in
1557 // the original expression, since we will delete it below.
1558 Exp->setArg(i, 0);
1559 }
Steve Naroff0744c472007-11-04 22:37:50 +00001560 // Generate the funky cast.
1561 CastExpr *cast;
1562 llvm::SmallVector<QualType, 8> ArgTypes;
1563 QualType returnType;
1564
1565 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001566 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1567 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1568 else
1569 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001570 ArgTypes.push_back(Context->getObjcSelType());
1571 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1572 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001573 for (int i = 0; i < mDecl->getNumParams(); i++) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001574 QualType t = mDecl->getParamDecl(i)->getType()->isObjcQualifiedIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001575 ? Context->getObjcIdType()
1576 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001577 ArgTypes.push_back(t);
1578 }
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001579 returnType = mDecl->getResultType()->isObjcQualifiedIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001580 ? Context->getObjcIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00001581 } else {
1582 returnType = Context->getObjcIdType();
1583 }
1584 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001585 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001586
1587 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001588 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1589 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001590
1591 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1592 // If we don't do this cast, we get the following bizarre warning/note:
1593 // xx.m:13: warning: function called through a non-compatible type
1594 // xx.m:13: note: if this code is reached, the program will abort
1595 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1596 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001597
Steve Naroff0744c472007-11-04 22:37:50 +00001598 // Now do the "normal" pointer to function cast.
1599 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001600 &ArgTypes[0], ArgTypes.size(),
1601 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001602 castType = Context->getPointerType(castType);
1603 cast = new CastExpr(castType, cast, SourceLocation());
1604
1605 // Don't forget the parens to enforce the proper binding.
1606 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1607
1608 const FunctionType *FT = msgSendType->getAsFunctionType();
1609 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1610 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001611 if (MsgSendStretFlavor) {
1612 // We have the method which returns a struct/union. Must also generate
1613 // call to objc_msgSend_stret and hang both varieties on a conditional
1614 // expression which dictate which one to envoke depending on size of
1615 // method's return type.
1616
1617 // Create a reference to the objc_msgSend_stret() declaration.
1618 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1619 SourceLocation());
1620 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1621 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1622 SourceLocation());
1623 // Now do the "normal" pointer to function cast.
1624 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001625 &ArgTypes[0], ArgTypes.size(),
1626 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001627 castType = Context->getPointerType(castType);
1628 cast = new CastExpr(castType, cast, SourceLocation());
1629
1630 // Don't forget the parens to enforce the proper binding.
1631 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1632
1633 FT = msgSendType->getAsFunctionType();
1634 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1635 FT->getResultType(), SourceLocation());
1636
1637 // Build sizeof(returnType)
1638 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1639 returnType, Context->getSizeType(),
1640 SourceLocation(), SourceLocation());
1641 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1642 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1643 // For X86 it is more complicated and some kind of target specific routine
1644 // is needed to decide what to do.
1645 unsigned IntSize = static_cast<unsigned>(
1646 Context->getTypeSize(Context->IntTy, SourceLocation()));
1647
1648 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1649 Context->IntTy,
1650 SourceLocation());
1651 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1652 BinaryOperator::LE,
1653 Context->IntTy,
1654 SourceLocation());
1655 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1656 ConditionalOperator *CondExpr =
1657 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1658 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1659 // Now do the actual rewrite.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001660 if (Rewrite.ReplaceStmt(Exp, PE)) {
1661 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001662 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1663 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001664 SourceRange Range = Exp->getSourceRange();
1665 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001666 }
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001667 delete Exp;
1668 return PE;
1669 }
Steve Naroff71226032007-10-24 22:48:43 +00001670 // Now do the actual rewrite.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001671 if (Rewrite.ReplaceStmt(Exp, CE)) {
1672 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001673 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1674 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001675 SourceRange Range = Exp->getSourceRange();
1676 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001677 }
Steve Naroff71226032007-10-24 22:48:43 +00001678
Chris Lattner0021f452007-10-24 16:57:36 +00001679 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001680 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001681}
1682
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001683/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1684/// call to objc_getProtocol("proto-name").
1685Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1686 if (!GetProtocolFunctionDecl)
1687 SynthGetProtocolFunctionDecl();
1688 // Create a call to objc_getProtocol("ProtocolName").
1689 llvm::SmallVector<Expr*, 8> ProtoExprs;
1690 QualType argType = Context->getPointerType(Context->CharTy);
1691 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1692 strlen(Exp->getProtocol()->getName()),
1693 false, argType, SourceLocation(),
1694 SourceLocation()));
1695 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1696 &ProtoExprs[0],
1697 ProtoExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001698 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1699 // replacement failed.
Steve Naroffbcf0a922007-12-19 19:16:49 +00001700 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1701 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroffe4e5e262007-12-19 14:32:56 +00001702 SourceRange Range = Exp->getSourceRange();
1703 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001704 }
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001705 delete Exp;
1706 return ProtoExp;
1707
1708}
1709
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001710/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1711/// an objective-c class with ivars.
1712void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1713 std::string &Result) {
1714 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1715 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001716 // Do not synthesize more than once.
1717 if (ObjcSynthesizedStructs.count(CDecl))
1718 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001719 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001720 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001721 SourceLocation LocStart = CDecl->getLocStart();
1722 SourceLocation LocEnd = CDecl->getLocEnd();
1723
1724 const char *startBuf = SM->getCharacterData(LocStart);
1725 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001726 // If no ivars and no root or if its root, directly or indirectly,
1727 // have no ivars (thus not synthesized) then no need to synthesize this class.
1728 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001729 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1730 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1731 Result.c_str(), Result.size());
1732 return;
1733 }
1734
1735 // FIXME: This has potential of causing problem. If
1736 // SynthesizeObjcInternalStruct is ever called recursively.
1737 Result += "\nstruct ";
1738 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001739
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001740 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001741 const char *cursor = strchr(startBuf, '{');
1742 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001743 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001744
1745 // rewrite the original header *without* disturbing the '{'
1746 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1747 Result.c_str(), Result.size());
1748 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1749 Result = "\n struct ";
1750 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001751 // Note: We don't name the field decl. This simplifies the "codegen" for
1752 // accessing a superclasses instance variables (and is similar to what gcc
1753 // does internally). The unnamed struct field feature is enabled with
1754 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1755 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001756 Result += ";\n";
1757
1758 // insert the super class structure definition.
1759 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1760 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1761 }
1762 cursor++; // past '{'
1763
1764 // Now comment out any visibility specifiers.
1765 while (cursor < endBuf) {
1766 if (*cursor == '@') {
1767 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001768 // Skip whitespace.
1769 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1770 /*scan*/;
1771
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001772 // FIXME: presence of @public, etc. inside comment results in
1773 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001774 if (!strncmp(cursor, "public", strlen("public")) ||
1775 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001776 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001777 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001778 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001779 // FIXME: If there are cases where '<' is used in ivar declaration part
1780 // of user code, then scan the ivar list and use needToScanForQualifiers
1781 // for type checking.
1782 else if (*cursor == '<') {
1783 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1784 Rewrite.InsertText(atLoc, "/* ", 3);
1785 cursor = strchr(cursor, '>');
1786 cursor++;
1787 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1788 Rewrite.InsertText(atLoc, " */", 3);
1789 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001790 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001791 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001792 // Don't forget to add a ';'!!
1793 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1794 } else { // we don't have any instance variables - insert super struct.
1795 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1796 Result += " {\n struct ";
1797 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001798 // Note: We don't name the field decl. This simplifies the "codegen" for
1799 // accessing a superclasses instance variables (and is similar to what gcc
1800 // does internally). The unnamed struct field feature is enabled with
1801 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1802 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001803 Result += ";\n};\n";
1804 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1805 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001806 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001807 // Mark this struct as having been generated.
1808 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001809 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001810}
1811
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001812// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1813/// class methods.
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001814void RewriteTest::RewriteObjcMethodsMetaData(instmeth_iterator MethodBegin,
1815 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001816 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001817 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001818 const char *ClassName,
1819 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001820 if (MethodBegin == MethodEnd) return;
1821
Fariborz Jahanian04455192007-10-22 21:41:37 +00001822 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001823 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001824 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001825 SEL _cmd;
1826 char *method_types;
1827 void *_imp;
1828 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001829 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001830 Result += "\nstruct _objc_method {\n";
1831 Result += "\tSEL _cmd;\n";
1832 Result += "\tchar *method_types;\n";
1833 Result += "\tvoid *_imp;\n";
1834 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001835
1836 /* struct _objc_method_list {
1837 struct _objc_method_list *next_method;
1838 int method_count;
1839 struct _objc_method method_list[];
1840 }
1841 */
1842 Result += "\nstruct _objc_method_list {\n";
1843 Result += "\tstruct _objc_method_list *next_method;\n";
1844 Result += "\tint method_count;\n";
1845 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001846 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001847 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001848
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001849 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001850 Result += "\nstatic struct _objc_method_list _OBJC_";
1851 Result += prefix;
1852 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1853 Result += "_METHODS_";
1854 Result += ClassName;
1855 Result += " __attribute__ ((section (\"__OBJC, __";
1856 Result += IsInstanceMethod ? "inst" : "cls";
1857 Result += "_meth\")))= ";
1858 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001859
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001860 Result += "\t,{{(SEL)\"";
1861 Result += (*MethodBegin)->getSelector().getName().c_str();
1862 std::string MethodTypeString;
1863 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
1864 Result += "\", \"";
1865 Result += MethodTypeString;
1866 Result += "\", ";
1867 Result += MethodInternalNames[*MethodBegin];
1868 Result += "}\n";
1869 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
1870 Result += "\t ,{(SEL)\"";
1871 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001872 std::string MethodTypeString;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001873 Context->getObjcEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001874 Result += "\", \"";
1875 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001876 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001877 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001878 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001879 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00001880 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001881}
1882
1883/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1884void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1885 int NumProtocols,
1886 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001887 const char *ClassName,
1888 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001889 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001890 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001891 for (int i = 0; i < NumProtocols; i++) {
1892 ObjcProtocolDecl *PDecl = Protocols[i];
1893 // Output struct protocol_methods holder of method selector and type.
1894 if (!objc_protocol_methods &&
1895 (PDecl->getNumInstanceMethods() > 0
1896 || PDecl->getNumClassMethods() > 0)) {
1897 /* struct protocol_methods {
1898 SEL _cmd;
1899 char *method_types;
1900 }
1901 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001902 Result += "\nstruct protocol_methods {\n";
1903 Result += "\tSEL _cmd;\n";
1904 Result += "\tchar *method_types;\n";
1905 Result += "};\n";
1906
1907 /* struct _objc_protocol_method_list {
1908 int protocol_method_count;
1909 struct protocol_methods protocols[];
1910 }
1911 */
1912 Result += "\nstruct _objc_protocol_method_list {\n";
1913 Result += "\tint protocol_method_count;\n";
1914 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001915 objc_protocol_methods = true;
1916 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001917
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00001918 int NumMethods = PDecl->getNumInstanceMethods();
1919 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001920 Result += "\nstatic struct _objc_protocol_method_list "
1921 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1922 Result += PDecl->getName();
1923 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1924 "{\n\t" + utostr(NumMethods) + "\n";
1925
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00001926 // Output instance methods declared in this protocol.
1927 for (ObjcProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1928 E = PDecl->instmeth_end(); I != E; ++I) {
1929 if (I == PDecl->instmeth_begin())
1930 Result += "\t ,{{(SEL)\"";
1931 else
1932 Result += "\t ,{(SEL)\"";
1933 Result += (*I)->getSelector().getName().c_str();
1934 std::string MethodTypeString;
1935 Context->getObjcEncodingForMethodDecl((*I), MethodTypeString);
1936 Result += "\", \"";
1937 Result += MethodTypeString;
1938 Result += "\"}\n";
1939 }
1940 Result += "\t }\n};\n";
1941 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001942
1943 // Output class methods declared in this protocol.
1944 NumMethods = PDecl->getNumClassMethods();
1945 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001946 Result += "\nstatic struct _objc_protocol_method_list "
1947 "_OBJC_PROTOCOL_CLASS_METHODS_";
1948 Result += PDecl->getName();
1949 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1950 "{\n\t";
1951 Result += utostr(NumMethods);
1952 Result += "\n";
1953
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00001954 // Output instance methods declared in this protocol.
1955 for (ObjcProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
1956 E = PDecl->classmeth_end(); I != E; ++I) {
1957 if (I == PDecl->classmeth_begin())
1958 Result += "\t ,{{(SEL)\"";
1959 else
1960 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00001961 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001962 std::string MethodTypeString;
Steve Naroff2ce399a2007-12-14 23:37:57 +00001963 Context->getObjcEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001964 Result += "\", \"";
1965 Result += MethodTypeString;
1966 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001967 }
1968 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001969 }
1970 // Output:
1971 /* struct _objc_protocol {
1972 // Objective-C 1.0 extensions
1973 struct _objc_protocol_extension *isa;
1974 char *protocol_name;
1975 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001976 struct _objc_protocol_method_list *instance_methods;
1977 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001978 };
1979 */
1980 static bool objc_protocol = false;
1981 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001982 Result += "\nstruct _objc_protocol {\n";
1983 Result += "\tstruct _objc_protocol_extension *isa;\n";
1984 Result += "\tchar *protocol_name;\n";
1985 Result += "\tstruct _objc_protocol **protocol_list;\n";
1986 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1987 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1988 Result += "};\n";
1989
1990 /* struct _objc_protocol_list {
1991 struct _objc_protocol_list *next;
1992 int protocol_count;
1993 struct _objc_protocol *class_protocols[];
1994 }
1995 */
1996 Result += "\nstruct _objc_protocol_list {\n";
1997 Result += "\tstruct _objc_protocol_list *next;\n";
1998 Result += "\tint protocol_count;\n";
1999 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2000 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002001 objc_protocol = true;
2002 }
2003
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002004 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2005 Result += PDecl->getName();
2006 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2007 "{\n\t0, \"";
2008 Result += PDecl->getName();
2009 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002010 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002011 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2012 Result += PDecl->getName();
2013 Result += ", ";
2014 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002015 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002016 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002017 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002018 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2019 Result += PDecl->getName();
2020 Result += "\n";
2021 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002022 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002023 Result += "0\n";
2024 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002025 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002026 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002027 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2028 Result += prefix;
2029 Result += "_PROTOCOLS_";
2030 Result += ClassName;
2031 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2032 "{\n\t0, ";
2033 Result += utostr(NumProtocols);
2034 Result += "\n";
2035
2036 Result += "\t,{&_OBJC_PROTOCOL_";
2037 Result += Protocols[0]->getName();
2038 Result += " \n";
2039
2040 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002041 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002042 Result += "\t ,&_OBJC_PROTOCOL_";
2043 Result += PDecl->getName();
2044 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002045 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002046 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002047 }
2048}
2049
2050/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
2051/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002052void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
2053 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002054 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
2055 // Find category declaration for this implementation.
2056 ObjcCategoryDecl *CDecl;
2057 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2058 CDecl = CDecl->getNextClassCategory())
2059 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2060 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002061
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002062 char *FullCategoryName = (char*)alloca(
2063 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
2064 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
2065
2066 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002067 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2068 true, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002069
2070 // Build _objc_method_list for class's class methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002071 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2072 false, "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002073
2074 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002075 // Null CDecl is case of a category implementation with no category interface
2076 if (CDecl)
2077 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2078 CDecl->getNumReferencedProtocols(),
2079 "CATEGORY",
2080 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002081
2082 /* struct _objc_category {
2083 char *category_name;
2084 char *class_name;
2085 struct _objc_method_list *instance_methods;
2086 struct _objc_method_list *class_methods;
2087 struct _objc_protocol_list *protocols;
2088 // Objective-C 1.0 extensions
2089 uint32_t size; // sizeof (struct _objc_category)
2090 struct _objc_property_list *instance_properties; // category's own
2091 // @property decl.
2092 };
2093 */
2094
2095 static bool objc_category = false;
2096 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002097 Result += "\nstruct _objc_category {\n";
2098 Result += "\tchar *category_name;\n";
2099 Result += "\tchar *class_name;\n";
2100 Result += "\tstruct _objc_method_list *instance_methods;\n";
2101 Result += "\tstruct _objc_method_list *class_methods;\n";
2102 Result += "\tstruct _objc_protocol_list *protocols;\n";
2103 Result += "\tunsigned int size;\n";
2104 Result += "\tstruct _objc_property_list *instance_properties;\n";
2105 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002106 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002107 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002108 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2109 Result += FullCategoryName;
2110 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2111 Result += IDecl->getName();
2112 Result += "\"\n\t, \"";
2113 Result += ClassDecl->getName();
2114 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002115
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002116 if (IDecl->getNumInstanceMethods() > 0) {
2117 Result += "\t, (struct _objc_method_list *)"
2118 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2119 Result += FullCategoryName;
2120 Result += "\n";
2121 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002122 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002123 Result += "\t, 0\n";
2124 if (IDecl->getNumClassMethods() > 0) {
2125 Result += "\t, (struct _objc_method_list *)"
2126 "&_OBJC_CATEGORY_CLASS_METHODS_";
2127 Result += FullCategoryName;
2128 Result += "\n";
2129 }
2130 else
2131 Result += "\t, 0\n";
2132
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002133 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002134 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2135 Result += FullCategoryName;
2136 Result += "\n";
2137 }
2138 else
2139 Result += "\t, 0\n";
2140 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002141}
2142
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002143/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2144/// ivar offset.
2145void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2146 ObjcIvarDecl *ivar,
2147 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002148 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002149 Result += IDecl->getName();
2150 Result += ", ";
2151 Result += ivar->getName();
2152 Result += ")";
2153}
2154
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002155//===----------------------------------------------------------------------===//
2156// Meta Data Emission
2157//===----------------------------------------------------------------------===//
2158
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002159void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2160 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002161 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2162
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002163 // Explictly declared @interface's are already synthesized.
2164 if (CDecl->ImplicitInterfaceDecl()) {
2165 // FIXME: Implementation of a class with no @interface (legacy) doese not
2166 // produce correct synthesis as yet.
2167 SynthesizeObjcInternalStruct(CDecl, Result);
2168 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002169
Chris Lattnerc7b06752007-12-12 07:56:42 +00002170 // Build _objc_ivar_list metadata for classes ivars if needed
2171 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2172 ? IDecl->getImplDeclNumIvars()
2173 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002174 if (NumIvars > 0) {
2175 static bool objc_ivar = false;
2176 if (!objc_ivar) {
2177 /* struct _objc_ivar {
2178 char *ivar_name;
2179 char *ivar_type;
2180 int ivar_offset;
2181 };
2182 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002183 Result += "\nstruct _objc_ivar {\n";
2184 Result += "\tchar *ivar_name;\n";
2185 Result += "\tchar *ivar_type;\n";
2186 Result += "\tint ivar_offset;\n";
2187 Result += "};\n";
2188
2189 /* struct _objc_ivar_list {
2190 int ivar_count;
2191 struct _objc_ivar ivar_list[];
2192 };
2193 */
2194 Result += "\nstruct _objc_ivar_list {\n";
2195 Result += "\tint ivar_count;\n";
2196 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002197 objc_ivar = true;
2198 }
2199
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002200 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2201 Result += IDecl->getName();
2202 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2203 "{\n\t";
2204 Result += utostr(NumIvars);
2205 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002206
2207 ObjcInterfaceDecl::ivar_iterator IVI, IVE;
2208 if (IDecl->getImplDeclNumIvars() > 0) {
2209 IVI = IDecl->ivar_begin();
2210 IVE = IDecl->ivar_end();
2211 } else {
2212 IVI = CDecl->ivar_begin();
2213 IVE = CDecl->ivar_end();
2214 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002215 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002216 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002217 Result += "\", \"";
2218 std::string StrEncoding;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002219 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002220 Result += StrEncoding;
2221 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002222 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002223 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002224 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002225 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002226 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002227 Result += "\", \"";
2228 std::string StrEncoding;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002229 Context->getObjcEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002230 Result += StrEncoding;
2231 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002232 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002233 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002234 }
2235
2236 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002237 }
2238
2239 // Build _objc_method_list for class's instance methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002240 RewriteObjcMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
2241 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002242
2243 // Build _objc_method_list for class's class methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002244 RewriteObjcMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
2245 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002246
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002247 // Protocols referenced in class declaration?
2248 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2249 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002250 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002251
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002252
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002253 // Declaration of class/meta-class metadata
2254 /* struct _objc_class {
2255 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002256 const char *super_class_name;
2257 char *name;
2258 long version;
2259 long info;
2260 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002261 struct _objc_ivar_list *ivars;
2262 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002263 struct objc_cache *cache;
2264 struct objc_protocol_list *protocols;
2265 const char *ivar_layout;
2266 struct _objc_class_ext *ext;
2267 };
2268 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002269 static bool objc_class = false;
2270 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002271 Result += "\nstruct _objc_class {\n";
2272 Result += "\tstruct _objc_class *isa;\n";
2273 Result += "\tconst char *super_class_name;\n";
2274 Result += "\tchar *name;\n";
2275 Result += "\tlong version;\n";
2276 Result += "\tlong info;\n";
2277 Result += "\tlong instance_size;\n";
2278 Result += "\tstruct _objc_ivar_list *ivars;\n";
2279 Result += "\tstruct _objc_method_list *methods;\n";
2280 Result += "\tstruct objc_cache *cache;\n";
2281 Result += "\tstruct _objc_protocol_list *protocols;\n";
2282 Result += "\tconst char *ivar_layout;\n";
2283 Result += "\tstruct _objc_class_ext *ext;\n";
2284 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002285 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002286 }
2287
2288 // Meta-class metadata generation.
2289 ObjcInterfaceDecl *RootClass = 0;
2290 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2291 while (SuperClass) {
2292 RootClass = SuperClass;
2293 SuperClass = SuperClass->getSuperClass();
2294 }
2295 SuperClass = CDecl->getSuperClass();
2296
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002297 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2298 Result += CDecl->getName();
2299 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2300 "{\n\t(struct _objc_class *)\"";
2301 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2302 Result += "\"";
2303
2304 if (SuperClass) {
2305 Result += ", \"";
2306 Result += SuperClass->getName();
2307 Result += "\", \"";
2308 Result += CDecl->getName();
2309 Result += "\"";
2310 }
2311 else {
2312 Result += ", 0, \"";
2313 Result += CDecl->getName();
2314 Result += "\"";
2315 }
Fariborz Jahanian771d3b92007-12-04 19:31:56 +00002316 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002317 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002318 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002319 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002320 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002321 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002322 Result += "\n";
2323 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002324 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002325 Result += ", 0\n";
2326 if (CDecl->getNumIntfRefProtocols() > 0) {
2327 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2328 Result += CDecl->getName();
2329 Result += ",0,0\n";
2330 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002331 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002332 Result += "\t,0,0,0,0\n";
2333 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002334
2335 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002336 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2337 Result += CDecl->getName();
2338 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2339 "{\n\t&_OBJC_METACLASS_";
2340 Result += CDecl->getName();
2341 if (SuperClass) {
2342 Result += ", \"";
2343 Result += SuperClass->getName();
2344 Result += "\", \"";
2345 Result += CDecl->getName();
2346 Result += "\"";
2347 }
2348 else {
2349 Result += ", 0, \"";
2350 Result += CDecl->getName();
2351 Result += "\"";
2352 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002353 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002354 Result += ", 0,1";
2355 if (!ObjcSynthesizedStructs.count(CDecl))
2356 Result += ",0";
2357 else {
2358 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002359 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002360 Result += CDecl->getName();
2361 Result += ")";
2362 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002363 if (NumIvars > 0) {
2364 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2365 Result += CDecl->getName();
2366 Result += "\n\t";
2367 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002368 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002369 Result += ",0";
2370 if (IDecl->getNumInstanceMethods() > 0) {
2371 Result += ", &_OBJC_INSTANCE_METHODS_";
2372 Result += CDecl->getName();
2373 Result += ", 0\n\t";
2374 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002375 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002376 Result += ",0,0";
2377 if (CDecl->getNumIntfRefProtocols() > 0) {
2378 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2379 Result += CDecl->getName();
2380 Result += ", 0,0\n";
2381 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002382 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002383 Result += ",0,0,0\n";
2384 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002385}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002386
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002387/// RewriteImplementations - This routine rewrites all method implementations
2388/// and emits meta-data.
2389
2390void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002391 int ClsDefCount = ClassImplementation.size();
2392 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002393
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002394 if (ClsDefCount == 0 && CatDefCount == 0)
2395 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002396 // Rewrite implemented methods
2397 for (int i = 0; i < ClsDefCount; i++)
2398 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002399
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002400 for (int i = 0; i < CatDefCount; i++)
2401 RewriteImplementationDecl(CategoryImplementation[i]);
2402
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002403 // This is needed for use of offsetof
2404 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002405
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002406 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002407 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002408 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002409
2410 // For each implemented category, write out all its meta data.
2411 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002412 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002413
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002414 // Write objc_symtab metadata
2415 /*
2416 struct _objc_symtab
2417 {
2418 long sel_ref_cnt;
2419 SEL *refs;
2420 short cls_def_cnt;
2421 short cat_def_cnt;
2422 void *defs[cls_def_cnt + cat_def_cnt];
2423 };
2424 */
2425
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002426 Result += "\nstruct _objc_symtab {\n";
2427 Result += "\tlong sel_ref_cnt;\n";
2428 Result += "\tSEL *refs;\n";
2429 Result += "\tshort cls_def_cnt;\n";
2430 Result += "\tshort cat_def_cnt;\n";
2431 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2432 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002433
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002434 Result += "static struct _objc_symtab "
2435 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2436 Result += "\t0, 0, " + utostr(ClsDefCount)
2437 + ", " + utostr(CatDefCount) + "\n";
2438 for (int i = 0; i < ClsDefCount; i++) {
2439 Result += "\t,&_OBJC_CLASS_";
2440 Result += ClassImplementation[i]->getName();
2441 Result += "\n";
2442 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002443
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002444 for (int i = 0; i < CatDefCount; i++) {
2445 Result += "\t,&_OBJC_CATEGORY_";
2446 Result += CategoryImplementation[i]->getClassInterface()->getName();
2447 Result += "_";
2448 Result += CategoryImplementation[i]->getName();
2449 Result += "\n";
2450 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002451
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002452 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002453
2454 // Write objc_module metadata
2455
2456 /*
2457 struct _objc_module {
2458 long version;
2459 long size;
2460 const char *name;
2461 struct _objc_symtab *symtab;
2462 }
2463 */
2464
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002465 Result += "\nstruct _objc_module {\n";
2466 Result += "\tlong version;\n";
2467 Result += "\tlong size;\n";
2468 Result += "\tconst char *name;\n";
2469 Result += "\tstruct _objc_symtab *symtab;\n";
2470 Result += "};\n\n";
2471 Result += "static struct _objc_module "
2472 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002473 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2474 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002475 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002476
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002477}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002478