blob: cc10ab0d383958390ba4ccc7698c4ca3a29eaccc [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"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000025#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000026using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000028
Chris Lattnerb429ae42007-10-11 00:43:27 +000029namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000038 llvm::SmallVector<ObjcImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjcCategoryImplDecl *, 8> CategoryImplementation;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000040 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcSynthesizedStructs;
Steve Naroff809b4f02007-10-31 22:11:35 +000041 llvm::SmallPtrSet<ObjcInterfaceDecl*, 8> ObjcForwardDecls;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +000042 llvm::DenseMap<ObjcMethodDecl*, std::string> MethodInternalNames;
Steve Naroffe9780582007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000054
Steve Naroff0add5d22007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000058
Steve Naroff764c1ae2007-11-15 10:28:18 +000059 // Needed for super.
60 ObjcMethodDecl *CurMethodDecl;
61 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000064 public:
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000065 void Initialize(ASTContext &context, unsigned mainFileID) {
66 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattnerae43eb72007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
84 MainFileID = mainFileID;
85 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenekb3ee1932007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff8a9b95c2007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000094 "#ifndef OBJC_SUPER\n"
95 "struct objc_super { struct objc_object *o; "
96 "struct objc_object *superClass; };\n"
97 "#define OBJC_SUPER\n"
98 "#endif\n"
99 "#ifndef _REWRITER_typedef_Protocol\n"
100 "typedef struct objc_object Protocol;\n"
101 "#define _REWRITER_typedef_Protocol\n"
102 "#endif\n"
Steve Narofffcab7932007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000107 "extern struct objc_object *objc_msgSend_stret"
108 "(struct objc_object *, struct objc_selector *, ...);\n"
109 "extern struct objc_object *objc_msgSendSuper_stret"
110 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroffd3287d82007-11-07 18:43:40 +0000117 "extern void objc_exception_throw(struct objc_object *);\n"
118 "extern void objc_exception_try_enter(void *);\n"
119 "extern void objc_exception_try_exit(void *);\n"
120 "extern struct objc_object *objc_exception_extract(void *);\n"
121 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian0079f292007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000125
Steve Naroff0744c472007-11-04 22:37:50 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(mainFileID, 0),
127 s, strlen(s));
Chris Lattnerb429ae42007-10-11 00:43:27 +0000128 }
Chris Lattner569faa62007-10-11 18:38:32 +0000129
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattner258f26c2007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000139 void RewriteTabs();
140 void RewriteForwardClassDecl(ObjcClassDecl *Dcl);
Steve Naroff3774dd92007-10-26 20:53:56 +0000141 void RewriteInterfaceDecl(ObjcInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000143 void RewriteObjcMethodDecl(ObjcMethodDecl *MDecl, std::string &ResultStr);
Steve Naroff667f1682007-10-30 13:30:57 +0000144 void RewriteCategoryDecl(ObjcCategoryDecl *Dcl);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000145 void RewriteProtocolDecl(ObjcProtocolDecl *Dcl);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000146 void RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *Dcl);
Steve Naroff18c83382007-11-13 23:01:27 +0000147 void RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods);
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000148 void RewriteProperties(int nProperties, ObjcPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000150 void RewriteObjcQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000152 ObjcInterfaceDecl *isSuperReceiver(Expr *recExpr);
153 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000154
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000163 Stmt *RewriteObjcTryStmt(ObjcAtTryStmt *S);
164 Stmt *RewriteObjcCatchStmt(ObjcAtCatchStmt *S);
165 Stmt *RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000166 Stmt *RewriteObjcThrowStmt(ObjcAtThrowStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000179
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000180 // Metadata emission.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000181 void RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
182 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000183
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000184 void RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *CDecl,
185 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000186
Steve Naroffb82c50f2007-11-11 17:19:15 +0000187 void RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000188 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000189 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000190 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000191 const char *ClassName,
192 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000193
194 void RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
195 int NumProtocols,
196 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000197 const char *ClassName,
198 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000199 void SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
200 std::string &Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000201 void SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
202 ObjcIvarDecl *ivar,
203 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000204 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000205 };
206}
207
Chris Lattner258f26c2007-11-30 22:25:36 +0000208ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
209 return new RewriteTest(Diags);
210}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000211
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000212//===----------------------------------------------------------------------===//
213// Top Level Driver Code
214//===----------------------------------------------------------------------===//
215
Chris Lattner569faa62007-10-11 18:38:32 +0000216void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000217 // Two cases: either the decl could be in the main file, or it could be in a
218 // #included file. If the former, rewrite it now. If the later, check to see
219 // if we rewrote the #include/#import.
220 SourceLocation Loc = D->getLocation();
221 Loc = SM->getLogicalLoc(Loc);
222
223 // If this is for a builtin, ignore it.
224 if (Loc.isInvalid()) return;
225
Steve Naroffe9780582007-10-23 23:50:29 +0000226 // Look for built-in declarations that we need to refer during the rewrite.
227 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000228 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000229 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
230 // declared in <Foundation/NSString.h>
231 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
232 ConstantStringClassReference = FVD;
233 return;
234 }
Steve Naroff3774dd92007-10-26 20:53:56 +0000235 } else if (ObjcInterfaceDecl *MD = dyn_cast<ObjcInterfaceDecl>(D)) {
236 RewriteInterfaceDecl(MD);
Steve Naroff667f1682007-10-30 13:30:57 +0000237 } else if (ObjcCategoryDecl *CD = dyn_cast<ObjcCategoryDecl>(D)) {
238 RewriteCategoryDecl(CD);
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000239 } else if (ObjcProtocolDecl *PD = dyn_cast<ObjcProtocolDecl>(D)) {
240 RewriteProtocolDecl(PD);
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000241 } else if (ObjcForwardProtocolDecl *FP =
242 dyn_cast<ObjcForwardProtocolDecl>(D)){
243 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000244 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000245 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000246 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
247 return HandleDeclInMainFile(D);
248
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000249 // Otherwise, see if there is a #import in the main file that should be
250 // rewritten.
Steve Naroff2aeae312007-11-09 12:50:28 +0000251 //RewriteInclude(Loc);
Chris Lattner74db1682007-10-16 21:07:07 +0000252}
253
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000254/// HandleDeclInMainFile - This is called for each top-level decl defined in the
255/// main file of the input.
256void RewriteTest::HandleDeclInMainFile(Decl *D) {
257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
258 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000259 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff18c83382007-11-13 23:01:27 +0000260
261 if (ObjcMethodDecl *MD = dyn_cast<ObjcMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000262 if (Stmt *Body = MD->getBody()) {
263 //Body->dump();
264 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000265 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000266 CurMethodDecl = 0;
267 }
Steve Naroff18c83382007-11-13 23:01:27 +0000268 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000269 if (ObjcImplementationDecl *CI = dyn_cast<ObjcImplementationDecl>(D))
270 ClassImplementation.push_back(CI);
271 else if (ObjcCategoryImplDecl *CI = dyn_cast<ObjcCategoryImplDecl>(D))
272 CategoryImplementation.push_back(CI);
273 else if (ObjcClassDecl *CD = dyn_cast<ObjcClassDecl>(D))
274 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000275 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
276 if (VD->getInit())
277 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
278 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000279 // Nothing yet.
280}
281
282RewriteTest::~RewriteTest() {
283 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000284
285 // Rewrite tabs if we care.
286 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000287
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000288 // Rewrite Objective-c meta data*
289 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000290 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000291
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000292 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
293 // we are done.
294 if (const RewriteBuffer *RewriteBuf =
295 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000296 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000297 std::string S(RewriteBuf->begin(), RewriteBuf->end());
298 printf("%s\n", S.c_str());
299 } else {
300 printf("No changes\n");
301 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000302 // Emit metadata.
303 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000304}
305
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000306//===----------------------------------------------------------------------===//
307// Syntactic (non-AST) Rewriting Code
308//===----------------------------------------------------------------------===//
309
Chris Lattner74db1682007-10-16 21:07:07 +0000310void RewriteTest::RewriteInclude(SourceLocation Loc) {
311 // Rip up the #include stack to the main file.
312 SourceLocation IncLoc = Loc, NextLoc = Loc;
313 do {
314 IncLoc = Loc;
315 Loc = SM->getLogicalLoc(NextLoc);
316 NextLoc = SM->getIncludeLoc(Loc);
317 } while (!NextLoc.isInvalid());
318
319 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
320 // IncLoc indicates the header that was included if it is useful.
321 IncLoc = SM->getLogicalLoc(IncLoc);
322 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
323 Loc == LastIncLoc)
324 return;
325 LastIncLoc = Loc;
326
327 unsigned IncCol = SM->getColumnNumber(Loc);
328 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
329
330 // Replace the #import with #include.
331 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
332}
333
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000334void RewriteTest::RewriteTabs() {
335 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
336 const char *MainBufStart = MainBuf.first;
337 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000338
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000339 // Loop over the whole file, looking for tabs.
340 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
341 if (*BufPtr != '\t')
342 continue;
343
344 // Okay, we found a tab. This tab will turn into at least one character,
345 // but it depends on which 'virtual column' it is in. Compute that now.
346 unsigned VCol = 0;
347 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
348 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
349 ++VCol;
350
351 // Okay, now that we know the virtual column, we know how many spaces to
352 // insert. We assume 8-character tab-stops.
353 unsigned Spaces = 8-(VCol & 7);
354
355 // Get the location of the tab.
356 SourceLocation TabLoc =
357 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
358
359 // Rewrite the single tab character into a sequence of spaces.
360 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
361 }
Chris Lattner569faa62007-10-11 18:38:32 +0000362}
363
364
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000365void RewriteTest::RewriteForwardClassDecl(ObjcClassDecl *ClassDecl) {
366 int numDecls = ClassDecl->getNumForwardDecls();
367 ObjcInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
368
369 // Get the start location and compute the semi location.
370 SourceLocation startLoc = ClassDecl->getLocation();
371 const char *startBuf = SM->getCharacterData(startLoc);
372 const char *semiPtr = strchr(startBuf, ';');
373
374 // Translate to typedef's that forward reference structs with the same name
375 // as the class. As a convenience, we include the original declaration
376 // as a comment.
377 std::string typedefString;
378 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000379 typedefString.append(startBuf, semiPtr-startBuf+1);
380 typedefString += "\n";
381 for (int i = 0; i < numDecls; i++) {
382 ObjcInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000383 typedefString += "#ifndef _REWRITER_typedef_";
384 typedefString += ForwardDecl->getName();
385 typedefString += "\n";
386 typedefString += "#define _REWRITER_typedef_";
387 typedefString += ForwardDecl->getName();
388 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000389 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000390 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000391 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000392 }
393
394 // Replace the @class with typedefs corresponding to the classes.
395 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
396 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000397}
398
Steve Naroff18c83382007-11-13 23:01:27 +0000399void RewriteTest::RewriteMethodDeclarations(int nMethods, ObjcMethodDecl **Methods) {
Steve Naroff667f1682007-10-30 13:30:57 +0000400 for (int i = 0; i < nMethods; i++) {
401 ObjcMethodDecl *Method = Methods[i];
Steve Narofffbfb46d2007-11-14 14:34:23 +0000402 SourceLocation LocStart = Method->getLocStart();
403 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000404
Steve Narofffbfb46d2007-11-14 14:34:23 +0000405 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
406 Rewrite.InsertText(LocStart, "/* ", 3);
407 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
408 } else {
409 Rewrite.InsertText(LocStart, "// ", 3);
410 }
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 Naroff18c83382007-11-13 23:01:27 +0000432 RewriteMethodDeclarations(CatDecl->getNumInstanceMethods(),
433 CatDecl->getInstanceMethods());
434 RewriteMethodDeclarations(CatDecl->getNumClassMethods(),
435 CatDecl->getClassMethods());
Steve Naroff667f1682007-10-30 13:30:57 +0000436 // Lastly, comment out the @end.
437 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
438}
439
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000440void RewriteTest::RewriteProtocolDecl(ObjcProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000441 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000442
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000443 SourceLocation LocStart = PDecl->getLocStart();
444
445 // FIXME: handle protocol headers that are declared across multiple lines.
446 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
447
Steve Naroff18c83382007-11-13 23:01:27 +0000448 RewriteMethodDeclarations(PDecl->getNumInstanceMethods(),
449 PDecl->getInstanceMethods());
450 RewriteMethodDeclarations(PDecl->getNumClassMethods(),
451 PDecl->getClassMethods());
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000452 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000453 SourceLocation LocEnd = PDecl->getAtEndLoc();
454 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000455
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000456 // Must comment out @optional/@required
457 const char *startBuf = SM->getCharacterData(LocStart);
458 const char *endBuf = SM->getCharacterData(LocEnd);
459 for (const char *p = startBuf; p < endBuf; p++) {
460 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
461 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000462 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000463 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
464 CommentedOptional.c_str(), CommentedOptional.size());
465
466 }
467 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
468 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000469 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000470 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
471 CommentedRequired.c_str(), CommentedRequired.size());
472
473 }
474 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000475}
476
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000477void RewriteTest::RewriteForwardProtocolDecl(ObjcForwardProtocolDecl *PDecl) {
478 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000479 if (LocStart.isInvalid())
480 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000481 // FIXME: handle forward protocol that are declared across multiple lines.
482 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
483}
484
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000485void RewriteTest::RewriteObjcMethodDecl(ObjcMethodDecl *OMD,
486 std::string &ResultStr) {
487 ResultStr += "\nstatic ";
488 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000489 ResultStr += "\n";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000490
491 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000492 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000493
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000494 if (OMD->isInstance())
495 NameStr += "_I_";
496 else
497 NameStr += "_C_";
498
499 NameStr += OMD->getClassInterface()->getName();
500 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000501
502 NamedDecl *MethodContext = OMD->getMethodContext();
503 if (ObjcCategoryImplDecl *CID =
504 dyn_cast<ObjcCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000505 NameStr += CID->getName();
506 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000507 }
508 // Append selector names, replacing ':' with '_'
509 const char *selName = OMD->getSelector().getName().c_str();
510 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000511 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000512 else {
513 std::string selString = OMD->getSelector().getName();
514 int len = selString.size();
515 for (int i = 0; i < len; i++)
516 if (selString[i] == ':')
517 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000518 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000519 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000520 // Remember this name for metadata emission
521 MethodInternalNames[OMD] = NameStr;
522 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000523
524 // Rewrite arguments
525 ResultStr += "(";
526
527 // invisible arguments
528 if (OMD->isInstance()) {
529 QualType selfTy = Context->getObjcInterfaceType(OMD->getClassInterface());
530 selfTy = Context->getPointerType(selfTy);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000531 if (ObjcSynthesizedStructs.count(OMD->getClassInterface()))
532 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000533 ResultStr += selfTy.getAsString();
534 }
535 else
536 ResultStr += Context->getObjcIdType().getAsString();
537
538 ResultStr += " self, ";
539 ResultStr += Context->getObjcSelType().getAsString();
540 ResultStr += " _cmd";
541
542 // Method arguments.
543 for (int i = 0; i < OMD->getNumParams(); i++) {
544 ParmVarDecl *PDecl = OMD->getParamDecl(i);
545 ResultStr += ", ";
546 ResultStr += PDecl->getType().getAsString();
547 ResultStr += " ";
548 ResultStr += PDecl->getName();
549 }
550 ResultStr += ")";
551
552}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000553void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
554 ObjcImplementationDecl *IMD = dyn_cast<ObjcImplementationDecl>(OID);
555 ObjcCategoryImplDecl *CID = dyn_cast<ObjcCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000556
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000557 if (IMD)
558 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
559 else
560 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000561
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000562 int numMethods = IMD ? IMD->getNumInstanceMethods()
563 : CID->getNumInstanceMethods();
564
565 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000566 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000567 ObjcMethodDecl *OMD;
568 if (IMD)
569 OMD = IMD->getInstanceMethods()[i];
570 else
571 OMD = CID->getInstanceMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000572 RewriteObjcMethodDecl(OMD, ResultStr);
573 SourceLocation LocStart = OMD->getLocStart();
574 SourceLocation LocEnd = OMD->getBody()->getLocStart();
575
576 const char *startBuf = SM->getCharacterData(LocStart);
577 const char *endBuf = SM->getCharacterData(LocEnd);
578 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
579 ResultStr.c_str(), ResultStr.size());
580 }
581
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000582 numMethods = IMD ? IMD->getNumClassMethods() : CID->getNumClassMethods();
583 for (int i = 0; i < numMethods; i++) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000584 std::string ResultStr;
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000585 ObjcMethodDecl *OMD;
586 if (IMD)
587 OMD = IMD->getClassMethods()[i];
588 else
589 OMD = CID->getClassMethods()[i];
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000590 RewriteObjcMethodDecl(OMD, ResultStr);
591 SourceLocation LocStart = OMD->getLocStart();
592 SourceLocation LocEnd = OMD->getBody()->getLocStart();
593
594 const char *startBuf = SM->getCharacterData(LocStart);
595 const char *endBuf = SM->getCharacterData(LocEnd);
596 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
597 ResultStr.c_str(), ResultStr.size());
598 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000599 if (IMD)
600 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
601 else
602 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000603}
604
Steve Naroff3774dd92007-10-26 20:53:56 +0000605void RewriteTest::RewriteInterfaceDecl(ObjcInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000606 std::string ResultStr;
Steve Naroff77d081b2007-11-01 03:35:41 +0000607 if (!ObjcForwardDecls.count(ClassDecl)) {
608 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000609 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000610 ResultStr += ClassDecl->getName();
611 ResultStr += "\n";
612 ResultStr += "#define _REWRITER_typedef_";
613 ResultStr += ClassDecl->getName();
614 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000615 ResultStr += "typedef struct ";
616 ResultStr += ClassDecl->getName();
617 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000618 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000619 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000620
621 // Mark this typedef as having been generated.
622 ObjcForwardDecls.insert(ClassDecl);
623 }
Steve Naroffef20ed32007-10-30 02:23:23 +0000624 SynthesizeObjcInternalStruct(ClassDecl, ResultStr);
625
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000626 RewriteProperties(ClassDecl->getNumPropertyDecl(),
627 ClassDecl->getPropertyDecl());
Steve Naroff18c83382007-11-13 23:01:27 +0000628 RewriteMethodDeclarations(ClassDecl->getNumInstanceMethods(),
629 ClassDecl->getInstanceMethods());
630 RewriteMethodDeclarations(ClassDecl->getNumClassMethods(),
631 ClassDecl->getClassMethods());
Steve Naroff3774dd92007-10-26 20:53:56 +0000632
Steve Naroff1ccf4632007-10-30 03:43:13 +0000633 // Lastly, comment out the @end.
634 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000635}
636
Steve Naroff6b759ce2007-11-15 02:58:25 +0000637Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
638 ObjcIvarDecl *D = IV->getDecl();
639 if (IV->isFreeIvar()) {
640 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
641 IV->getLocation());
642 Rewrite.ReplaceStmt(IV, Replacement);
643 delete IV;
644 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000645 } else {
646 if (CurMethodDecl) {
647 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
648 ObjcInterfaceType *intT = dyn_cast<ObjcInterfaceType>(pType->getPointeeType());
649 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
650 IdentifierInfo *II = intT->getDecl()->getIdentifier();
651 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
652 II, 0);
653 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
654
655 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
656 // Don't forget the parens to enforce the proper binding.
657 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
658 Rewrite.ReplaceStmt(IV->getBase(), PE);
659 delete IV->getBase();
660 return PE;
661 }
662 }
663 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000664 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000665 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000666}
667
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000668//===----------------------------------------------------------------------===//
669// Function Body / Expression rewriting
670//===----------------------------------------------------------------------===//
671
Steve Naroff334fbc22007-11-09 15:20:18 +0000672Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000673 // Otherwise, just rewrite all children.
674 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
675 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000676 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000677 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000678 if (newStmt)
679 *CI = newStmt;
680 }
Steve Naroffe9780582007-10-23 23:50:29 +0000681
682 // Handle specific things.
683 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
684 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000685
686 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
687 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000688
689 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
690 return RewriteAtSelector(AtSelector);
Steve Naroff0add5d22007-11-03 11:27:19 +0000691
692 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
693 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000694
Steve Naroff71226032007-10-24 22:48:43 +0000695 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
696 // Before we rewrite it, put the original message expression in a comment.
697 SourceLocation startLoc = MessExpr->getLocStart();
698 SourceLocation endLoc = MessExpr->getLocEnd();
699
700 const char *startBuf = SM->getCharacterData(startLoc);
701 const char *endBuf = SM->getCharacterData(endLoc);
702
703 std::string messString;
704 messString += "// ";
705 messString.append(startBuf, endBuf-startBuf+1);
706 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000707
Steve Naroff71226032007-10-24 22:48:43 +0000708 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
709 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
710 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000711 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000712 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000713 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000714
715 if (ObjcAtTryStmt *StmtTry = dyn_cast<ObjcAtTryStmt>(S))
716 return RewriteObjcTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000717
718 if (ObjcAtThrowStmt *StmtThrow = dyn_cast<ObjcAtThrowStmt>(S))
719 return RewriteObjcThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000720
721 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
722 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000723#if 0
724 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
725 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
726 // Get the new text.
727 std::ostringstream Buf;
728 Replacement->printPretty(Buf);
729 const std::string &Str = Buf.str();
730
731 printf("CAST = %s\n", &Str[0]);
732 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
733 delete S;
734 return Replacement;
735 }
736#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000737 // Return this stmt unmodified.
738 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000739}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000740
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000741Stmt *RewriteTest::RewriteObjcTryStmt(ObjcAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000742 // Get the start location and compute the semi location.
743 SourceLocation startLoc = S->getLocStart();
744 const char *startBuf = SM->getCharacterData(startLoc);
745
746 assert((*startBuf == '@') && "bogus @try location");
747
748 std::string buf;
749 // declare a new scope with two variables, _stack and _rethrow.
750 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
751 buf += "int buf[18/*32-bit i386*/];\n";
752 buf += "char *pointers[4];} _stack;\n";
753 buf += "id volatile _rethrow = 0;\n";
754 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000755 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000756
757 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
758
759 startLoc = S->getTryBody()->getLocEnd();
760 startBuf = SM->getCharacterData(startLoc);
761
762 assert((*startBuf == '}') && "bogus @try block");
763
764 SourceLocation lastCurlyLoc = startLoc;
765
766 startLoc = startLoc.getFileLocWithOffset(1);
767 buf = " /* @catch begin */ else {\n";
768 buf += " id _caught = objc_exception_extract(&_stack);\n";
769 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +0000770 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +0000771 buf += " _rethrow = objc_exception_extract(&_stack);\n";
772 buf += " else { /* @catch continue */";
773
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000774 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000775
776 bool sawIdTypedCatch = false;
777 Stmt *lastCatchBody = 0;
778 ObjcAtCatchStmt *catchList = S->getCatchStmts();
779 while (catchList) {
780 Stmt *catchStmt = catchList->getCatchParamStmt();
781
782 if (catchList == S->getCatchStmts())
783 buf = "if ("; // we are generating code for the first catch clause
784 else
785 buf = "else if (";
786 startLoc = catchList->getLocStart();
787 startBuf = SM->getCharacterData(startLoc);
788
789 assert((*startBuf == '@') && "bogus @catch location");
790
791 const char *lParenLoc = strchr(startBuf, '(');
792
793 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
794 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
795 if (t == Context->getObjcIdType()) {
796 buf += "1) { ";
797 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
798 buf.c_str(), buf.size());
799 sawIdTypedCatch = true;
800 } else if (const PointerType *pType = t->getAsPointerType()) {
801 ObjcInterfaceType *cls; // Should be a pointer to a class.
802
803 cls = dyn_cast<ObjcInterfaceType>(pType->getPointeeType().getTypePtr());
804 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +0000805 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +0000806 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +0000807 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +0000808 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
809 buf.c_str(), buf.size());
810 }
811 }
812 // Now rewrite the body...
813 lastCatchBody = catchList->getCatchBody();
814 SourceLocation rParenLoc = catchList->getRParenLoc();
815 SourceLocation bodyLoc = lastCatchBody->getLocStart();
816 const char *bodyBuf = SM->getCharacterData(bodyLoc);
817 const char *rParenBuf = SM->getCharacterData(rParenLoc);
818 assert((*rParenBuf == ')') && "bogus @catch paren location");
819 assert((*bodyBuf == '{') && "bogus @catch body location");
820
821 buf = " = _caught;";
822 // Here we replace ") {" with "= _caught;" (which initializes and
823 // declares the @catch parameter).
824 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
825 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000826 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +0000827 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000828 }
Steve Naroffe9f69842007-11-07 04:08:17 +0000829 catchList = catchList->getNextCatchStmt();
830 }
831 // Complete the catch list...
832 if (lastCatchBody) {
833 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
834 const char *bodyBuf = SM->getCharacterData(bodyLoc);
835 assert((*bodyBuf == '}') && "bogus @catch body location");
836 bodyLoc = bodyLoc.getFileLocWithOffset(1);
837 buf = " } } /* @catch end */\n";
838
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000839 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000840
841 // Set lastCurlyLoc
842 lastCurlyLoc = lastCatchBody->getLocEnd();
843 }
844 if (ObjcAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
845 startLoc = finalStmt->getLocStart();
846 startBuf = SM->getCharacterData(startLoc);
847 assert((*startBuf == '@') && "bogus @finally start");
848
849 buf = "/* @finally */";
850 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
851
852 Stmt *body = finalStmt->getFinallyBody();
853 SourceLocation startLoc = body->getLocStart();
854 SourceLocation endLoc = body->getLocEnd();
855 const char *startBuf = SM->getCharacterData(startLoc);
856 const char *endBuf = SM->getCharacterData(endLoc);
857 assert((*startBuf == '{') && "bogus @finally body location");
858 assert((*endBuf == '}') && "bogus @finally body location");
859
860 startLoc = startLoc.getFileLocWithOffset(1);
861 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000862 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000863 endLoc = endLoc.getFileLocWithOffset(-1);
864 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000865 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +0000866
867 // Set lastCurlyLoc
868 lastCurlyLoc = body->getLocEnd();
869 }
870 // Now emit the final closing curly brace...
871 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
872 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +0000873 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000874 return 0;
875}
876
877Stmt *RewriteTest::RewriteObjcCatchStmt(ObjcAtCatchStmt *S) {
878 return 0;
879}
880
881Stmt *RewriteTest::RewriteObjcFinallyStmt(ObjcAtFinallyStmt *S) {
882 return 0;
883}
884
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000885// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
886// the throw expression is typically a message expression that's already
887// been rewritten! (which implies the SourceLocation's are invalid).
888Stmt *RewriteTest::RewriteObjcThrowStmt(ObjcAtThrowStmt *S) {
889 // Get the start location and compute the semi location.
890 SourceLocation startLoc = S->getLocStart();
891 const char *startBuf = SM->getCharacterData(startLoc);
892
893 assert((*startBuf == '@') && "bogus @throw location");
894
895 std::string buf;
896 /* void objc_exception_throw(id) __attribute__((noreturn)); */
897 buf = "objc_exception_throw(";
898 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
899 const char *semiBuf = strchr(startBuf, ';');
900 assert((*semiBuf == ';') && "@throw: can't find ';'");
901 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
902 buf = ");";
903 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
904 return 0;
905}
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000906
Chris Lattner0021f452007-10-24 16:57:36 +0000907Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000908 // Create a new string expression.
909 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +0000910 std::string StrEncoding;
911 Context->getObjcEncodingForType(Exp->getEncodedType(), StrEncoding);
912 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
913 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +0000914 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +0000915 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
916 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +0000917 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error,
918 "rewriter could not replace sub-expression due to macros");
919 SourceRange Range = Exp->getSourceRange();
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000920 Diags.Report(Exp->getAtLoc(), DiagID, Context->getSourceManager(),
921 0, 0, &Range, 1);
Chris Lattner217df512007-12-02 01:09:57 +0000922 delete Replacement;
Chris Lattner258f26c2007-11-30 22:25:36 +0000923 return Exp;
924 }
925
Chris Lattner4478db92007-11-30 22:53:43 +0000926 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000927 delete Exp;
928 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000929}
930
Steve Naroff296b74f2007-11-05 14:50:49 +0000931Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
932 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
933 // Create a call to sel_registerName("selName").
934 llvm::SmallVector<Expr*, 8> SelExprs;
935 QualType argType = Context->getPointerType(Context->CharTy);
936 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
937 Exp->getSelector().getName().size(),
938 false, argType, SourceLocation(),
939 SourceLocation()));
940 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
941 &SelExprs[0], SelExprs.size());
942 Rewrite.ReplaceStmt(Exp, SelExp);
943 delete Exp;
944 return SelExp;
945}
946
Steve Naroff71226032007-10-24 22:48:43 +0000947CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
948 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000949 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000950 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000951
952 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000953 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000954
955 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000956 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000957 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
958
959 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000960
Steve Naroff71226032007-10-24 22:48:43 +0000961 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
962}
963
Steve Naroffc8a92d12007-11-01 13:24:47 +0000964static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
965 const char *&startRef, const char *&endRef) {
966 while (startBuf < endBuf) {
967 if (*startBuf == '<')
968 startRef = startBuf; // mark the start.
969 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000970 if (startRef && *startRef == '<') {
971 endRef = startBuf; // mark the end.
972 return true;
973 }
974 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000975 }
976 startBuf++;
977 }
978 return false;
979}
980
981bool RewriteTest::needToScanForQualifiers(QualType T) {
982 // FIXME: we don't currently represent "id <Protocol>" in the type system.
983 if (T == Context->getObjcIdType())
984 return true;
985
986 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000987 Type *pointeeType = pType->getPointeeType().getTypePtr();
988 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
989 return true; // we have "Class <Protocol> *".
990 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000991 return false;
992}
993
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000994void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Steve Naroffc8a92d12007-11-01 13:24:47 +0000995
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000996 FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl);
997 if (!FD)
998 return;
999 // Check for ObjC 'id' and class types that have been adorned with protocol
1000 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1001 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1002 assert(funcType && "missing function type");
1003 const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType);
1004 if (!proto)
1005 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001006 if (needToScanForQualifiers(proto->getResultType())) {
1007 // Since types are unique, we need to scan the buffer.
1008 SourceLocation Loc = FD->getLocation();
1009
1010 const char *endBuf = SM->getCharacterData(Loc);
1011 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001012 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001013 startBuf--; // scan backward (from the decl location) for return type.
1014 const char *startRef = 0, *endRef = 0;
1015 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1016 // Get the locations of the startRef, endRef.
1017 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1018 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1019 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001020 Rewrite.InsertText(LessLoc, "/*", 2);
1021 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001022 }
1023 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001024 // Now check arguments.
1025 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1026 if (needToScanForQualifiers(proto->getArgType(i))) {
1027 // Since types are unique, we need to scan the buffer.
1028 SourceLocation Loc = FD->getLocation();
1029
1030 const char *startBuf = SM->getCharacterData(Loc);
1031 const char *endBuf = startBuf;
1032 while (*endBuf != ';')
1033 endBuf++; // scan forward (from the decl location) for argument types.
1034 const char *startRef = 0, *endRef = 0;
1035 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1036 // Get the locations of the startRef, endRef.
1037 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1038 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1039 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001040 Rewrite.InsertText(LessLoc, "/*", 2);
1041 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001042 }
1043 }
1044 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001045}
1046
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001047// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1048void RewriteTest::SynthSelGetUidFunctionDecl() {
1049 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1050 llvm::SmallVector<QualType, 16> ArgTys;
1051 ArgTys.push_back(Context->getPointerType(
1052 Context->CharTy.getQualifiedType(QualType::Const)));
1053 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1054 &ArgTys[0], ArgTys.size(),
1055 false /*isVariadic*/);
1056 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1057 SelGetUidIdent, getFuncType,
1058 FunctionDecl::Extern, false, 0);
1059}
1060
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001061// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1062void RewriteTest::SynthGetProtocolFunctionDecl() {
1063 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1064 llvm::SmallVector<QualType, 16> ArgTys;
1065 ArgTys.push_back(Context->getPointerType(
1066 Context->CharTy.getQualifiedType(QualType::Const)));
1067 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1068 &ArgTys[0], ArgTys.size(),
1069 false /*isVariadic*/);
1070 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1071 SelGetProtoIdent, getFuncType,
1072 FunctionDecl::Extern, false, 0);
1073}
1074
Steve Naroff02a82aa2007-10-30 23:14:51 +00001075void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1076 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001077 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001078 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001079 return;
1080 }
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001081 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001082}
1083
1084// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1085void RewriteTest::SynthMsgSendFunctionDecl() {
1086 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1087 llvm::SmallVector<QualType, 16> ArgTys;
1088 QualType argT = Context->getObjcIdType();
1089 assert(!argT.isNull() && "Can't find 'id' type");
1090 ArgTys.push_back(argT);
1091 argT = Context->getObjcSelType();
1092 assert(!argT.isNull() && "Can't find 'SEL' type");
1093 ArgTys.push_back(argT);
1094 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1095 &ArgTys[0], ArgTys.size(),
1096 true /*isVariadic*/);
1097 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1098 msgSendIdent, msgSendType,
1099 FunctionDecl::Extern, false, 0);
1100}
1101
Steve Naroff764c1ae2007-11-15 10:28:18 +00001102// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1103void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1104 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1105 llvm::SmallVector<QualType, 16> ArgTys;
1106 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1107 &Context->Idents.get("objc_super"), 0);
1108 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1109 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1110 ArgTys.push_back(argT);
1111 argT = Context->getObjcSelType();
1112 assert(!argT.isNull() && "Can't find 'SEL' type");
1113 ArgTys.push_back(argT);
1114 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1115 &ArgTys[0], ArgTys.size(),
1116 true /*isVariadic*/);
1117 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1118 msgSendIdent, msgSendType,
1119 FunctionDecl::Extern, false, 0);
1120}
1121
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001122// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1123void RewriteTest::SynthMsgSendStretFunctionDecl() {
1124 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1125 llvm::SmallVector<QualType, 16> ArgTys;
1126 QualType argT = Context->getObjcIdType();
1127 assert(!argT.isNull() && "Can't find 'id' type");
1128 ArgTys.push_back(argT);
1129 argT = Context->getObjcSelType();
1130 assert(!argT.isNull() && "Can't find 'SEL' type");
1131 ArgTys.push_back(argT);
1132 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1133 &ArgTys[0], ArgTys.size(),
1134 true /*isVariadic*/);
1135 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1136 msgSendIdent, msgSendType,
1137 FunctionDecl::Extern, false, 0);
1138}
1139
1140// SynthMsgSendSuperStretFunctionDecl -
1141// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1142void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1143 IdentifierInfo *msgSendIdent =
1144 &Context->Idents.get("objc_msgSendSuper_stret");
1145 llvm::SmallVector<QualType, 16> ArgTys;
1146 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1147 &Context->Idents.get("objc_super"), 0);
1148 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1149 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1150 ArgTys.push_back(argT);
1151 argT = Context->getObjcSelType();
1152 assert(!argT.isNull() && "Can't find 'SEL' type");
1153 ArgTys.push_back(argT);
1154 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1155 &ArgTys[0], ArgTys.size(),
1156 true /*isVariadic*/);
1157 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1158 msgSendIdent, msgSendType,
1159 FunctionDecl::Extern, false, 0);
1160}
1161
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001162// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1163void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1164 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1165 llvm::SmallVector<QualType, 16> ArgTys;
1166 QualType argT = Context->getObjcIdType();
1167 assert(!argT.isNull() && "Can't find 'id' type");
1168 ArgTys.push_back(argT);
1169 argT = Context->getObjcSelType();
1170 assert(!argT.isNull() && "Can't find 'SEL' type");
1171 ArgTys.push_back(argT);
1172 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1173 &ArgTys[0], ArgTys.size(),
1174 true /*isVariadic*/);
1175 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1176 msgSendIdent, msgSendType,
1177 FunctionDecl::Extern, false, 0);
1178}
1179
Steve Naroff02a82aa2007-10-30 23:14:51 +00001180// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1181void RewriteTest::SynthGetClassFunctionDecl() {
1182 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1183 llvm::SmallVector<QualType, 16> ArgTys;
1184 ArgTys.push_back(Context->getPointerType(
1185 Context->CharTy.getQualifiedType(QualType::Const)));
1186 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1187 &ArgTys[0], ArgTys.size(),
1188 false /*isVariadic*/);
1189 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1190 getClassIdent, getClassType,
1191 FunctionDecl::Extern, false, 0);
1192}
1193
Steve Naroff3b1caac2007-12-07 03:50:46 +00001194// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1195void RewriteTest::SynthGetMetaClassFunctionDecl() {
1196 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1197 llvm::SmallVector<QualType, 16> ArgTys;
1198 ArgTys.push_back(Context->getPointerType(
1199 Context->CharTy.getQualifiedType(QualType::Const)));
1200 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1201 &ArgTys[0], ArgTys.size(),
1202 false /*isVariadic*/);
1203 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1204 getClassIdent, getClassType,
1205 FunctionDecl::Extern, false, 0);
1206}
1207
Steve Naroffabb96362007-11-08 14:30:50 +00001208// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1209void RewriteTest::SynthCFStringFunctionDecl() {
1210 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1211 llvm::SmallVector<QualType, 16> ArgTys;
1212 ArgTys.push_back(Context->getPointerType(
1213 Context->CharTy.getQualifiedType(QualType::Const)));
1214 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1215 &ArgTys[0], ArgTys.size(),
1216 false /*isVariadic*/);
1217 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1218 getClassIdent, getClassType,
1219 FunctionDecl::Extern, false, 0);
1220}
1221
Steve Naroff0add5d22007-11-03 11:27:19 +00001222Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001223#if 1
1224 // This rewrite is specific to GCC, which has builtin support for CFString.
1225 if (!CFStringFunctionDecl)
1226 SynthCFStringFunctionDecl();
1227 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1228 llvm::SmallVector<Expr*, 8> StrExpr;
1229 StrExpr.push_back(Exp->getString());
1230 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1231 &StrExpr[0], StrExpr.size());
1232 // cast to NSConstantString *
1233 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1234 Rewrite.ReplaceStmt(Exp, cast);
1235 delete Exp;
1236 return cast;
1237#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001238 assert(ConstantStringClassReference && "Can't find constant string reference");
1239 llvm::SmallVector<Expr*, 4> InitExprs;
1240
1241 // Synthesize "(Class)&_NSConstantStringClassReference"
1242 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1243 ConstantStringClassReference->getType(),
1244 SourceLocation());
1245 QualType expType = Context->getPointerType(ClsRef->getType());
1246 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1247 expType, SourceLocation());
1248 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1249 SourceLocation());
1250 InitExprs.push_back(cast); // set the 'isa'.
1251 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1252 unsigned IntSize = static_cast<unsigned>(
1253 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1254 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1255 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1256 Exp->getLocStart());
1257 InitExprs.push_back(len); // set "int numBytes".
1258
1259 // struct NSConstantString
1260 QualType CFConstantStrType = Context->getCFConstantStringType();
1261 // (struct NSConstantString) { <exprs from above> }
1262 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1263 &InitExprs[0], InitExprs.size(),
1264 SourceLocation());
1265 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1266 // struct NSConstantString *
1267 expType = Context->getPointerType(StrRep->getType());
1268 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1269 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001270 // cast to NSConstantString *
1271 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001272 Rewrite.ReplaceStmt(Exp, cast);
1273 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001274 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001275#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001276}
1277
Steve Naroff764c1ae2007-11-15 10:28:18 +00001278ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001279 // check if we are sending a message to 'super'
1280 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001281 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1282 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1283 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1284 if (!strcmp(PVD->getName(), "self")) {
1285 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1286 if (ObjcInterfaceType *IT =
1287 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1288 if (IT->getDecl() ==
1289 CurMethodDecl->getClassInterface()->getSuperClass())
1290 return IT->getDecl();
1291 }
1292 }
1293 }
1294 }
1295 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001296 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001297 }
1298 return 0;
1299}
1300
1301// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1302QualType RewriteTest::getSuperStructType() {
1303 if (!SuperStructDecl) {
1304 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1305 &Context->Idents.get("objc_super"), 0);
1306 QualType FieldTypes[2];
1307
1308 // struct objc_object *receiver;
1309 FieldTypes[0] = Context->getObjcIdType();
1310 // struct objc_class *super;
1311 FieldTypes[1] = Context->getObjcClassType();
1312 // Create fields
1313 FieldDecl *FieldDecls[2];
1314
1315 for (unsigned i = 0; i < 2; ++i)
1316 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1317
1318 SuperStructDecl->defineBody(FieldDecls, 4);
1319 }
1320 return Context->getTagDeclType(SuperStructDecl);
1321}
1322
Steve Naroff71226032007-10-24 22:48:43 +00001323Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001324 if (!SelGetUidFunctionDecl)
1325 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001326 if (!MsgSendFunctionDecl)
1327 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001328 if (!MsgSendSuperFunctionDecl)
1329 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001330 if (!MsgSendStretFunctionDecl)
1331 SynthMsgSendStretFunctionDecl();
1332 if (!MsgSendSuperStretFunctionDecl)
1333 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001334 if (!MsgSendFpretFunctionDecl)
1335 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001336 if (!GetClassFunctionDecl)
1337 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001338 if (!GetMetaClassFunctionDecl)
1339 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001340
Steve Naroff764c1ae2007-11-15 10:28:18 +00001341 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001342 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1343 // May need to use objc_msgSend_stret() as well.
1344 FunctionDecl *MsgSendStretFlavor = 0;
1345 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1346 QualType resultType = mDecl->getResultType();
1347 if (resultType.getCanonicalType()->isStructureType()
1348 || resultType.getCanonicalType()->isUnionType())
1349 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001350 else if (resultType.getCanonicalType()->isRealFloatingType())
1351 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001352 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001353
Steve Naroff71226032007-10-24 22:48:43 +00001354 // Synthesize a call to objc_msgSend().
1355 llvm::SmallVector<Expr*, 8> MsgExprs;
1356 IdentifierInfo *clsName = Exp->getClassName();
1357
1358 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1359 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001360 if (!strcmp(clsName->getName(), "super")) {
1361 MsgSendFlavor = MsgSendSuperFunctionDecl;
1362 if (MsgSendStretFlavor)
1363 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1364 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1365
1366 ObjcInterfaceDecl *SuperDecl =
1367 CurMethodDecl->getClassInterface()->getSuperClass();
1368
1369 llvm::SmallVector<Expr*, 4> InitExprs;
1370
1371 // set the receiver to self, the first argument to all methods.
1372 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1373 Context->getObjcIdType(),
1374 SourceLocation()));
1375 llvm::SmallVector<Expr*, 8> ClsExprs;
1376 QualType argType = Context->getPointerType(Context->CharTy);
1377 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1378 SuperDecl->getIdentifier()->getLength(),
1379 false, argType, SourceLocation(),
1380 SourceLocation()));
1381 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1382 &ClsExprs[0],
1383 ClsExprs.size());
1384 // To turn off a warning, type-cast to 'id'
1385 InitExprs.push_back(
1386 new CastExpr(Context->getObjcIdType(),
1387 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1388 // struct objc_super
1389 QualType superType = getSuperStructType();
1390 // (struct objc_super) { <exprs from above> }
1391 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1392 &InitExprs[0], InitExprs.size(),
1393 SourceLocation());
1394 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1395 // struct objc_super *
1396 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1397 Context->getPointerType(SuperRep->getType()),
1398 SourceLocation());
1399 MsgExprs.push_back(Unop);
1400 } else {
1401 llvm::SmallVector<Expr*, 8> ClsExprs;
1402 QualType argType = Context->getPointerType(Context->CharTy);
1403 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1404 clsName->getLength(),
1405 false, argType, SourceLocation(),
1406 SourceLocation()));
1407 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1408 &ClsExprs[0],
1409 ClsExprs.size());
1410 MsgExprs.push_back(Cls);
1411 }
Steve Naroff885e2122007-11-14 23:54:14 +00001412 } else { // instance message.
1413 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001414
Steve Naroff3b1caac2007-12-07 03:50:46 +00001415 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001416 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001417 if (MsgSendStretFlavor)
1418 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001419 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1420
1421 llvm::SmallVector<Expr*, 4> InitExprs;
1422
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001423 InitExprs.push_back(
1424 new CastExpr(Context->getObjcIdType(),
1425 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001426
1427 llvm::SmallVector<Expr*, 8> ClsExprs;
1428 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001429 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1430 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001431 false, argType, SourceLocation(),
1432 SourceLocation()));
1433 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001434 &ClsExprs[0],
1435 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001436 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001437 InitExprs.push_back(
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001438 new CastExpr(Context->getObjcIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001439 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001440 // struct objc_super
1441 QualType superType = getSuperStructType();
1442 // (struct objc_super) { <exprs from above> }
1443 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1444 &InitExprs[0], InitExprs.size(),
1445 SourceLocation());
1446 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1447 // struct objc_super *
1448 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1449 Context->getPointerType(SuperRep->getType()),
1450 SourceLocation());
1451 MsgExprs.push_back(Unop);
1452 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001453 // Remove all type-casts because it may contain objc-style types; e.g.
1454 // Foo<Proto> *.
1455 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1456 recExpr = CE->getSubExpr();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001457 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1458 MsgExprs.push_back(recExpr);
1459 }
Steve Naroff885e2122007-11-14 23:54:14 +00001460 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001461 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001462 llvm::SmallVector<Expr*, 8> SelExprs;
1463 QualType argType = Context->getPointerType(Context->CharTy);
1464 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1465 Exp->getSelector().getName().size(),
1466 false, argType, SourceLocation(),
1467 SourceLocation()));
1468 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1469 &SelExprs[0], SelExprs.size());
1470 MsgExprs.push_back(SelExp);
1471
1472 // Now push any user supplied arguments.
1473 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001474 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001475 // Make all implicit casts explicit...ICE comes in handy:-)
1476 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1477 // Reuse the ICE type, it is exactly what the doctor ordered.
1478 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1479 }
Steve Naroff885e2122007-11-14 23:54:14 +00001480 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001481 // We've transferred the ownership to MsgExprs. Null out the argument in
1482 // the original expression, since we will delete it below.
1483 Exp->setArg(i, 0);
1484 }
Steve Naroff0744c472007-11-04 22:37:50 +00001485 // Generate the funky cast.
1486 CastExpr *cast;
1487 llvm::SmallVector<QualType, 8> ArgTypes;
1488 QualType returnType;
1489
1490 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001491 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1492 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1493 else
1494 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001495 ArgTypes.push_back(Context->getObjcSelType());
1496 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1497 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001498 for (int i = 0; i < mDecl->getNumParams(); i++) {
1499 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001500 ArgTypes.push_back(t);
1501 }
Steve Naroff0744c472007-11-04 22:37:50 +00001502 returnType = mDecl->getResultType();
1503 } else {
1504 returnType = Context->getObjcIdType();
1505 }
1506 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001507 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001508
1509 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001510 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1511 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001512
1513 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1514 // If we don't do this cast, we get the following bizarre warning/note:
1515 // xx.m:13: warning: function called through a non-compatible type
1516 // xx.m:13: note: if this code is reached, the program will abort
1517 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1518 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001519
Steve Naroff0744c472007-11-04 22:37:50 +00001520 // Now do the "normal" pointer to function cast.
1521 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001522 &ArgTypes[0], ArgTypes.size(),
1523 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001524 castType = Context->getPointerType(castType);
1525 cast = new CastExpr(castType, cast, SourceLocation());
1526
1527 // Don't forget the parens to enforce the proper binding.
1528 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1529
1530 const FunctionType *FT = msgSendType->getAsFunctionType();
1531 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1532 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001533 if (MsgSendStretFlavor) {
1534 // We have the method which returns a struct/union. Must also generate
1535 // call to objc_msgSend_stret and hang both varieties on a conditional
1536 // expression which dictate which one to envoke depending on size of
1537 // method's return type.
1538
1539 // Create a reference to the objc_msgSend_stret() declaration.
1540 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1541 SourceLocation());
1542 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1543 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1544 SourceLocation());
1545 // Now do the "normal" pointer to function cast.
1546 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001547 &ArgTypes[0], ArgTypes.size(),
1548 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001549 castType = Context->getPointerType(castType);
1550 cast = new CastExpr(castType, cast, SourceLocation());
1551
1552 // Don't forget the parens to enforce the proper binding.
1553 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1554
1555 FT = msgSendType->getAsFunctionType();
1556 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1557 FT->getResultType(), SourceLocation());
1558
1559 // Build sizeof(returnType)
1560 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1561 returnType, Context->getSizeType(),
1562 SourceLocation(), SourceLocation());
1563 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1564 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1565 // For X86 it is more complicated and some kind of target specific routine
1566 // is needed to decide what to do.
1567 unsigned IntSize = static_cast<unsigned>(
1568 Context->getTypeSize(Context->IntTy, SourceLocation()));
1569
1570 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1571 Context->IntTy,
1572 SourceLocation());
1573 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1574 BinaryOperator::LE,
1575 Context->IntTy,
1576 SourceLocation());
1577 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1578 ConditionalOperator *CondExpr =
1579 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1580 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1581 // Now do the actual rewrite.
1582 Rewrite.ReplaceStmt(Exp, PE);
1583 delete Exp;
1584 return PE;
1585 }
Steve Naroff71226032007-10-24 22:48:43 +00001586 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001587 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001588
Chris Lattner0021f452007-10-24 16:57:36 +00001589 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001590 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001591}
1592
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001593/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1594/// call to objc_getProtocol("proto-name").
1595Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1596 if (!GetProtocolFunctionDecl)
1597 SynthGetProtocolFunctionDecl();
1598 // Create a call to objc_getProtocol("ProtocolName").
1599 llvm::SmallVector<Expr*, 8> ProtoExprs;
1600 QualType argType = Context->getPointerType(Context->CharTy);
1601 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1602 strlen(Exp->getProtocol()->getName()),
1603 false, argType, SourceLocation(),
1604 SourceLocation()));
1605 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1606 &ProtoExprs[0],
1607 ProtoExprs.size());
1608 Rewrite.ReplaceStmt(Exp, ProtoExp);
1609 delete Exp;
1610 return ProtoExp;
1611
1612}
1613
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001614/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1615/// an objective-c class with ivars.
1616void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1617 std::string &Result) {
1618 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1619 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001620 // Do not synthesize more than once.
1621 if (ObjcSynthesizedStructs.count(CDecl))
1622 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001623 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001624 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001625 SourceLocation LocStart = CDecl->getLocStart();
1626 SourceLocation LocEnd = CDecl->getLocEnd();
1627
1628 const char *startBuf = SM->getCharacterData(LocStart);
1629 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001630 // If no ivars and no root or if its root, directly or indirectly,
1631 // have no ivars (thus not synthesized) then no need to synthesize this class.
1632 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001633 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1634 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1635 Result.c_str(), Result.size());
1636 return;
1637 }
1638
1639 // FIXME: This has potential of causing problem. If
1640 // SynthesizeObjcInternalStruct is ever called recursively.
1641 Result += "\nstruct ";
1642 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001643
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001644 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001645 const char *cursor = strchr(startBuf, '{');
1646 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001647 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001648
1649 // rewrite the original header *without* disturbing the '{'
1650 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1651 Result.c_str(), Result.size());
1652 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1653 Result = "\n struct ";
1654 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001655 // Note: We don't name the field decl. This simplifies the "codegen" for
1656 // accessing a superclasses instance variables (and is similar to what gcc
1657 // does internally). The unnamed struct field feature is enabled with
1658 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1659 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001660 Result += ";\n";
1661
1662 // insert the super class structure definition.
1663 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1664 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1665 }
1666 cursor++; // past '{'
1667
1668 // Now comment out any visibility specifiers.
1669 while (cursor < endBuf) {
1670 if (*cursor == '@') {
1671 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001672 // Skip whitespace.
1673 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1674 /*scan*/;
1675
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001676 // FIXME: presence of @public, etc. inside comment results in
1677 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001678 if (!strncmp(cursor, "public", strlen("public")) ||
1679 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001680 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001681 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001682 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001683 // FIXME: If there are cases where '<' is used in ivar declaration part
1684 // of user code, then scan the ivar list and use needToScanForQualifiers
1685 // for type checking.
1686 else if (*cursor == '<') {
1687 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1688 Rewrite.InsertText(atLoc, "/* ", 3);
1689 cursor = strchr(cursor, '>');
1690 cursor++;
1691 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1692 Rewrite.InsertText(atLoc, " */", 3);
1693 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001694 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001695 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001696 // Don't forget to add a ';'!!
1697 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1698 } else { // we don't have any instance variables - insert super struct.
1699 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1700 Result += " {\n struct ";
1701 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001702 // Note: We don't name the field decl. This simplifies the "codegen" for
1703 // accessing a superclasses instance variables (and is similar to what gcc
1704 // does internally). The unnamed struct field feature is enabled with
1705 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1706 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001707 Result += ";\n};\n";
1708 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1709 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001710 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001711 // Mark this struct as having been generated.
1712 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001713 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001714}
1715
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001716// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1717/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001718void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001719 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001720 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001721 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001722 const char *ClassName,
1723 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001724 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001725 if (NumMethods > 0 && !objc_impl_method) {
1726 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001727 SEL _cmd;
1728 char *method_types;
1729 void *_imp;
1730 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001731 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001732 Result += "\nstruct _objc_method {\n";
1733 Result += "\tSEL _cmd;\n";
1734 Result += "\tchar *method_types;\n";
1735 Result += "\tvoid *_imp;\n";
1736 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001737
1738 /* struct _objc_method_list {
1739 struct _objc_method_list *next_method;
1740 int method_count;
1741 struct _objc_method method_list[];
1742 }
1743 */
1744 Result += "\nstruct _objc_method_list {\n";
1745 Result += "\tstruct _objc_method_list *next_method;\n";
1746 Result += "\tint method_count;\n";
1747 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001748 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001749 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001750 // Build _objc_method_list for class's methods if needed
1751 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001752 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001753 Result += prefix;
1754 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1755 Result += "_METHODS_";
1756 Result += ClassName;
1757 Result += " __attribute__ ((section (\"__OBJC, __";
1758 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001759 Result += "_meth\")))= ";
1760 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1761
1762 Result += "\t,{{(SEL)\"";
1763 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001764 std::string MethodTypeString;
1765 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1766 Result += "\", \"";
1767 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001768 Result += "\", ";
1769 Result += MethodInternalNames[Methods[0]];
1770 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001771 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001772 Result += "\t ,{(SEL)\"";
1773 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001774 std::string MethodTypeString;
1775 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1776 Result += "\", \"";
1777 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001778 Result += "\", ";
1779 Result += MethodInternalNames[Methods[i]];
1780 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001781 }
1782 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001783 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001784}
1785
1786/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1787void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1788 int NumProtocols,
1789 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001790 const char *ClassName,
1791 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001792 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001793 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001794 for (int i = 0; i < NumProtocols; i++) {
1795 ObjcProtocolDecl *PDecl = Protocols[i];
1796 // Output struct protocol_methods holder of method selector and type.
1797 if (!objc_protocol_methods &&
1798 (PDecl->getNumInstanceMethods() > 0
1799 || PDecl->getNumClassMethods() > 0)) {
1800 /* struct protocol_methods {
1801 SEL _cmd;
1802 char *method_types;
1803 }
1804 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001805 Result += "\nstruct protocol_methods {\n";
1806 Result += "\tSEL _cmd;\n";
1807 Result += "\tchar *method_types;\n";
1808 Result += "};\n";
1809
1810 /* struct _objc_protocol_method_list {
1811 int protocol_method_count;
1812 struct protocol_methods protocols[];
1813 }
1814 */
1815 Result += "\nstruct _objc_protocol_method_list {\n";
1816 Result += "\tint protocol_method_count;\n";
1817 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001818 objc_protocol_methods = true;
1819 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001820
Fariborz Jahanian04455192007-10-22 21:41:37 +00001821 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001822 int NumMethods = PDecl->getNumInstanceMethods();
1823 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001824 Result += "\nstatic struct _objc_protocol_method_list "
1825 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1826 Result += PDecl->getName();
1827 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1828 "{\n\t" + utostr(NumMethods) + "\n";
1829
Fariborz Jahanian04455192007-10-22 21:41:37 +00001830 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001831 Result += "\t,{{(SEL)\"";
1832 Result += Methods[0]->getSelector().getName().c_str();
1833 Result += "\", \"\"}\n";
1834
1835 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001836 Result += "\t ,{(SEL)\"";
1837 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001838 std::string MethodTypeString;
1839 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1840 Result += "\", \"";
1841 Result += MethodTypeString;
1842 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001843 }
1844 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001845 }
1846
1847 // Output class methods declared in this protocol.
1848 NumMethods = PDecl->getNumClassMethods();
1849 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001850 Result += "\nstatic struct _objc_protocol_method_list "
1851 "_OBJC_PROTOCOL_CLASS_METHODS_";
1852 Result += PDecl->getName();
1853 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1854 "{\n\t";
1855 Result += utostr(NumMethods);
1856 Result += "\n";
1857
Fariborz Jahanian04455192007-10-22 21:41:37 +00001858 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001859 Result += "\t,{{(SEL)\"";
1860 Result += Methods[0]->getSelector().getName().c_str();
1861 Result += "\", \"\"}\n";
1862
1863 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001864 Result += "\t ,{(SEL)\"";
1865 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001866 std::string MethodTypeString;
1867 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1868 Result += "\", \"";
1869 Result += MethodTypeString;
1870 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001871 }
1872 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001873 }
1874 // Output:
1875 /* struct _objc_protocol {
1876 // Objective-C 1.0 extensions
1877 struct _objc_protocol_extension *isa;
1878 char *protocol_name;
1879 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001880 struct _objc_protocol_method_list *instance_methods;
1881 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001882 };
1883 */
1884 static bool objc_protocol = false;
1885 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001886 Result += "\nstruct _objc_protocol {\n";
1887 Result += "\tstruct _objc_protocol_extension *isa;\n";
1888 Result += "\tchar *protocol_name;\n";
1889 Result += "\tstruct _objc_protocol **protocol_list;\n";
1890 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1891 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1892 Result += "};\n";
1893
1894 /* struct _objc_protocol_list {
1895 struct _objc_protocol_list *next;
1896 int protocol_count;
1897 struct _objc_protocol *class_protocols[];
1898 }
1899 */
1900 Result += "\nstruct _objc_protocol_list {\n";
1901 Result += "\tstruct _objc_protocol_list *next;\n";
1902 Result += "\tint protocol_count;\n";
1903 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1904 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001905 objc_protocol = true;
1906 }
1907
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001908 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1909 Result += PDecl->getName();
1910 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1911 "{\n\t0, \"";
1912 Result += PDecl->getName();
1913 Result += "\", 0, ";
1914 if (PDecl->getInstanceMethods() > 0) {
1915 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1916 Result += PDecl->getName();
1917 Result += ", ";
1918 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001919 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001920 Result += "0, ";
1921 if (PDecl->getClassMethods() > 0) {
1922 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1923 Result += PDecl->getName();
1924 Result += "\n";
1925 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001926 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001927 Result += "0\n";
1928 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001929 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001930 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001931 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1932 Result += prefix;
1933 Result += "_PROTOCOLS_";
1934 Result += ClassName;
1935 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1936 "{\n\t0, ";
1937 Result += utostr(NumProtocols);
1938 Result += "\n";
1939
1940 Result += "\t,{&_OBJC_PROTOCOL_";
1941 Result += Protocols[0]->getName();
1942 Result += " \n";
1943
1944 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001945 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001946 Result += "\t ,&_OBJC_PROTOCOL_";
1947 Result += PDecl->getName();
1948 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001949 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001950 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001951 }
1952}
1953
1954/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1955/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001956void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1957 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001958 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1959 // Find category declaration for this implementation.
1960 ObjcCategoryDecl *CDecl;
1961 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1962 CDecl = CDecl->getNextClassCategory())
1963 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1964 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001965
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001966 char *FullCategoryName = (char*)alloca(
1967 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1968 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1969
1970 // Build _objc_method_list for class's instance methods if needed
1971 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1972 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001973 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001974 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001975
1976 // Build _objc_method_list for class's class methods if needed
1977 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1978 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001979 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001980 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001981
1982 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001983 // Null CDecl is case of a category implementation with no category interface
1984 if (CDecl)
1985 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1986 CDecl->getNumReferencedProtocols(),
1987 "CATEGORY",
1988 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001989
1990 /* struct _objc_category {
1991 char *category_name;
1992 char *class_name;
1993 struct _objc_method_list *instance_methods;
1994 struct _objc_method_list *class_methods;
1995 struct _objc_protocol_list *protocols;
1996 // Objective-C 1.0 extensions
1997 uint32_t size; // sizeof (struct _objc_category)
1998 struct _objc_property_list *instance_properties; // category's own
1999 // @property decl.
2000 };
2001 */
2002
2003 static bool objc_category = false;
2004 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002005 Result += "\nstruct _objc_category {\n";
2006 Result += "\tchar *category_name;\n";
2007 Result += "\tchar *class_name;\n";
2008 Result += "\tstruct _objc_method_list *instance_methods;\n";
2009 Result += "\tstruct _objc_method_list *class_methods;\n";
2010 Result += "\tstruct _objc_protocol_list *protocols;\n";
2011 Result += "\tunsigned int size;\n";
2012 Result += "\tstruct _objc_property_list *instance_properties;\n";
2013 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002014 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002015 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002016 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2017 Result += FullCategoryName;
2018 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2019 Result += IDecl->getName();
2020 Result += "\"\n\t, \"";
2021 Result += ClassDecl->getName();
2022 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002023
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002024 if (IDecl->getNumInstanceMethods() > 0) {
2025 Result += "\t, (struct _objc_method_list *)"
2026 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2027 Result += FullCategoryName;
2028 Result += "\n";
2029 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002030 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002031 Result += "\t, 0\n";
2032 if (IDecl->getNumClassMethods() > 0) {
2033 Result += "\t, (struct _objc_method_list *)"
2034 "&_OBJC_CATEGORY_CLASS_METHODS_";
2035 Result += FullCategoryName;
2036 Result += "\n";
2037 }
2038 else
2039 Result += "\t, 0\n";
2040
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002041 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002042 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2043 Result += FullCategoryName;
2044 Result += "\n";
2045 }
2046 else
2047 Result += "\t, 0\n";
2048 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002049}
2050
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002051/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2052/// ivar offset.
2053void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2054 ObjcIvarDecl *ivar,
2055 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002056 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002057 Result += IDecl->getName();
2058 Result += ", ";
2059 Result += ivar->getName();
2060 Result += ")";
2061}
2062
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002063//===----------------------------------------------------------------------===//
2064// Meta Data Emission
2065//===----------------------------------------------------------------------===//
2066
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002067void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2068 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002069 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2070
2071 // Build _objc_ivar_list metadata for classes ivars if needed
2072 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2073 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002074 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002075 // Explictly declared @interface's are already synthesized.
2076 if (CDecl->ImplicitInterfaceDecl()) {
2077 // FIXME: Implementation of a class with no @interface (legacy) doese not
2078 // produce correct synthesis as yet.
2079 SynthesizeObjcInternalStruct(CDecl, Result);
2080 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002081
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002082 if (NumIvars > 0) {
2083 static bool objc_ivar = false;
2084 if (!objc_ivar) {
2085 /* struct _objc_ivar {
2086 char *ivar_name;
2087 char *ivar_type;
2088 int ivar_offset;
2089 };
2090 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002091 Result += "\nstruct _objc_ivar {\n";
2092 Result += "\tchar *ivar_name;\n";
2093 Result += "\tchar *ivar_type;\n";
2094 Result += "\tint ivar_offset;\n";
2095 Result += "};\n";
2096
2097 /* struct _objc_ivar_list {
2098 int ivar_count;
2099 struct _objc_ivar ivar_list[];
2100 };
2101 */
2102 Result += "\nstruct _objc_ivar_list {\n";
2103 Result += "\tint ivar_count;\n";
2104 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002105 objc_ivar = true;
2106 }
2107
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002108 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2109 Result += IDecl->getName();
2110 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2111 "{\n\t";
2112 Result += utostr(NumIvars);
2113 Result += "\n";
2114
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002115 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
2116 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002117 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002118 Result += "\t,{{\"";
2119 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002120 Result += "\", \"";
2121 std::string StrEncoding;
2122 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
2123 Result += StrEncoding;
2124 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002125 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
2126 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002127 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002128 Result += "\t ,{\"";
2129 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002130 Result += "\", \"";
2131 std::string StrEncoding;
2132 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
2133 Result += StrEncoding;
2134 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002135 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
2136 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002137 }
2138
2139 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002140 }
2141
2142 // Build _objc_method_list for class's instance methods if needed
2143 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2144 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002145 true,
2146 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002147
2148 // Build _objc_method_list for class's class methods if needed
2149 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002150 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002151 false,
2152 "", IDecl->getName(), Result);
2153
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002154 // Protocols referenced in class declaration?
2155 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2156 CDecl->getNumIntfRefProtocols(),
2157 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002158 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002159
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002160
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002161 // Declaration of class/meta-class metadata
2162 /* struct _objc_class {
2163 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002164 const char *super_class_name;
2165 char *name;
2166 long version;
2167 long info;
2168 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002169 struct _objc_ivar_list *ivars;
2170 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002171 struct objc_cache *cache;
2172 struct objc_protocol_list *protocols;
2173 const char *ivar_layout;
2174 struct _objc_class_ext *ext;
2175 };
2176 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002177 static bool objc_class = false;
2178 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002179 Result += "\nstruct _objc_class {\n";
2180 Result += "\tstruct _objc_class *isa;\n";
2181 Result += "\tconst char *super_class_name;\n";
2182 Result += "\tchar *name;\n";
2183 Result += "\tlong version;\n";
2184 Result += "\tlong info;\n";
2185 Result += "\tlong instance_size;\n";
2186 Result += "\tstruct _objc_ivar_list *ivars;\n";
2187 Result += "\tstruct _objc_method_list *methods;\n";
2188 Result += "\tstruct objc_cache *cache;\n";
2189 Result += "\tstruct _objc_protocol_list *protocols;\n";
2190 Result += "\tconst char *ivar_layout;\n";
2191 Result += "\tstruct _objc_class_ext *ext;\n";
2192 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002193 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002194 }
2195
2196 // Meta-class metadata generation.
2197 ObjcInterfaceDecl *RootClass = 0;
2198 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2199 while (SuperClass) {
2200 RootClass = SuperClass;
2201 SuperClass = SuperClass->getSuperClass();
2202 }
2203 SuperClass = CDecl->getSuperClass();
2204
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002205 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2206 Result += CDecl->getName();
2207 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2208 "{\n\t(struct _objc_class *)\"";
2209 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2210 Result += "\"";
2211
2212 if (SuperClass) {
2213 Result += ", \"";
2214 Result += SuperClass->getName();
2215 Result += "\", \"";
2216 Result += CDecl->getName();
2217 Result += "\"";
2218 }
2219 else {
2220 Result += ", 0, \"";
2221 Result += CDecl->getName();
2222 Result += "\"";
2223 }
Fariborz Jahanian771d3b92007-12-04 19:31:56 +00002224 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002225 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002226 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002227 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002228 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002229 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002230 Result += "\n";
2231 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002232 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002233 Result += ", 0\n";
2234 if (CDecl->getNumIntfRefProtocols() > 0) {
2235 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2236 Result += CDecl->getName();
2237 Result += ",0,0\n";
2238 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002239 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002240 Result += "\t,0,0,0,0\n";
2241 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002242
2243 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002244 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2245 Result += CDecl->getName();
2246 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2247 "{\n\t&_OBJC_METACLASS_";
2248 Result += CDecl->getName();
2249 if (SuperClass) {
2250 Result += ", \"";
2251 Result += SuperClass->getName();
2252 Result += "\", \"";
2253 Result += CDecl->getName();
2254 Result += "\"";
2255 }
2256 else {
2257 Result += ", 0, \"";
2258 Result += CDecl->getName();
2259 Result += "\"";
2260 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002261 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002262 Result += ", 0,1";
2263 if (!ObjcSynthesizedStructs.count(CDecl))
2264 Result += ",0";
2265 else {
2266 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002267 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002268 Result += CDecl->getName();
2269 Result += ")";
2270 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002271 if (NumIvars > 0) {
2272 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2273 Result += CDecl->getName();
2274 Result += "\n\t";
2275 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002276 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002277 Result += ",0";
2278 if (IDecl->getNumInstanceMethods() > 0) {
2279 Result += ", &_OBJC_INSTANCE_METHODS_";
2280 Result += CDecl->getName();
2281 Result += ", 0\n\t";
2282 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002283 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002284 Result += ",0,0";
2285 if (CDecl->getNumIntfRefProtocols() > 0) {
2286 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2287 Result += CDecl->getName();
2288 Result += ", 0,0\n";
2289 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002290 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002291 Result += ",0,0,0\n";
2292 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002293}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002294
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002295/// RewriteImplementations - This routine rewrites all method implementations
2296/// and emits meta-data.
2297
2298void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002299 int ClsDefCount = ClassImplementation.size();
2300 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002301
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002302 if (ClsDefCount == 0 && CatDefCount == 0)
2303 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002304 // Rewrite implemented methods
2305 for (int i = 0; i < ClsDefCount; i++)
2306 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002307
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002308 for (int i = 0; i < CatDefCount; i++)
2309 RewriteImplementationDecl(CategoryImplementation[i]);
2310
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002311 // This is needed for use of offsetof
2312 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002313
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002314 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002315 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002316 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002317
2318 // For each implemented category, write out all its meta data.
2319 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002320 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002321
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002322 // Write objc_symtab metadata
2323 /*
2324 struct _objc_symtab
2325 {
2326 long sel_ref_cnt;
2327 SEL *refs;
2328 short cls_def_cnt;
2329 short cat_def_cnt;
2330 void *defs[cls_def_cnt + cat_def_cnt];
2331 };
2332 */
2333
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002334 Result += "\nstruct _objc_symtab {\n";
2335 Result += "\tlong sel_ref_cnt;\n";
2336 Result += "\tSEL *refs;\n";
2337 Result += "\tshort cls_def_cnt;\n";
2338 Result += "\tshort cat_def_cnt;\n";
2339 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2340 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002341
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002342 Result += "static struct _objc_symtab "
2343 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2344 Result += "\t0, 0, " + utostr(ClsDefCount)
2345 + ", " + utostr(CatDefCount) + "\n";
2346 for (int i = 0; i < ClsDefCount; i++) {
2347 Result += "\t,&_OBJC_CLASS_";
2348 Result += ClassImplementation[i]->getName();
2349 Result += "\n";
2350 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002351
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002352 for (int i = 0; i < CatDefCount; i++) {
2353 Result += "\t,&_OBJC_CATEGORY_";
2354 Result += CategoryImplementation[i]->getClassInterface()->getName();
2355 Result += "_";
2356 Result += CategoryImplementation[i]->getName();
2357 Result += "\n";
2358 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002359
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002360 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002361
2362 // Write objc_module metadata
2363
2364 /*
2365 struct _objc_module {
2366 long version;
2367 long size;
2368 const char *name;
2369 struct _objc_symtab *symtab;
2370 }
2371 */
2372
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002373 Result += "\nstruct _objc_module {\n";
2374 Result += "\tlong version;\n";
2375 Result += "\tlong size;\n";
2376 Result += "\tconst char *name;\n";
2377 Result += "\tstruct _objc_symtab *symtab;\n";
2378 Result += "};\n\n";
2379 Result += "static struct _objc_module "
2380 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002381 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2382 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002383 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002384
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002385}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002386