blob: 77adafecba6effae4c7d1d3b6d637de346f7cae1 [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;
67 SM = &Context->SourceMgr;
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
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000090 Rewrite.setSourceMgr(Context->SourceMgr);
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();
920 Diags.Report(Exp->getAtLoc(), DiagID, 0, 0, &Range, 1);
921 delete Replacement;
Chris Lattner258f26c2007-11-30 22:25:36 +0000922 return Exp;
923 }
924
Chris Lattner4478db92007-11-30 22:53:43 +0000925 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +0000926 delete Exp;
927 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000928}
929
Steve Naroff296b74f2007-11-05 14:50:49 +0000930Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
931 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
932 // Create a call to sel_registerName("selName").
933 llvm::SmallVector<Expr*, 8> SelExprs;
934 QualType argType = Context->getPointerType(Context->CharTy);
935 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
936 Exp->getSelector().getName().size(),
937 false, argType, SourceLocation(),
938 SourceLocation()));
939 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
940 &SelExprs[0], SelExprs.size());
941 Rewrite.ReplaceStmt(Exp, SelExp);
942 delete Exp;
943 return SelExp;
944}
945
Steve Naroff71226032007-10-24 22:48:43 +0000946CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
947 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +0000948 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +0000949 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +0000950
951 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +0000952 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +0000953
954 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000955 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +0000956 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
957
958 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +0000959
Steve Naroff71226032007-10-24 22:48:43 +0000960 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
961}
962
Steve Naroffc8a92d12007-11-01 13:24:47 +0000963static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
964 const char *&startRef, const char *&endRef) {
965 while (startBuf < endBuf) {
966 if (*startBuf == '<')
967 startRef = startBuf; // mark the start.
968 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +0000969 if (startRef && *startRef == '<') {
970 endRef = startBuf; // mark the end.
971 return true;
972 }
973 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +0000974 }
975 startBuf++;
976 }
977 return false;
978}
979
980bool RewriteTest::needToScanForQualifiers(QualType T) {
981 // FIXME: we don't currently represent "id <Protocol>" in the type system.
982 if (T == Context->getObjcIdType())
983 return true;
984
985 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +0000986 Type *pointeeType = pType->getPointeeType().getTypePtr();
987 if (isa<ObjcQualifiedInterfaceType>(pointeeType))
988 return true; // we have "Class <Protocol> *".
989 }
Steve Naroffc8a92d12007-11-01 13:24:47 +0000990 return false;
991}
992
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000993void RewriteTest::RewriteObjcQualifiedInterfaceTypes(Decl *Dcl) {
Steve Naroffc8a92d12007-11-01 13:24:47 +0000994
Fariborz Jahanian866ac792007-12-11 19:56:36 +0000995 FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl);
996 if (!FD)
997 return;
998 // Check for ObjC 'id' and class types that have been adorned with protocol
999 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1000 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1001 assert(funcType && "missing function type");
1002 const FunctionTypeProto *proto = dyn_cast<FunctionTypeProto>(funcType);
1003 if (!proto)
1004 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001005 if (needToScanForQualifiers(proto->getResultType())) {
1006 // Since types are unique, we need to scan the buffer.
1007 SourceLocation Loc = FD->getLocation();
1008
1009 const char *endBuf = SM->getCharacterData(Loc);
1010 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001011 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001012 startBuf--; // scan backward (from the decl location) for return type.
1013 const char *startRef = 0, *endRef = 0;
1014 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1015 // Get the locations of the startRef, endRef.
1016 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1017 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1018 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001019 Rewrite.InsertText(LessLoc, "/*", 2);
1020 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001021 }
1022 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001023 // Now check arguments.
1024 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1025 if (needToScanForQualifiers(proto->getArgType(i))) {
1026 // Since types are unique, we need to scan the buffer.
1027 SourceLocation Loc = FD->getLocation();
1028
1029 const char *startBuf = SM->getCharacterData(Loc);
1030 const char *endBuf = startBuf;
1031 while (*endBuf != ';')
1032 endBuf++; // scan forward (from the decl location) for argument types.
1033 const char *startRef = 0, *endRef = 0;
1034 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1035 // Get the locations of the startRef, endRef.
1036 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1037 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1038 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001039 Rewrite.InsertText(LessLoc, "/*", 2);
1040 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001041 }
1042 }
1043 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001044}
1045
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001046// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1047void RewriteTest::SynthSelGetUidFunctionDecl() {
1048 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1049 llvm::SmallVector<QualType, 16> ArgTys;
1050 ArgTys.push_back(Context->getPointerType(
1051 Context->CharTy.getQualifiedType(QualType::Const)));
1052 QualType getFuncType = Context->getFunctionType(Context->getObjcSelType(),
1053 &ArgTys[0], ArgTys.size(),
1054 false /*isVariadic*/);
1055 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1056 SelGetUidIdent, getFuncType,
1057 FunctionDecl::Extern, false, 0);
1058}
1059
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001060// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1061void RewriteTest::SynthGetProtocolFunctionDecl() {
1062 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1063 llvm::SmallVector<QualType, 16> ArgTys;
1064 ArgTys.push_back(Context->getPointerType(
1065 Context->CharTy.getQualifiedType(QualType::Const)));
1066 QualType getFuncType = Context->getFunctionType(Context->getObjcProtoType(),
1067 &ArgTys[0], ArgTys.size(),
1068 false /*isVariadic*/);
1069 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1070 SelGetProtoIdent, getFuncType,
1071 FunctionDecl::Extern, false, 0);
1072}
1073
Steve Naroff02a82aa2007-10-30 23:14:51 +00001074void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1075 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001076 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001077 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001078 return;
1079 }
Fariborz Jahanian866ac792007-12-11 19:56:36 +00001080 RewriteObjcQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001081}
1082
1083// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1084void RewriteTest::SynthMsgSendFunctionDecl() {
1085 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1086 llvm::SmallVector<QualType, 16> ArgTys;
1087 QualType argT = Context->getObjcIdType();
1088 assert(!argT.isNull() && "Can't find 'id' type");
1089 ArgTys.push_back(argT);
1090 argT = Context->getObjcSelType();
1091 assert(!argT.isNull() && "Can't find 'SEL' type");
1092 ArgTys.push_back(argT);
1093 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1094 &ArgTys[0], ArgTys.size(),
1095 true /*isVariadic*/);
1096 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1097 msgSendIdent, msgSendType,
1098 FunctionDecl::Extern, false, 0);
1099}
1100
Steve Naroff764c1ae2007-11-15 10:28:18 +00001101// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1102void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1103 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1104 llvm::SmallVector<QualType, 16> ArgTys;
1105 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1106 &Context->Idents.get("objc_super"), 0);
1107 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1108 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1109 ArgTys.push_back(argT);
1110 argT = Context->getObjcSelType();
1111 assert(!argT.isNull() && "Can't find 'SEL' type");
1112 ArgTys.push_back(argT);
1113 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1114 &ArgTys[0], ArgTys.size(),
1115 true /*isVariadic*/);
1116 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1117 msgSendIdent, msgSendType,
1118 FunctionDecl::Extern, false, 0);
1119}
1120
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001121// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1122void RewriteTest::SynthMsgSendStretFunctionDecl() {
1123 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1124 llvm::SmallVector<QualType, 16> ArgTys;
1125 QualType argT = Context->getObjcIdType();
1126 assert(!argT.isNull() && "Can't find 'id' type");
1127 ArgTys.push_back(argT);
1128 argT = Context->getObjcSelType();
1129 assert(!argT.isNull() && "Can't find 'SEL' type");
1130 ArgTys.push_back(argT);
1131 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1132 &ArgTys[0], ArgTys.size(),
1133 true /*isVariadic*/);
1134 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1135 msgSendIdent, msgSendType,
1136 FunctionDecl::Extern, false, 0);
1137}
1138
1139// SynthMsgSendSuperStretFunctionDecl -
1140// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1141void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1142 IdentifierInfo *msgSendIdent =
1143 &Context->Idents.get("objc_msgSendSuper_stret");
1144 llvm::SmallVector<QualType, 16> ArgTys;
1145 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1146 &Context->Idents.get("objc_super"), 0);
1147 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1148 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1149 ArgTys.push_back(argT);
1150 argT = Context->getObjcSelType();
1151 assert(!argT.isNull() && "Can't find 'SEL' type");
1152 ArgTys.push_back(argT);
1153 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1154 &ArgTys[0], ArgTys.size(),
1155 true /*isVariadic*/);
1156 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1157 msgSendIdent, msgSendType,
1158 FunctionDecl::Extern, false, 0);
1159}
1160
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001161// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1162void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1163 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1164 llvm::SmallVector<QualType, 16> ArgTys;
1165 QualType argT = Context->getObjcIdType();
1166 assert(!argT.isNull() && "Can't find 'id' type");
1167 ArgTys.push_back(argT);
1168 argT = Context->getObjcSelType();
1169 assert(!argT.isNull() && "Can't find 'SEL' type");
1170 ArgTys.push_back(argT);
1171 QualType msgSendType = Context->getFunctionType(Context->getObjcIdType(),
1172 &ArgTys[0], ArgTys.size(),
1173 true /*isVariadic*/);
1174 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1175 msgSendIdent, msgSendType,
1176 FunctionDecl::Extern, false, 0);
1177}
1178
Steve Naroff02a82aa2007-10-30 23:14:51 +00001179// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1180void RewriteTest::SynthGetClassFunctionDecl() {
1181 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1182 llvm::SmallVector<QualType, 16> ArgTys;
1183 ArgTys.push_back(Context->getPointerType(
1184 Context->CharTy.getQualifiedType(QualType::Const)));
1185 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1186 &ArgTys[0], ArgTys.size(),
1187 false /*isVariadic*/);
1188 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1189 getClassIdent, getClassType,
1190 FunctionDecl::Extern, false, 0);
1191}
1192
Steve Naroff3b1caac2007-12-07 03:50:46 +00001193// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1194void RewriteTest::SynthGetMetaClassFunctionDecl() {
1195 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1196 llvm::SmallVector<QualType, 16> ArgTys;
1197 ArgTys.push_back(Context->getPointerType(
1198 Context->CharTy.getQualifiedType(QualType::Const)));
1199 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1200 &ArgTys[0], ArgTys.size(),
1201 false /*isVariadic*/);
1202 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1203 getClassIdent, getClassType,
1204 FunctionDecl::Extern, false, 0);
1205}
1206
Steve Naroffabb96362007-11-08 14:30:50 +00001207// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1208void RewriteTest::SynthCFStringFunctionDecl() {
1209 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1210 llvm::SmallVector<QualType, 16> ArgTys;
1211 ArgTys.push_back(Context->getPointerType(
1212 Context->CharTy.getQualifiedType(QualType::Const)));
1213 QualType getClassType = Context->getFunctionType(Context->getObjcIdType(),
1214 &ArgTys[0], ArgTys.size(),
1215 false /*isVariadic*/);
1216 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1217 getClassIdent, getClassType,
1218 FunctionDecl::Extern, false, 0);
1219}
1220
Steve Naroff0add5d22007-11-03 11:27:19 +00001221Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001222#if 1
1223 // This rewrite is specific to GCC, which has builtin support for CFString.
1224 if (!CFStringFunctionDecl)
1225 SynthCFStringFunctionDecl();
1226 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1227 llvm::SmallVector<Expr*, 8> StrExpr;
1228 StrExpr.push_back(Exp->getString());
1229 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1230 &StrExpr[0], StrExpr.size());
1231 // cast to NSConstantString *
1232 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
1233 Rewrite.ReplaceStmt(Exp, cast);
1234 delete Exp;
1235 return cast;
1236#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001237 assert(ConstantStringClassReference && "Can't find constant string reference");
1238 llvm::SmallVector<Expr*, 4> InitExprs;
1239
1240 // Synthesize "(Class)&_NSConstantStringClassReference"
1241 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1242 ConstantStringClassReference->getType(),
1243 SourceLocation());
1244 QualType expType = Context->getPointerType(ClsRef->getType());
1245 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1246 expType, SourceLocation());
1247 CastExpr *cast = new CastExpr(Context->getObjcClassType(), Unop,
1248 SourceLocation());
1249 InitExprs.push_back(cast); // set the 'isa'.
1250 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1251 unsigned IntSize = static_cast<unsigned>(
1252 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1253 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1254 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1255 Exp->getLocStart());
1256 InitExprs.push_back(len); // set "int numBytes".
1257
1258 // struct NSConstantString
1259 QualType CFConstantStrType = Context->getCFConstantStringType();
1260 // (struct NSConstantString) { <exprs from above> }
1261 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1262 &InitExprs[0], InitExprs.size(),
1263 SourceLocation());
1264 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1265 // struct NSConstantString *
1266 expType = Context->getPointerType(StrRep->getType());
1267 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1268 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001269 // cast to NSConstantString *
1270 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001271 Rewrite.ReplaceStmt(Exp, cast);
1272 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001273 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001274#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001275}
1276
Steve Naroff764c1ae2007-11-15 10:28:18 +00001277ObjcInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001278 // check if we are sending a message to 'super'
1279 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001280 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1281 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1282 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1283 if (!strcmp(PVD->getName(), "self")) {
1284 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
1285 if (ObjcInterfaceType *IT =
1286 dyn_cast<ObjcInterfaceType>(PT->getPointeeType())) {
1287 if (IT->getDecl() ==
1288 CurMethodDecl->getClassInterface()->getSuperClass())
1289 return IT->getDecl();
1290 }
1291 }
1292 }
1293 }
1294 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001295 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001296 }
1297 return 0;
1298}
1299
1300// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1301QualType RewriteTest::getSuperStructType() {
1302 if (!SuperStructDecl) {
1303 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1304 &Context->Idents.get("objc_super"), 0);
1305 QualType FieldTypes[2];
1306
1307 // struct objc_object *receiver;
1308 FieldTypes[0] = Context->getObjcIdType();
1309 // struct objc_class *super;
1310 FieldTypes[1] = Context->getObjcClassType();
1311 // Create fields
1312 FieldDecl *FieldDecls[2];
1313
1314 for (unsigned i = 0; i < 2; ++i)
1315 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1316
1317 SuperStructDecl->defineBody(FieldDecls, 4);
1318 }
1319 return Context->getTagDeclType(SuperStructDecl);
1320}
1321
Steve Naroff71226032007-10-24 22:48:43 +00001322Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001323 if (!SelGetUidFunctionDecl)
1324 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001325 if (!MsgSendFunctionDecl)
1326 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001327 if (!MsgSendSuperFunctionDecl)
1328 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001329 if (!MsgSendStretFunctionDecl)
1330 SynthMsgSendStretFunctionDecl();
1331 if (!MsgSendSuperStretFunctionDecl)
1332 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001333 if (!MsgSendFpretFunctionDecl)
1334 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001335 if (!GetClassFunctionDecl)
1336 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001337 if (!GetMetaClassFunctionDecl)
1338 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001339
Steve Naroff764c1ae2007-11-15 10:28:18 +00001340 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001341 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1342 // May need to use objc_msgSend_stret() as well.
1343 FunctionDecl *MsgSendStretFlavor = 0;
1344 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1345 QualType resultType = mDecl->getResultType();
1346 if (resultType.getCanonicalType()->isStructureType()
1347 || resultType.getCanonicalType()->isUnionType())
1348 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001349 else if (resultType.getCanonicalType()->isRealFloatingType())
1350 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001351 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001352
Steve Naroff71226032007-10-24 22:48:43 +00001353 // Synthesize a call to objc_msgSend().
1354 llvm::SmallVector<Expr*, 8> MsgExprs;
1355 IdentifierInfo *clsName = Exp->getClassName();
1356
1357 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1358 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001359 if (!strcmp(clsName->getName(), "super")) {
1360 MsgSendFlavor = MsgSendSuperFunctionDecl;
1361 if (MsgSendStretFlavor)
1362 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1363 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1364
1365 ObjcInterfaceDecl *SuperDecl =
1366 CurMethodDecl->getClassInterface()->getSuperClass();
1367
1368 llvm::SmallVector<Expr*, 4> InitExprs;
1369
1370 // set the receiver to self, the first argument to all methods.
1371 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
1372 Context->getObjcIdType(),
1373 SourceLocation()));
1374 llvm::SmallVector<Expr*, 8> ClsExprs;
1375 QualType argType = Context->getPointerType(Context->CharTy);
1376 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1377 SuperDecl->getIdentifier()->getLength(),
1378 false, argType, SourceLocation(),
1379 SourceLocation()));
1380 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1381 &ClsExprs[0],
1382 ClsExprs.size());
1383 // To turn off a warning, type-cast to 'id'
1384 InitExprs.push_back(
1385 new CastExpr(Context->getObjcIdType(),
1386 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1387 // struct objc_super
1388 QualType superType = getSuperStructType();
1389 // (struct objc_super) { <exprs from above> }
1390 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1391 &InitExprs[0], InitExprs.size(),
1392 SourceLocation());
1393 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1394 // struct objc_super *
1395 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1396 Context->getPointerType(SuperRep->getType()),
1397 SourceLocation());
1398 MsgExprs.push_back(Unop);
1399 } else {
1400 llvm::SmallVector<Expr*, 8> ClsExprs;
1401 QualType argType = Context->getPointerType(Context->CharTy);
1402 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1403 clsName->getLength(),
1404 false, argType, SourceLocation(),
1405 SourceLocation()));
1406 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1407 &ClsExprs[0],
1408 ClsExprs.size());
1409 MsgExprs.push_back(Cls);
1410 }
Steve Naroff885e2122007-11-14 23:54:14 +00001411 } else { // instance message.
1412 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001413
Steve Naroff3b1caac2007-12-07 03:50:46 +00001414 if (ObjcInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001415 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001416 if (MsgSendStretFlavor)
1417 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001418 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1419
1420 llvm::SmallVector<Expr*, 4> InitExprs;
1421
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001422 InitExprs.push_back(
1423 new CastExpr(Context->getObjcIdType(),
1424 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001425
1426 llvm::SmallVector<Expr*, 8> ClsExprs;
1427 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001428 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1429 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001430 false, argType, SourceLocation(),
1431 SourceLocation()));
1432 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001433 &ClsExprs[0],
1434 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001435 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001436 InitExprs.push_back(
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001437 new CastExpr(Context->getObjcIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001438 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001439 // struct objc_super
1440 QualType superType = getSuperStructType();
1441 // (struct objc_super) { <exprs from above> }
1442 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1443 &InitExprs[0], InitExprs.size(),
1444 SourceLocation());
1445 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(superType, ILE);
1446 // struct objc_super *
1447 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1448 Context->getPointerType(SuperRep->getType()),
1449 SourceLocation());
1450 MsgExprs.push_back(Unop);
1451 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001452 // Remove all type-casts because it may contain objc-style types; e.g.
1453 // Foo<Proto> *.
1454 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1455 recExpr = CE->getSubExpr();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001456 recExpr = new CastExpr(Context->getObjcIdType(), recExpr, SourceLocation());
1457 MsgExprs.push_back(recExpr);
1458 }
Steve Naroff885e2122007-11-14 23:54:14 +00001459 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001460 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001461 llvm::SmallVector<Expr*, 8> SelExprs;
1462 QualType argType = Context->getPointerType(Context->CharTy);
1463 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1464 Exp->getSelector().getName().size(),
1465 false, argType, SourceLocation(),
1466 SourceLocation()));
1467 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1468 &SelExprs[0], SelExprs.size());
1469 MsgExprs.push_back(SelExp);
1470
1471 // Now push any user supplied arguments.
1472 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001473 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001474 // Make all implicit casts explicit...ICE comes in handy:-)
1475 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1476 // Reuse the ICE type, it is exactly what the doctor ordered.
1477 userExpr = new CastExpr(ICE->getType(), userExpr, SourceLocation());
1478 }
Steve Naroff885e2122007-11-14 23:54:14 +00001479 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001480 // We've transferred the ownership to MsgExprs. Null out the argument in
1481 // the original expression, since we will delete it below.
1482 Exp->setArg(i, 0);
1483 }
Steve Naroff0744c472007-11-04 22:37:50 +00001484 // Generate the funky cast.
1485 CastExpr *cast;
1486 llvm::SmallVector<QualType, 8> ArgTypes;
1487 QualType returnType;
1488
1489 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001490 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1491 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1492 else
1493 ArgTypes.push_back(Context->getObjcIdType());
Steve Naroff0744c472007-11-04 22:37:50 +00001494 ArgTypes.push_back(Context->getObjcSelType());
1495 if (ObjcMethodDecl *mDecl = Exp->getMethodDecl()) {
1496 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001497 for (int i = 0; i < mDecl->getNumParams(); i++) {
1498 QualType t = mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001499 ArgTypes.push_back(t);
1500 }
Steve Naroff0744c472007-11-04 22:37:50 +00001501 returnType = mDecl->getResultType();
1502 } else {
1503 returnType = Context->getObjcIdType();
1504 }
1505 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001506 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001507
1508 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001509 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1510 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001511
1512 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1513 // If we don't do this cast, we get the following bizarre warning/note:
1514 // xx.m:13: warning: function called through a non-compatible type
1515 // xx.m:13: note: if this code is reached, the program will abort
1516 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1517 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001518
Steve Naroff0744c472007-11-04 22:37:50 +00001519 // Now do the "normal" pointer to function cast.
1520 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001521 &ArgTypes[0], ArgTypes.size(),
1522 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001523 castType = Context->getPointerType(castType);
1524 cast = new CastExpr(castType, cast, SourceLocation());
1525
1526 // Don't forget the parens to enforce the proper binding.
1527 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1528
1529 const FunctionType *FT = msgSendType->getAsFunctionType();
1530 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1531 FT->getResultType(), SourceLocation());
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001532 if (MsgSendStretFlavor) {
1533 // We have the method which returns a struct/union. Must also generate
1534 // call to objc_msgSend_stret and hang both varieties on a conditional
1535 // expression which dictate which one to envoke depending on size of
1536 // method's return type.
1537
1538 // Create a reference to the objc_msgSend_stret() declaration.
1539 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1540 SourceLocation());
1541 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1542 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1543 SourceLocation());
1544 // Now do the "normal" pointer to function cast.
1545 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001546 &ArgTypes[0], ArgTypes.size(),
1547 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001548 castType = Context->getPointerType(castType);
1549 cast = new CastExpr(castType, cast, SourceLocation());
1550
1551 // Don't forget the parens to enforce the proper binding.
1552 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1553
1554 FT = msgSendType->getAsFunctionType();
1555 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1556 FT->getResultType(), SourceLocation());
1557
1558 // Build sizeof(returnType)
1559 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1560 returnType, Context->getSizeType(),
1561 SourceLocation(), SourceLocation());
1562 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1563 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1564 // For X86 it is more complicated and some kind of target specific routine
1565 // is needed to decide what to do.
1566 unsigned IntSize = static_cast<unsigned>(
1567 Context->getTypeSize(Context->IntTy, SourceLocation()));
1568
1569 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1570 Context->IntTy,
1571 SourceLocation());
1572 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1573 BinaryOperator::LE,
1574 Context->IntTy,
1575 SourceLocation());
1576 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1577 ConditionalOperator *CondExpr =
1578 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1579 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1580 // Now do the actual rewrite.
1581 Rewrite.ReplaceStmt(Exp, PE);
1582 delete Exp;
1583 return PE;
1584 }
Steve Naroff71226032007-10-24 22:48:43 +00001585 // Now do the actual rewrite.
Steve Naroff0744c472007-11-04 22:37:50 +00001586 Rewrite.ReplaceStmt(Exp, CE);
Steve Naroff71226032007-10-24 22:48:43 +00001587
Chris Lattner0021f452007-10-24 16:57:36 +00001588 delete Exp;
Steve Naroff0744c472007-11-04 22:37:50 +00001589 return CE;
Steve Naroffe9780582007-10-23 23:50:29 +00001590}
1591
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001592/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1593/// call to objc_getProtocol("proto-name").
1594Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1595 if (!GetProtocolFunctionDecl)
1596 SynthGetProtocolFunctionDecl();
1597 // Create a call to objc_getProtocol("ProtocolName").
1598 llvm::SmallVector<Expr*, 8> ProtoExprs;
1599 QualType argType = Context->getPointerType(Context->CharTy);
1600 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1601 strlen(Exp->getProtocol()->getName()),
1602 false, argType, SourceLocation(),
1603 SourceLocation()));
1604 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1605 &ProtoExprs[0],
1606 ProtoExprs.size());
1607 Rewrite.ReplaceStmt(Exp, ProtoExp);
1608 delete Exp;
1609 return ProtoExp;
1610
1611}
1612
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001613/// SynthesizeObjcInternalStruct - Rewrite one internal struct corresponding to
1614/// an objective-c class with ivars.
1615void RewriteTest::SynthesizeObjcInternalStruct(ObjcInterfaceDecl *CDecl,
1616 std::string &Result) {
1617 assert(CDecl && "Class missing in SynthesizeObjcInternalStruct");
1618 assert(CDecl->getName() && "Name missing in SynthesizeObjcInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00001619 // Do not synthesize more than once.
1620 if (ObjcSynthesizedStructs.count(CDecl))
1621 return;
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001622 ObjcInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00001623 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001624 SourceLocation LocStart = CDecl->getLocStart();
1625 SourceLocation LocEnd = CDecl->getLocEnd();
1626
1627 const char *startBuf = SM->getCharacterData(LocStart);
1628 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001629 // If no ivars and no root or if its root, directly or indirectly,
1630 // have no ivars (thus not synthesized) then no need to synthesize this class.
1631 if (NumIvars <= 0 && (!RCDecl || !ObjcSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00001632 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1633 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1634 Result.c_str(), Result.size());
1635 return;
1636 }
1637
1638 // FIXME: This has potential of causing problem. If
1639 // SynthesizeObjcInternalStruct is ever called recursively.
1640 Result += "\nstruct ";
1641 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00001642
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001643 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00001644 const char *cursor = strchr(startBuf, '{');
1645 assert((cursor && endBuf)
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001646 && "SynthesizeObjcInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00001647
1648 // rewrite the original header *without* disturbing the '{'
1649 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1650 Result.c_str(), Result.size());
1651 if (RCDecl && ObjcSynthesizedStructs.count(RCDecl)) {
1652 Result = "\n struct ";
1653 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001654 // Note: We don't name the field decl. This simplifies the "codegen" for
1655 // accessing a superclasses instance variables (and is similar to what gcc
1656 // does internally). The unnamed struct field feature is enabled with
1657 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1658 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001659 Result += ";\n";
1660
1661 // insert the super class structure definition.
1662 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1663 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1664 }
1665 cursor++; // past '{'
1666
1667 // Now comment out any visibility specifiers.
1668 while (cursor < endBuf) {
1669 if (*cursor == '@') {
1670 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00001671 // Skip whitespace.
1672 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1673 /*scan*/;
1674
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001675 // FIXME: presence of @public, etc. inside comment results in
1676 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001677 if (!strncmp(cursor, "public", strlen("public")) ||
1678 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001679 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00001680 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001681 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00001682 // FIXME: If there are cases where '<' is used in ivar declaration part
1683 // of user code, then scan the ivar list and use needToScanForQualifiers
1684 // for type checking.
1685 else if (*cursor == '<') {
1686 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1687 Rewrite.InsertText(atLoc, "/* ", 3);
1688 cursor = strchr(cursor, '>');
1689 cursor++;
1690 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1691 Rewrite.InsertText(atLoc, " */", 3);
1692 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001693 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00001694 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00001695 // Don't forget to add a ';'!!
1696 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1697 } else { // we don't have any instance variables - insert super struct.
1698 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1699 Result += " {\n struct ";
1700 Result += RCDecl->getName();
Steve Narofff2ee53f2007-12-07 22:15:58 +00001701 // Note: We don't name the field decl. This simplifies the "codegen" for
1702 // accessing a superclasses instance variables (and is similar to what gcc
1703 // does internally). The unnamed struct field feature is enabled with
1704 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1705 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00001706 Result += ";\n};\n";
1707 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1708 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001709 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001710 // Mark this struct as having been generated.
1711 if (!ObjcSynthesizedStructs.insert(CDecl))
Fariborz Jahanian2a3c7762007-10-31 22:57:04 +00001712 assert(false && "struct already synthesize- SynthesizeObjcInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00001713}
1714
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001715// RewriteObjcMethodsMetaData - Rewrite methods metadata for instance or
1716/// class methods.
Steve Naroffb82c50f2007-11-11 17:19:15 +00001717void RewriteTest::RewriteObjcMethodsMetaData(ObjcMethodDecl *const*Methods,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001718 int NumMethods,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001719 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001720 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001721 const char *ClassName,
1722 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001723 static bool objc_impl_method = false;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001724 if (NumMethods > 0 && !objc_impl_method) {
1725 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001726 SEL _cmd;
1727 char *method_types;
1728 void *_imp;
1729 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001730 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001731 Result += "\nstruct _objc_method {\n";
1732 Result += "\tSEL _cmd;\n";
1733 Result += "\tchar *method_types;\n";
1734 Result += "\tvoid *_imp;\n";
1735 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001736
1737 /* struct _objc_method_list {
1738 struct _objc_method_list *next_method;
1739 int method_count;
1740 struct _objc_method method_list[];
1741 }
1742 */
1743 Result += "\nstruct _objc_method_list {\n";
1744 Result += "\tstruct _objc_method_list *next_method;\n";
1745 Result += "\tint method_count;\n";
1746 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001747 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00001748 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001749 // Build _objc_method_list for class's methods if needed
1750 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001751 Result += "\nstatic struct _objc_method_list _OBJC_";
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00001752 Result += prefix;
1753 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1754 Result += "_METHODS_";
1755 Result += ClassName;
1756 Result += " __attribute__ ((section (\"__OBJC, __";
1757 Result += IsInstanceMethod ? "inst" : "cls";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001758 Result += "_meth\")))= ";
1759 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
1760
1761 Result += "\t,{{(SEL)\"";
1762 Result += Methods[0]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001763 std::string MethodTypeString;
1764 Context->getObjcEncodingForMethodDecl(Methods[0], MethodTypeString);
1765 Result += "\", \"";
1766 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001767 Result += "\", ";
1768 Result += MethodInternalNames[Methods[0]];
1769 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001770 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001771 Result += "\t ,{(SEL)\"";
1772 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001773 std::string MethodTypeString;
1774 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1775 Result += "\", \"";
1776 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00001777 Result += "\", ";
1778 Result += MethodInternalNames[Methods[i]];
1779 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001780 }
1781 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001782 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001783}
1784
1785/// RewriteObjcProtocolsMetaData - Rewrite protocols meta-data.
1786void RewriteTest::RewriteObjcProtocolsMetaData(ObjcProtocolDecl **Protocols,
1787 int NumProtocols,
1788 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001789 const char *ClassName,
1790 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001791 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001792 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001793 for (int i = 0; i < NumProtocols; i++) {
1794 ObjcProtocolDecl *PDecl = Protocols[i];
1795 // Output struct protocol_methods holder of method selector and type.
1796 if (!objc_protocol_methods &&
1797 (PDecl->getNumInstanceMethods() > 0
1798 || PDecl->getNumClassMethods() > 0)) {
1799 /* struct protocol_methods {
1800 SEL _cmd;
1801 char *method_types;
1802 }
1803 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001804 Result += "\nstruct protocol_methods {\n";
1805 Result += "\tSEL _cmd;\n";
1806 Result += "\tchar *method_types;\n";
1807 Result += "};\n";
1808
1809 /* struct _objc_protocol_method_list {
1810 int protocol_method_count;
1811 struct protocol_methods protocols[];
1812 }
1813 */
1814 Result += "\nstruct _objc_protocol_method_list {\n";
1815 Result += "\tint protocol_method_count;\n";
1816 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001817 objc_protocol_methods = true;
1818 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001819
Fariborz Jahanian04455192007-10-22 21:41:37 +00001820 // Output instance methods declared in this protocol.
Fariborz Jahanian04455192007-10-22 21:41:37 +00001821 int NumMethods = PDecl->getNumInstanceMethods();
1822 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001823 Result += "\nstatic struct _objc_protocol_method_list "
1824 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1825 Result += PDecl->getName();
1826 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1827 "{\n\t" + utostr(NumMethods) + "\n";
1828
Fariborz Jahanian04455192007-10-22 21:41:37 +00001829 ObjcMethodDecl **Methods = PDecl->getInstanceMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001830 Result += "\t,{{(SEL)\"";
1831 Result += Methods[0]->getSelector().getName().c_str();
1832 Result += "\", \"\"}\n";
1833
1834 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001835 Result += "\t ,{(SEL)\"";
1836 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001837 std::string MethodTypeString;
1838 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1839 Result += "\", \"";
1840 Result += MethodTypeString;
1841 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001842 }
1843 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001844 }
1845
1846 // Output class methods declared in this protocol.
1847 NumMethods = PDecl->getNumClassMethods();
1848 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001849 Result += "\nstatic struct _objc_protocol_method_list "
1850 "_OBJC_PROTOCOL_CLASS_METHODS_";
1851 Result += PDecl->getName();
1852 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1853 "{\n\t";
1854 Result += utostr(NumMethods);
1855 Result += "\n";
1856
Fariborz Jahanian04455192007-10-22 21:41:37 +00001857 ObjcMethodDecl **Methods = PDecl->getClassMethods();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001858 Result += "\t,{{(SEL)\"";
1859 Result += Methods[0]->getSelector().getName().c_str();
1860 Result += "\", \"\"}\n";
1861
1862 for (int i = 1; i < NumMethods; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001863 Result += "\t ,{(SEL)\"";
1864 Result += Methods[i]->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00001865 std::string MethodTypeString;
1866 Context->getObjcEncodingForMethodDecl(Methods[i], MethodTypeString);
1867 Result += "\", \"";
1868 Result += MethodTypeString;
1869 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001870 }
1871 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001872 }
1873 // Output:
1874 /* struct _objc_protocol {
1875 // Objective-C 1.0 extensions
1876 struct _objc_protocol_extension *isa;
1877 char *protocol_name;
1878 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001879 struct _objc_protocol_method_list *instance_methods;
1880 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00001881 };
1882 */
1883 static bool objc_protocol = false;
1884 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001885 Result += "\nstruct _objc_protocol {\n";
1886 Result += "\tstruct _objc_protocol_extension *isa;\n";
1887 Result += "\tchar *protocol_name;\n";
1888 Result += "\tstruct _objc_protocol **protocol_list;\n";
1889 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1890 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1891 Result += "};\n";
1892
1893 /* struct _objc_protocol_list {
1894 struct _objc_protocol_list *next;
1895 int protocol_count;
1896 struct _objc_protocol *class_protocols[];
1897 }
1898 */
1899 Result += "\nstruct _objc_protocol_list {\n";
1900 Result += "\tstruct _objc_protocol_list *next;\n";
1901 Result += "\tint protocol_count;\n";
1902 Result += "\tstruct _objc_protocol *class_protocols[];\n";
1903 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001904 objc_protocol = true;
1905 }
1906
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001907 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
1908 Result += PDecl->getName();
1909 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
1910 "{\n\t0, \"";
1911 Result += PDecl->getName();
1912 Result += "\", 0, ";
1913 if (PDecl->getInstanceMethods() > 0) {
1914 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
1915 Result += PDecl->getName();
1916 Result += ", ";
1917 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001918 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001919 Result += "0, ";
1920 if (PDecl->getClassMethods() > 0) {
1921 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
1922 Result += PDecl->getName();
1923 Result += "\n";
1924 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001925 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001926 Result += "0\n";
1927 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001928 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00001929 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001930 Result += "\nstatic struct _objc_protocol_list _OBJC_";
1931 Result += prefix;
1932 Result += "_PROTOCOLS_";
1933 Result += ClassName;
1934 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1935 "{\n\t0, ";
1936 Result += utostr(NumProtocols);
1937 Result += "\n";
1938
1939 Result += "\t,{&_OBJC_PROTOCOL_";
1940 Result += Protocols[0]->getName();
1941 Result += " \n";
1942
1943 for (int i = 1; i < NumProtocols; i++) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00001944 ObjcProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001945 Result += "\t ,&_OBJC_PROTOCOL_";
1946 Result += PDecl->getName();
1947 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00001948 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001949 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001950 }
1951}
1952
1953/// RewriteObjcCategoryImplDecl - Rewrite metadata for each category
1954/// implementation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001955void RewriteTest::RewriteObjcCategoryImplDecl(ObjcCategoryImplDecl *IDecl,
1956 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001957 ObjcInterfaceDecl *ClassDecl = IDecl->getClassInterface();
1958 // Find category declaration for this implementation.
1959 ObjcCategoryDecl *CDecl;
1960 for (CDecl = ClassDecl->getCategoryList(); CDecl;
1961 CDecl = CDecl->getNextClassCategory())
1962 if (CDecl->getIdentifier() == IDecl->getIdentifier())
1963 break;
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001964
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001965 char *FullCategoryName = (char*)alloca(
1966 strlen(ClassDecl->getName()) + strlen(IDecl->getName()) + 2);
1967 sprintf(FullCategoryName, "%s_%s", ClassDecl->getName(), IDecl->getName());
1968
1969 // Build _objc_method_list for class's instance methods if needed
1970 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
1971 IDecl->getNumInstanceMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001972 true,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001973 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001974
1975 // Build _objc_method_list for class's class methods if needed
1976 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
1977 IDecl->getNumClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00001978 false,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00001979 "CATEGORY_", FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001980
1981 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00001982 // Null CDecl is case of a category implementation with no category interface
1983 if (CDecl)
1984 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
1985 CDecl->getNumReferencedProtocols(),
1986 "CATEGORY",
1987 FullCategoryName, Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00001988
1989 /* struct _objc_category {
1990 char *category_name;
1991 char *class_name;
1992 struct _objc_method_list *instance_methods;
1993 struct _objc_method_list *class_methods;
1994 struct _objc_protocol_list *protocols;
1995 // Objective-C 1.0 extensions
1996 uint32_t size; // sizeof (struct _objc_category)
1997 struct _objc_property_list *instance_properties; // category's own
1998 // @property decl.
1999 };
2000 */
2001
2002 static bool objc_category = false;
2003 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002004 Result += "\nstruct _objc_category {\n";
2005 Result += "\tchar *category_name;\n";
2006 Result += "\tchar *class_name;\n";
2007 Result += "\tstruct _objc_method_list *instance_methods;\n";
2008 Result += "\tstruct _objc_method_list *class_methods;\n";
2009 Result += "\tstruct _objc_protocol_list *protocols;\n";
2010 Result += "\tunsigned int size;\n";
2011 Result += "\tstruct _objc_property_list *instance_properties;\n";
2012 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002013 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002014 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002015 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2016 Result += FullCategoryName;
2017 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2018 Result += IDecl->getName();
2019 Result += "\"\n\t, \"";
2020 Result += ClassDecl->getName();
2021 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002022
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002023 if (IDecl->getNumInstanceMethods() > 0) {
2024 Result += "\t, (struct _objc_method_list *)"
2025 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2026 Result += FullCategoryName;
2027 Result += "\n";
2028 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002029 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002030 Result += "\t, 0\n";
2031 if (IDecl->getNumClassMethods() > 0) {
2032 Result += "\t, (struct _objc_method_list *)"
2033 "&_OBJC_CATEGORY_CLASS_METHODS_";
2034 Result += FullCategoryName;
2035 Result += "\n";
2036 }
2037 else
2038 Result += "\t, 0\n";
2039
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002040 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002041 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2042 Result += FullCategoryName;
2043 Result += "\n";
2044 }
2045 else
2046 Result += "\t, 0\n";
2047 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002048}
2049
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002050/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2051/// ivar offset.
2052void RewriteTest::SynthesizeIvarOffsetComputation(ObjcImplementationDecl *IDecl,
2053 ObjcIvarDecl *ivar,
2054 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002055 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002056 Result += IDecl->getName();
2057 Result += ", ";
2058 Result += ivar->getName();
2059 Result += ")";
2060}
2061
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002062//===----------------------------------------------------------------------===//
2063// Meta Data Emission
2064//===----------------------------------------------------------------------===//
2065
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002066void RewriteTest::RewriteObjcClassMetaData(ObjcImplementationDecl *IDecl,
2067 std::string &Result) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002068 ObjcInterfaceDecl *CDecl = IDecl->getClassInterface();
2069
2070 // Build _objc_ivar_list metadata for classes ivars if needed
2071 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2072 ? IDecl->getImplDeclNumIvars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002073 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002074 // Explictly declared @interface's are already synthesized.
2075 if (CDecl->ImplicitInterfaceDecl()) {
2076 // FIXME: Implementation of a class with no @interface (legacy) doese not
2077 // produce correct synthesis as yet.
2078 SynthesizeObjcInternalStruct(CDecl, Result);
2079 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002080
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002081 if (NumIvars > 0) {
2082 static bool objc_ivar = false;
2083 if (!objc_ivar) {
2084 /* struct _objc_ivar {
2085 char *ivar_name;
2086 char *ivar_type;
2087 int ivar_offset;
2088 };
2089 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002090 Result += "\nstruct _objc_ivar {\n";
2091 Result += "\tchar *ivar_name;\n";
2092 Result += "\tchar *ivar_type;\n";
2093 Result += "\tint ivar_offset;\n";
2094 Result += "};\n";
2095
2096 /* struct _objc_ivar_list {
2097 int ivar_count;
2098 struct _objc_ivar ivar_list[];
2099 };
2100 */
2101 Result += "\nstruct _objc_ivar_list {\n";
2102 Result += "\tint ivar_count;\n";
2103 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002104 objc_ivar = true;
2105 }
2106
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002107 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2108 Result += IDecl->getName();
2109 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2110 "{\n\t";
2111 Result += utostr(NumIvars);
2112 Result += "\n";
2113
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002114 ObjcIvarDecl **Ivars = IDecl->getImplDeclIVars()
2115 ? IDecl->getImplDeclIVars()
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002116 : CDecl->getInstanceVariables();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002117 Result += "\t,{{\"";
2118 Result += Ivars[0]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002119 Result += "\", \"";
2120 std::string StrEncoding;
2121 Context->getObjcEncodingForType(Ivars[0]->getType(), StrEncoding);
2122 Result += StrEncoding;
2123 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002124 SynthesizeIvarOffsetComputation(IDecl, Ivars[0], Result);
2125 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002126 for (int i = 1; i < NumIvars; i++) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002127 Result += "\t ,{\"";
2128 Result += Ivars[i]->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002129 Result += "\", \"";
2130 std::string StrEncoding;
2131 Context->getObjcEncodingForType(Ivars[i]->getType(), StrEncoding);
2132 Result += StrEncoding;
2133 Result += "\", ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002134 SynthesizeIvarOffsetComputation(IDecl, Ivars[i], Result);
2135 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002136 }
2137
2138 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002139 }
2140
2141 // Build _objc_method_list for class's instance methods if needed
2142 RewriteObjcMethodsMetaData(IDecl->getInstanceMethods(),
2143 IDecl->getNumInstanceMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002144 true,
2145 "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002146
2147 // Build _objc_method_list for class's class methods if needed
2148 RewriteObjcMethodsMetaData(IDecl->getClassMethods(),
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002149 IDecl->getNumClassMethods(),
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002150 false,
2151 "", IDecl->getName(), Result);
2152
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002153 // Protocols referenced in class declaration?
2154 RewriteObjcProtocolsMetaData(CDecl->getReferencedProtocols(),
2155 CDecl->getNumIntfRefProtocols(),
2156 "CLASS",
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002157 CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002158
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002159
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002160 // Declaration of class/meta-class metadata
2161 /* struct _objc_class {
2162 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002163 const char *super_class_name;
2164 char *name;
2165 long version;
2166 long info;
2167 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002168 struct _objc_ivar_list *ivars;
2169 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002170 struct objc_cache *cache;
2171 struct objc_protocol_list *protocols;
2172 const char *ivar_layout;
2173 struct _objc_class_ext *ext;
2174 };
2175 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002176 static bool objc_class = false;
2177 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002178 Result += "\nstruct _objc_class {\n";
2179 Result += "\tstruct _objc_class *isa;\n";
2180 Result += "\tconst char *super_class_name;\n";
2181 Result += "\tchar *name;\n";
2182 Result += "\tlong version;\n";
2183 Result += "\tlong info;\n";
2184 Result += "\tlong instance_size;\n";
2185 Result += "\tstruct _objc_ivar_list *ivars;\n";
2186 Result += "\tstruct _objc_method_list *methods;\n";
2187 Result += "\tstruct objc_cache *cache;\n";
2188 Result += "\tstruct _objc_protocol_list *protocols;\n";
2189 Result += "\tconst char *ivar_layout;\n";
2190 Result += "\tstruct _objc_class_ext *ext;\n";
2191 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002192 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002193 }
2194
2195 // Meta-class metadata generation.
2196 ObjcInterfaceDecl *RootClass = 0;
2197 ObjcInterfaceDecl *SuperClass = CDecl->getSuperClass();
2198 while (SuperClass) {
2199 RootClass = SuperClass;
2200 SuperClass = SuperClass->getSuperClass();
2201 }
2202 SuperClass = CDecl->getSuperClass();
2203
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002204 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2205 Result += CDecl->getName();
2206 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2207 "{\n\t(struct _objc_class *)\"";
2208 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2209 Result += "\"";
2210
2211 if (SuperClass) {
2212 Result += ", \"";
2213 Result += SuperClass->getName();
2214 Result += "\", \"";
2215 Result += CDecl->getName();
2216 Result += "\"";
2217 }
2218 else {
2219 Result += ", 0, \"";
2220 Result += CDecl->getName();
2221 Result += "\"";
2222 }
Fariborz Jahanian771d3b92007-12-04 19:31:56 +00002223 // Set 'ivars' field for root class to 0. Objc1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002224 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002225 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002226 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002227 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002228 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002229 Result += "\n";
2230 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002231 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002232 Result += ", 0\n";
2233 if (CDecl->getNumIntfRefProtocols() > 0) {
2234 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2235 Result += CDecl->getName();
2236 Result += ",0,0\n";
2237 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002238 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002239 Result += "\t,0,0,0,0\n";
2240 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002241
2242 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002243 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2244 Result += CDecl->getName();
2245 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2246 "{\n\t&_OBJC_METACLASS_";
2247 Result += CDecl->getName();
2248 if (SuperClass) {
2249 Result += ", \"";
2250 Result += SuperClass->getName();
2251 Result += "\", \"";
2252 Result += CDecl->getName();
2253 Result += "\"";
2254 }
2255 else {
2256 Result += ", 0, \"";
2257 Result += CDecl->getName();
2258 Result += "\"";
2259 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002260 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002261 Result += ", 0,1";
2262 if (!ObjcSynthesizedStructs.count(CDecl))
2263 Result += ",0";
2264 else {
2265 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002266 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002267 Result += CDecl->getName();
2268 Result += ")";
2269 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002270 if (NumIvars > 0) {
2271 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2272 Result += CDecl->getName();
2273 Result += "\n\t";
2274 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002275 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002276 Result += ",0";
2277 if (IDecl->getNumInstanceMethods() > 0) {
2278 Result += ", &_OBJC_INSTANCE_METHODS_";
2279 Result += CDecl->getName();
2280 Result += ", 0\n\t";
2281 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002282 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002283 Result += ",0,0";
2284 if (CDecl->getNumIntfRefProtocols() > 0) {
2285 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2286 Result += CDecl->getName();
2287 Result += ", 0,0\n";
2288 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002289 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002290 Result += ",0,0,0\n";
2291 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002292}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002293
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002294/// RewriteImplementations - This routine rewrites all method implementations
2295/// and emits meta-data.
2296
2297void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002298 int ClsDefCount = ClassImplementation.size();
2299 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002300
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002301 if (ClsDefCount == 0 && CatDefCount == 0)
2302 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002303 // Rewrite implemented methods
2304 for (int i = 0; i < ClsDefCount; i++)
2305 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002306
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002307 for (int i = 0; i < CatDefCount; i++)
2308 RewriteImplementationDecl(CategoryImplementation[i]);
2309
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002310 // This is needed for use of offsetof
2311 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002312
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002313 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002314 for (int i = 0; i < ClsDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002315 RewriteObjcClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002316
2317 // For each implemented category, write out all its meta data.
2318 for (int i = 0; i < CatDefCount; i++)
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002319 RewriteObjcCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002320
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002321 // Write objc_symtab metadata
2322 /*
2323 struct _objc_symtab
2324 {
2325 long sel_ref_cnt;
2326 SEL *refs;
2327 short cls_def_cnt;
2328 short cat_def_cnt;
2329 void *defs[cls_def_cnt + cat_def_cnt];
2330 };
2331 */
2332
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002333 Result += "\nstruct _objc_symtab {\n";
2334 Result += "\tlong sel_ref_cnt;\n";
2335 Result += "\tSEL *refs;\n";
2336 Result += "\tshort cls_def_cnt;\n";
2337 Result += "\tshort cat_def_cnt;\n";
2338 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2339 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002340
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002341 Result += "static struct _objc_symtab "
2342 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2343 Result += "\t0, 0, " + utostr(ClsDefCount)
2344 + ", " + utostr(CatDefCount) + "\n";
2345 for (int i = 0; i < ClsDefCount; i++) {
2346 Result += "\t,&_OBJC_CLASS_";
2347 Result += ClassImplementation[i]->getName();
2348 Result += "\n";
2349 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002350
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002351 for (int i = 0; i < CatDefCount; i++) {
2352 Result += "\t,&_OBJC_CATEGORY_";
2353 Result += CategoryImplementation[i]->getClassInterface()->getName();
2354 Result += "_";
2355 Result += CategoryImplementation[i]->getName();
2356 Result += "\n";
2357 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002358
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002359 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002360
2361 // Write objc_module metadata
2362
2363 /*
2364 struct _objc_module {
2365 long version;
2366 long size;
2367 const char *name;
2368 struct _objc_symtab *symtab;
2369 }
2370 */
2371
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002372 Result += "\nstruct _objc_module {\n";
2373 Result += "\tlong version;\n";
2374 Result += "\tlong size;\n";
2375 Result += "\tconst char *name;\n";
2376 Result += "\tstruct _objc_symtab *symtab;\n";
2377 Result += "};\n\n";
2378 Result += "static struct _objc_module "
2379 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002380 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2381 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002382 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002383
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002384}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002385