blob: 93c9838a910a5aacf4cfee74fbffe512f8bf8288 [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff874e2322007-11-15 10:28:18 +000025#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000026using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000027using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000028
Chris Lattner77cd2a02007-10-11 00:43:27 +000029namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000030 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000031 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000032 Diagnostic &Diags;
Chris Lattner01c57482007-10-17 22:35:30 +000033 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000035 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000036 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000037 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000038 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
39 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
40 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
41 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
42 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Steve Naroffebf2b562007-10-23 23:50:29 +000043
44 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000045 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000046 FunctionDecl *MsgSendStretFunctionDecl;
47 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000048 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000049 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000050 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000051 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000052 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000053 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000054
Steve Naroffbeaf2992007-11-03 11:27:19 +000055 // ObjC string constant support.
56 FileVarDecl *ConstantStringClassReference;
57 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000058
Steve Naroff874e2322007-11-15 10:28:18 +000059 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000060 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000061 RecordDecl *SuperStructDecl;
62
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000063 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 public:
Ted Kremenek95041a22007-12-19 22:51:13 +000065 void Initialize(ASTContext &context) {
Chris Lattner01c57482007-10-17 22:35:30 +000066 Context = &context;
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000067 SM = &Context->getSourceManager();
Steve Naroffebf2b562007-10-23 23:50:29 +000068 MsgSendFunctionDecl = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000069 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000070 MsgSendStretFunctionDecl = 0;
71 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000072 MsgSendFpretFunctionDecl = 0;
Steve Naroffc0006092007-10-24 01:09:48 +000073 GetClassFunctionDecl = 0;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000074 GetMetaClassFunctionDecl = 0;
Steve Naroff934f2762007-10-24 22:48:43 +000075 SelGetUidFunctionDecl = 0;
Steve Naroff96984642007-11-08 14:30:50 +000076 CFStringFunctionDecl = 0;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000077 GetProtocolFunctionDecl = 0;
Steve Naroffbeaf2992007-11-03 11:27:19 +000078 ConstantStringClassReference = 0;
79 NSStringRecord = 0;
Steve Naroff874e2322007-11-15 10:28:18 +000080 CurMethodDecl = 0;
81 SuperStructDecl = 0;
82
Chris Lattner26de4652007-12-02 01:13:47 +000083 // Get the ID and start/end of the main file.
Ted Kremenek95041a22007-12-19 22:51:13 +000084 MainFileID = SM->getMainFileID();
Chris Lattner26de4652007-12-02 01:13:47 +000085 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
86 MainFileStart = MainBuf->getBufferStart();
87 MainFileEnd = MainBuf->getBufferEnd();
88
89
Ted Kremenek7a9d49f2007-12-11 21:27:55 +000090 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroffe3abbf52007-11-05 14:55:35 +000091 // declaring objc_selector outside the parameter list removes a silly
92 // scope related warning...
Steve Naroff3cadd032007-12-04 23:59:30 +000093 const char *s = "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000094 "#ifndef OBJC_SUPER\n"
95 "struct objc_super { struct objc_object *o; "
96 "struct objc_object *superClass; };\n"
97 "#define OBJC_SUPER\n"
98 "#endif\n"
99 "#ifndef _REWRITER_typedef_Protocol\n"
100 "typedef struct objc_object Protocol;\n"
101 "#define _REWRITER_typedef_Protocol\n"
102 "#endif\n"
Steve Naroffe3abbf52007-11-05 14:55:35 +0000103 "extern struct objc_object *objc_msgSend"
Steve Naroffab972d32007-11-04 22:37:50 +0000104 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff874e2322007-11-15 10:28:18 +0000105 "extern struct objc_object *objc_msgSendSuper"
106 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000107 "extern struct objc_object *objc_msgSend_stret"
108 "(struct objc_object *, struct objc_selector *, ...);\n"
109 "extern struct objc_object *objc_msgSendSuper_stret"
110 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000111 "extern struct objc_object *objc_msgSend_fpret"
112 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroffab972d32007-11-04 22:37:50 +0000113 "extern struct objc_object *objc_getClass"
Steve Naroff21867b12007-11-07 18:43:40 +0000114 "(const char *);\n"
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000115 "extern struct objc_object *objc_getMetaClass"
116 "(const char *);\n"
Steve Naroff21867b12007-11-07 18:43:40 +0000117 "extern void objc_exception_throw(struct objc_object *);\n"
118 "extern void objc_exception_try_enter(void *);\n"
119 "extern void objc_exception_try_exit(void *);\n"
120 "extern struct objc_object *objc_exception_extract(void *);\n"
121 "extern int objc_exception_match"
Fariborz Jahanian95673922007-11-14 22:26:25 +0000122 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000123 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian2c1e9c72007-12-03 23:04:29 +0000124 "#include <objc/objc.h>\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000125
Ted Kremenek95041a22007-12-19 22:51:13 +0000126 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
Steve Naroffab972d32007-11-04 22:37:50 +0000127 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000128 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000129
Chris Lattnerf04da132007-10-24 17:06:59 +0000130 // Top Level Driver code.
131 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000132 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000133 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 ~RewriteTest();
135
136 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000137 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000138 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000139 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000140 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
141 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000142 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000143 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
144 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
145 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
146 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
147 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
148 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000149 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000150 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000151 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000152 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000153 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000156 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000157 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000158 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000159 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000160 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000161 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000162 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000163 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
164 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
165 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
166 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000167 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
168 Expr **args, unsigned nargs);
Steve Naroff09b266e2007-10-30 23:14:51 +0000169 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000170 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000171 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000172 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000173 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000174 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000175 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000176 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000177 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000178 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000179
Chris Lattnerf04da132007-10-24 17:06:59 +0000180 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000181 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000182 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000183
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000184 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000185 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000186
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000187 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
188 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000189 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000190 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000191 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000192 const char *ClassName,
193 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000194
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000195 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000196 int NumProtocols,
197 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000198 const char *ClassName,
199 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000200 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000201 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
203 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000204 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000205 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000206 };
207}
208
Chris Lattnere365c502007-11-30 22:25:36 +0000209ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
210 return new RewriteTest(Diags);
211}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000212
Chris Lattnerf04da132007-10-24 17:06:59 +0000213//===----------------------------------------------------------------------===//
214// Top Level Driver Code
215//===----------------------------------------------------------------------===//
216
Chris Lattner8a12c272007-10-11 18:38:32 +0000217void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000218 // Two cases: either the decl could be in the main file, or it could be in a
219 // #included file. If the former, rewrite it now. If the later, check to see
220 // if we rewrote the #include/#import.
221 SourceLocation Loc = D->getLocation();
222 Loc = SM->getLogicalLoc(Loc);
223
224 // If this is for a builtin, ignore it.
225 if (Loc.isInvalid()) return;
226
Steve Naroffebf2b562007-10-23 23:50:29 +0000227 // Look for built-in declarations that we need to refer during the rewrite.
228 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000229 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000230 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
231 // declared in <Foundation/NSString.h>
232 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
233 ConstantStringClassReference = FVD;
234 return;
235 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000236 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000237 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000238 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000239 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000240 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000241 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000242 } else if (ObjCForwardProtocolDecl *FP =
243 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000244 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000245 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000246 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000247 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
248 return HandleDeclInMainFile(D);
249
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 // Otherwise, see if there is a #import in the main file that should be
251 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000252 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000253}
254
Chris Lattnerf04da132007-10-24 17:06:59 +0000255/// HandleDeclInMainFile - This is called for each top-level decl defined in the
256/// main file of the input.
257void RewriteTest::HandleDeclInMainFile(Decl *D) {
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
259 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000260 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000261
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000262 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000263 if (Stmt *Body = MD->getBody()) {
264 //Body->dump();
265 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000266 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000267 CurMethodDecl = 0;
268 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000269 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000270 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000271 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000272 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000273 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000274 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000275 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000276 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000277 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000278 if (VD->getInit())
279 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
280 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000281 // Nothing yet.
282}
283
284RewriteTest::~RewriteTest() {
285 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000286
287 // Rewrite tabs if we care.
288 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000289
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000290 // Rewrite Objective-c meta data*
291 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000292 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000293
Chris Lattnerf04da132007-10-24 17:06:59 +0000294 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
295 // we are done.
296 if (const RewriteBuffer *RewriteBuf =
297 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000298 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000299 std::string S(RewriteBuf->begin(), RewriteBuf->end());
300 printf("%s\n", S.c_str());
301 } else {
302 printf("No changes\n");
303 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000304 // Emit metadata.
305 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000306}
307
Chris Lattnerf04da132007-10-24 17:06:59 +0000308//===----------------------------------------------------------------------===//
309// Syntactic (non-AST) Rewriting Code
310//===----------------------------------------------------------------------===//
311
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000312void RewriteTest::RewriteInclude(SourceLocation Loc) {
313 // Rip up the #include stack to the main file.
314 SourceLocation IncLoc = Loc, NextLoc = Loc;
315 do {
316 IncLoc = Loc;
317 Loc = SM->getLogicalLoc(NextLoc);
318 NextLoc = SM->getIncludeLoc(Loc);
319 } while (!NextLoc.isInvalid());
320
321 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
322 // IncLoc indicates the header that was included if it is useful.
323 IncLoc = SM->getLogicalLoc(IncLoc);
324 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
325 Loc == LastIncLoc)
326 return;
327 LastIncLoc = Loc;
328
329 unsigned IncCol = SM->getColumnNumber(Loc);
330 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
331
332 // Replace the #import with #include.
333 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
334}
335
Chris Lattnerf04da132007-10-24 17:06:59 +0000336void RewriteTest::RewriteTabs() {
337 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
338 const char *MainBufStart = MainBuf.first;
339 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000340
Chris Lattnerf04da132007-10-24 17:06:59 +0000341 // Loop over the whole file, looking for tabs.
342 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
343 if (*BufPtr != '\t')
344 continue;
345
346 // Okay, we found a tab. This tab will turn into at least one character,
347 // but it depends on which 'virtual column' it is in. Compute that now.
348 unsigned VCol = 0;
349 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
350 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
351 ++VCol;
352
353 // Okay, now that we know the virtual column, we know how many spaces to
354 // insert. We assume 8-character tab-stops.
355 unsigned Spaces = 8-(VCol & 7);
356
357 // Get the location of the tab.
358 SourceLocation TabLoc =
359 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
360
361 // Rewrite the single tab character into a sequence of spaces.
362 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
363 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000364}
365
366
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000367void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000368 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000369 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000370
371 // Get the start location and compute the semi location.
372 SourceLocation startLoc = ClassDecl->getLocation();
373 const char *startBuf = SM->getCharacterData(startLoc);
374 const char *semiPtr = strchr(startBuf, ';');
375
376 // Translate to typedef's that forward reference structs with the same name
377 // as the class. As a convenience, we include the original declaration
378 // as a comment.
379 std::string typedefString;
380 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000381 typedefString.append(startBuf, semiPtr-startBuf+1);
382 typedefString += "\n";
383 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000384 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000385 typedefString += "#ifndef _REWRITER_typedef_";
386 typedefString += ForwardDecl->getName();
387 typedefString += "\n";
388 typedefString += "#define _REWRITER_typedef_";
389 typedefString += ForwardDecl->getName();
390 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000391 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000392 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000393 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000394 }
395
396 // Replace the @class with typedefs corresponding to the classes.
397 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
398 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000399}
400
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000401void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000402 SourceLocation LocStart = Method->getLocStart();
403 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000404
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000405 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
406 Rewrite.InsertText(LocStart, "/* ", 3);
407 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
408 } else {
409 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000410 }
411}
412
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000413void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000414{
415 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000416 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000417 SourceLocation Loc = Property->getLocation();
418
419 Rewrite.ReplaceText(Loc, 0, "// ", 3);
420
421 // FIXME: handle properties that are declared across multiple lines.
422 }
423}
424
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000425void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000426 SourceLocation LocStart = CatDecl->getLocStart();
427
428 // FIXME: handle category headers that are declared across multiple lines.
429 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
430
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000431 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000432 E = CatDecl->instmeth_end(); I != E; ++I)
433 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000434 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000435 E = CatDecl->classmeth_end(); I != E; ++I)
436 RewriteMethodDeclaration(*I);
437
Steve Naroff423cb562007-10-30 13:30:57 +0000438 // Lastly, comment out the @end.
439 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
440}
441
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000442void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000443 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000444
Steve Naroff752d6ef2007-10-30 16:42:30 +0000445 SourceLocation LocStart = PDecl->getLocStart();
446
447 // FIXME: handle protocol headers that are declared across multiple lines.
448 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
449
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000450 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000451 E = PDecl->instmeth_end(); I != E; ++I)
452 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000453 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000454 E = PDecl->classmeth_end(); I != E; ++I)
455 RewriteMethodDeclaration(*I);
456
Steve Naroff752d6ef2007-10-30 16:42:30 +0000457 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000458 SourceLocation LocEnd = PDecl->getAtEndLoc();
459 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000460
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000461 // Must comment out @optional/@required
462 const char *startBuf = SM->getCharacterData(LocStart);
463 const char *endBuf = SM->getCharacterData(LocEnd);
464 for (const char *p = startBuf; p < endBuf; p++) {
465 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
466 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000467 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000468 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
469 CommentedOptional.c_str(), CommentedOptional.size());
470
471 }
472 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
473 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000474 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000475 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
476 CommentedRequired.c_str(), CommentedRequired.size());
477
478 }
479 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000480}
481
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000482void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000483 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000484 if (LocStart.isInvalid())
485 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000486 // FIXME: handle forward protocol that are declared across multiple lines.
487 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
488}
489
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000490void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000491 std::string &ResultStr) {
492 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000493 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000494 ResultStr += "id";
495 else
496 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000497 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000498
499 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000500 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000501
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000502 if (OMD->isInstance())
503 NameStr += "_I_";
504 else
505 NameStr += "_C_";
506
507 NameStr += OMD->getClassInterface()->getName();
508 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000509
510 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000511 if (ObjCCategoryImplDecl *CID =
512 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000513 NameStr += CID->getName();
514 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000515 }
516 // Append selector names, replacing ':' with '_'
517 const char *selName = OMD->getSelector().getName().c_str();
518 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000519 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000520 else {
521 std::string selString = OMD->getSelector().getName();
522 int len = selString.size();
523 for (int i = 0; i < len; i++)
524 if (selString[i] == ':')
525 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000526 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000527 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000528 // Remember this name for metadata emission
529 MethodInternalNames[OMD] = NameStr;
530 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000531
532 // Rewrite arguments
533 ResultStr += "(";
534
535 // invisible arguments
536 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000537 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000538 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000539 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000540 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000541 ResultStr += selfTy.getAsString();
542 }
543 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000544 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000545
546 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000547 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000548 ResultStr += " _cmd";
549
550 // Method arguments.
551 for (int i = 0; i < OMD->getNumParams(); i++) {
552 ParmVarDecl *PDecl = OMD->getParamDecl(i);
553 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000554 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000555 ResultStr += "id";
556 else
557 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000558 ResultStr += " ";
559 ResultStr += PDecl->getName();
560 }
561 ResultStr += ")";
562
563}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000564void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000565 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
566 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000567
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000568 if (IMD)
569 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
570 else
571 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000572
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000573 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000574 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
575 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000576 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000577 ObjCMethodDecl *OMD = *I;
578 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000579 SourceLocation LocStart = OMD->getLocStart();
580 SourceLocation LocEnd = OMD->getBody()->getLocStart();
581
582 const char *startBuf = SM->getCharacterData(LocStart);
583 const char *endBuf = SM->getCharacterData(LocEnd);
584 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
585 ResultStr.c_str(), ResultStr.size());
586 }
587
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000588 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000589 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
590 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000591 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000592 ObjCMethodDecl *OMD = *I;
593 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000594 SourceLocation LocStart = OMD->getLocStart();
595 SourceLocation LocEnd = OMD->getBody()->getLocStart();
596
597 const char *startBuf = SM->getCharacterData(LocStart);
598 const char *endBuf = SM->getCharacterData(LocEnd);
599 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
600 ResultStr.c_str(), ResultStr.size());
601 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000602 if (IMD)
603 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
604 else
605 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000606}
607
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000608void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000609 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000610 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000611 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000612 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000613 ResultStr += ClassDecl->getName();
614 ResultStr += "\n";
615 ResultStr += "#define _REWRITER_typedef_";
616 ResultStr += ClassDecl->getName();
617 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000618 ResultStr += "typedef struct ";
619 ResultStr += ClassDecl->getName();
620 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000621 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000622 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000623
624 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000625 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000626 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000627 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000628
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000629 RewriteProperties(ClassDecl->getNumPropertyDecl(),
630 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000631 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000632 E = ClassDecl->instmeth_end(); I != E; ++I)
633 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000634 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000635 E = ClassDecl->classmeth_end(); I != E; ++I)
636 RewriteMethodDeclaration(*I);
637
Steve Naroff2feac5e2007-10-30 03:43:13 +0000638 // Lastly, comment out the @end.
639 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000640}
641
Steve Naroff7e3411b2007-11-15 02:58:25 +0000642Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000643 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000644 if (IV->isFreeIvar()) {
645 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
646 IV->getLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +0000647 if (Rewrite.ReplaceStmt(IV, Replacement)) {
648 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000649 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
650 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000651 SourceRange Range = IV->getSourceRange();
652 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000653 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000654 delete IV;
655 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000656 } else {
657 if (CurMethodDecl) {
658 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000659 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000660 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
661 IdentifierInfo *II = intT->getDecl()->getIdentifier();
662 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
663 II, 0);
664 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
665
666 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
667 // Don't forget the parens to enforce the proper binding.
668 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroff5ca40202007-12-19 14:32:56 +0000669 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
670 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000671 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
672 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000673 SourceRange Range = IV->getBase()->getSourceRange();
674 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000675 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000676 delete IV->getBase();
677 return PE;
678 }
679 }
680 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000681 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000682 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000683}
684
Chris Lattnerf04da132007-10-24 17:06:59 +0000685//===----------------------------------------------------------------------===//
686// Function Body / Expression rewriting
687//===----------------------------------------------------------------------===//
688
Steve Narofff3473a72007-11-09 15:20:18 +0000689Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000690 // Otherwise, just rewrite all children.
691 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
692 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000693 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000694 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000695 if (newStmt)
696 *CI = newStmt;
697 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000698
699 // Handle specific things.
700 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
701 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000702
703 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
704 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000705
706 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
707 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000708
709 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
710 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000711
Steve Naroff934f2762007-10-24 22:48:43 +0000712 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
713 // Before we rewrite it, put the original message expression in a comment.
714 SourceLocation startLoc = MessExpr->getLocStart();
715 SourceLocation endLoc = MessExpr->getLocEnd();
716
717 const char *startBuf = SM->getCharacterData(startLoc);
718 const char *endBuf = SM->getCharacterData(endLoc);
719
720 std::string messString;
721 messString += "// ";
722 messString.append(startBuf, endBuf-startBuf+1);
723 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000724
Steve Naroff934f2762007-10-24 22:48:43 +0000725 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
726 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
727 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000728 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000729 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000730 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000731
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
733 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000734
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000735 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
736 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000737
738 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
739 return RewriteObjCProtocolExpr(ProtocolExp);
Steve Naroff874e2322007-11-15 10:28:18 +0000740#if 0
741 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
742 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
743 // Get the new text.
744 std::ostringstream Buf;
745 Replacement->printPretty(Buf);
746 const std::string &Str = Buf.str();
747
748 printf("CAST = %s\n", &Str[0]);
749 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
750 delete S;
751 return Replacement;
752 }
753#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000754 // Return this stmt unmodified.
755 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000756}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000757
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000758Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000759 // Get the start location and compute the semi location.
760 SourceLocation startLoc = S->getLocStart();
761 const char *startBuf = SM->getCharacterData(startLoc);
762
763 assert((*startBuf == '@') && "bogus @try location");
764
765 std::string buf;
766 // declare a new scope with two variables, _stack and _rethrow.
767 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
768 buf += "int buf[18/*32-bit i386*/];\n";
769 buf += "char *pointers[4];} _stack;\n";
770 buf += "id volatile _rethrow = 0;\n";
771 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000772 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000773
774 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
775
776 startLoc = S->getTryBody()->getLocEnd();
777 startBuf = SM->getCharacterData(startLoc);
778
779 assert((*startBuf == '}') && "bogus @try block");
780
781 SourceLocation lastCurlyLoc = startLoc;
782
783 startLoc = startLoc.getFileLocWithOffset(1);
784 buf = " /* @catch begin */ else {\n";
785 buf += " id _caught = objc_exception_extract(&_stack);\n";
786 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000787 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000788 buf += " _rethrow = objc_exception_extract(&_stack);\n";
789 buf += " else { /* @catch continue */";
790
Chris Lattner28d1fe82007-11-08 04:41:51 +0000791 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000792
793 bool sawIdTypedCatch = false;
794 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000795 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +0000796 while (catchList) {
797 Stmt *catchStmt = catchList->getCatchParamStmt();
798
799 if (catchList == S->getCatchStmts())
800 buf = "if ("; // we are generating code for the first catch clause
801 else
802 buf = "else if (";
803 startLoc = catchList->getLocStart();
804 startBuf = SM->getCharacterData(startLoc);
805
806 assert((*startBuf == '@') && "bogus @catch location");
807
808 const char *lParenLoc = strchr(startBuf, '(');
809
810 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
811 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000812 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +0000813 buf += "1) { ";
814 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
815 buf.c_str(), buf.size());
816 sawIdTypedCatch = true;
817 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000818 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +0000819
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000820 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +0000821 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000822 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000823 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000824 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000825 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
826 buf.c_str(), buf.size());
827 }
828 }
829 // Now rewrite the body...
830 lastCatchBody = catchList->getCatchBody();
831 SourceLocation rParenLoc = catchList->getRParenLoc();
832 SourceLocation bodyLoc = lastCatchBody->getLocStart();
833 const char *bodyBuf = SM->getCharacterData(bodyLoc);
834 const char *rParenBuf = SM->getCharacterData(rParenLoc);
835 assert((*rParenBuf == ')') && "bogus @catch paren location");
836 assert((*bodyBuf == '{') && "bogus @catch body location");
837
838 buf = " = _caught;";
839 // Here we replace ") {" with "= _caught;" (which initializes and
840 // declares the @catch parameter).
841 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
842 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +0000843 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +0000844 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +0000845 }
Steve Naroff75730982007-11-07 04:08:17 +0000846 catchList = catchList->getNextCatchStmt();
847 }
848 // Complete the catch list...
849 if (lastCatchBody) {
850 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
851 const char *bodyBuf = SM->getCharacterData(bodyLoc);
852 assert((*bodyBuf == '}') && "bogus @catch body location");
853 bodyLoc = bodyLoc.getFileLocWithOffset(1);
854 buf = " } } /* @catch end */\n";
855
Chris Lattner28d1fe82007-11-08 04:41:51 +0000856 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000857
858 // Set lastCurlyLoc
859 lastCurlyLoc = lastCatchBody->getLocEnd();
860 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000861 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +0000862 startLoc = finalStmt->getLocStart();
863 startBuf = SM->getCharacterData(startLoc);
864 assert((*startBuf == '@') && "bogus @finally start");
865
866 buf = "/* @finally */";
867 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
868
869 Stmt *body = finalStmt->getFinallyBody();
870 SourceLocation startLoc = body->getLocStart();
871 SourceLocation endLoc = body->getLocEnd();
872 const char *startBuf = SM->getCharacterData(startLoc);
873 const char *endBuf = SM->getCharacterData(endLoc);
874 assert((*startBuf == '{') && "bogus @finally body location");
875 assert((*endBuf == '}') && "bogus @finally body location");
876
877 startLoc = startLoc.getFileLocWithOffset(1);
878 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000879 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000880 endLoc = endLoc.getFileLocWithOffset(-1);
881 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000882 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000883
884 // Set lastCurlyLoc
885 lastCurlyLoc = body->getLocEnd();
886 }
887 // Now emit the final closing curly brace...
888 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
889 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +0000890 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000891 return 0;
892}
893
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000894Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000895 return 0;
896}
897
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000898Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000899 return 0;
900}
901
Steve Naroff2bd03922007-11-07 15:32:26 +0000902// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
903// the throw expression is typically a message expression that's already
904// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000905Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +0000906 // Get the start location and compute the semi location.
907 SourceLocation startLoc = S->getLocStart();
908 const char *startBuf = SM->getCharacterData(startLoc);
909
910 assert((*startBuf == '@') && "bogus @throw location");
911
912 std::string buf;
913 /* void objc_exception_throw(id) __attribute__((noreturn)); */
914 buf = "objc_exception_throw(";
915 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
916 const char *semiBuf = strchr(startBuf, ';');
917 assert((*semiBuf == ';') && "@throw: can't find ';'");
918 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
919 buf = ");";
920 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
921 return 0;
922}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000923
Chris Lattnere64b7772007-10-24 16:57:36 +0000924Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +0000925 // Create a new string expression.
926 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000927 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000928 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +0000929 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
930 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +0000931 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +0000932 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
933 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000934 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
935 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner182745a2007-12-02 01:09:57 +0000936 SourceRange Range = Exp->getSourceRange();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000937 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattnere365c502007-11-30 22:25:36 +0000938 }
939
Chris Lattner07506182007-11-30 22:53:43 +0000940 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +0000941 delete Exp;
942 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +0000943}
944
Steve Naroffb42f8412007-11-05 14:50:49 +0000945Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
946 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
947 // Create a call to sel_registerName("selName").
948 llvm::SmallVector<Expr*, 8> SelExprs;
949 QualType argType = Context->getPointerType(Context->CharTy);
950 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
951 Exp->getSelector().getName().size(),
952 false, argType, SourceLocation(),
953 SourceLocation()));
954 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
955 &SelExprs[0], SelExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +0000956 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
957 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000958 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
959 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000960 SourceRange Range = Exp->getSourceRange();
961 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000962 }
Steve Naroffb42f8412007-11-05 14:50:49 +0000963 delete Exp;
964 return SelExp;
965}
966
Steve Naroff934f2762007-10-24 22:48:43 +0000967CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
968 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +0000969 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +0000970 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +0000971
972 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +0000973 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +0000974
975 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +0000976 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +0000977 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
978
979 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +0000980
Steve Naroff934f2762007-10-24 22:48:43 +0000981 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
982}
983
Steve Naroffd5255f52007-11-01 13:24:47 +0000984static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
985 const char *&startRef, const char *&endRef) {
986 while (startBuf < endBuf) {
987 if (*startBuf == '<')
988 startRef = startBuf; // mark the start.
989 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +0000990 if (startRef && *startRef == '<') {
991 endRef = startBuf; // mark the end.
992 return true;
993 }
994 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +0000995 }
996 startBuf++;
997 }
998 return false;
999}
1000
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001001static void scanToNextArgument(const char *&argRef) {
1002 int angle = 0;
1003 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1004 if (*argRef == '<')
1005 angle++;
1006 else if (*argRef == '>')
1007 angle--;
1008 argRef++;
1009 }
1010 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1011}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001012
Steve Naroffd5255f52007-11-01 13:24:47 +00001013bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001014
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001015 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001016 return true;
1017
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001018 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001019 return true;
1020
Steve Naroffd5255f52007-11-01 13:24:47 +00001021 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001022 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001023 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001024 return true; // we have "Class <Protocol> *".
1025 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001026 return false;
1027}
1028
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001029void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001030 SourceLocation Loc;
1031 QualType Type;
1032 const FunctionTypeProto *proto = 0;
1033 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1034 Loc = VD->getLocation();
1035 Type = VD->getType();
1036 }
1037 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1038 Loc = FD->getLocation();
1039 // Check for ObjC 'id' and class types that have been adorned with protocol
1040 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1041 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1042 assert(funcType && "missing function type");
1043 proto = dyn_cast<FunctionTypeProto>(funcType);
1044 if (!proto)
1045 return;
1046 Type = proto->getResultType();
1047 }
1048 else
1049 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001050
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001051 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001052 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001053
1054 const char *endBuf = SM->getCharacterData(Loc);
1055 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001056 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001057 startBuf--; // scan backward (from the decl location) for return type.
1058 const char *startRef = 0, *endRef = 0;
1059 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1060 // Get the locations of the startRef, endRef.
1061 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1062 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1063 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001064 Rewrite.InsertText(LessLoc, "/*", 2);
1065 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001066 }
1067 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001068 if (!proto)
1069 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001070 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001071 const char *startBuf = SM->getCharacterData(Loc);
1072 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001073 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1074 if (needToScanForQualifiers(proto->getArgType(i))) {
1075 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001076
Steve Naroffd5255f52007-11-01 13:24:47 +00001077 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001078 // scan forward (from the decl location) for argument types.
1079 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001080 const char *startRef = 0, *endRef = 0;
1081 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1082 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001083 SourceLocation LessLoc =
1084 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1085 SourceLocation GreaterLoc =
1086 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001087 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001088 Rewrite.InsertText(LessLoc, "/*", 2);
1089 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001090 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001091 startBuf = ++endBuf;
1092 }
1093 else {
1094 while (*startBuf != ')' && *startBuf != ',')
1095 startBuf++; // scan forward (from the decl location) for argument types.
1096 startBuf++;
1097 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001098 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001099}
1100
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001101// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1102void RewriteTest::SynthSelGetUidFunctionDecl() {
1103 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1104 llvm::SmallVector<QualType, 16> ArgTys;
1105 ArgTys.push_back(Context->getPointerType(
1106 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001107 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001108 &ArgTys[0], ArgTys.size(),
1109 false /*isVariadic*/);
1110 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1111 SelGetUidIdent, getFuncType,
1112 FunctionDecl::Extern, false, 0);
1113}
1114
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001115// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1116void RewriteTest::SynthGetProtocolFunctionDecl() {
1117 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1118 llvm::SmallVector<QualType, 16> ArgTys;
1119 ArgTys.push_back(Context->getPointerType(
1120 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001121 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001122 &ArgTys[0], ArgTys.size(),
1123 false /*isVariadic*/);
1124 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1125 SelGetProtoIdent, getFuncType,
1126 FunctionDecl::Extern, false, 0);
1127}
1128
Steve Naroff09b266e2007-10-30 23:14:51 +00001129void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1130 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001131 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001132 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001133 return;
1134 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001135 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001136}
1137
1138// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1139void RewriteTest::SynthMsgSendFunctionDecl() {
1140 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1141 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001142 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001143 assert(!argT.isNull() && "Can't find 'id' type");
1144 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001145 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001146 assert(!argT.isNull() && "Can't find 'SEL' type");
1147 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001149 &ArgTys[0], ArgTys.size(),
1150 true /*isVariadic*/);
1151 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1152 msgSendIdent, msgSendType,
1153 FunctionDecl::Extern, false, 0);
1154}
1155
Steve Naroff874e2322007-11-15 10:28:18 +00001156// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1157void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1158 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1159 llvm::SmallVector<QualType, 16> ArgTys;
1160 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1161 &Context->Idents.get("objc_super"), 0);
1162 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1163 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1164 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001165 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001166 assert(!argT.isNull() && "Can't find 'SEL' type");
1167 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001168 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001169 &ArgTys[0], ArgTys.size(),
1170 true /*isVariadic*/);
1171 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1172 msgSendIdent, msgSendType,
1173 FunctionDecl::Extern, false, 0);
1174}
1175
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001176// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1177void RewriteTest::SynthMsgSendStretFunctionDecl() {
1178 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1179 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001180 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001181 assert(!argT.isNull() && "Can't find 'id' type");
1182 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001183 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001184 assert(!argT.isNull() && "Can't find 'SEL' type");
1185 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001186 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001187 &ArgTys[0], ArgTys.size(),
1188 true /*isVariadic*/);
1189 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1190 msgSendIdent, msgSendType,
1191 FunctionDecl::Extern, false, 0);
1192}
1193
1194// SynthMsgSendSuperStretFunctionDecl -
1195// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1196void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1197 IdentifierInfo *msgSendIdent =
1198 &Context->Idents.get("objc_msgSendSuper_stret");
1199 llvm::SmallVector<QualType, 16> ArgTys;
1200 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1201 &Context->Idents.get("objc_super"), 0);
1202 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1203 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1204 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001205 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001206 assert(!argT.isNull() && "Can't find 'SEL' type");
1207 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001208 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001209 &ArgTys[0], ArgTys.size(),
1210 true /*isVariadic*/);
1211 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1212 msgSendIdent, msgSendType,
1213 FunctionDecl::Extern, false, 0);
1214}
1215
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001216// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1217void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1218 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1219 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001220 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001221 assert(!argT.isNull() && "Can't find 'id' type");
1222 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001223 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001224 assert(!argT.isNull() && "Can't find 'SEL' type");
1225 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001226 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001227 &ArgTys[0], ArgTys.size(),
1228 true /*isVariadic*/);
1229 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1230 msgSendIdent, msgSendType,
1231 FunctionDecl::Extern, false, 0);
1232}
1233
Steve Naroff09b266e2007-10-30 23:14:51 +00001234// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1235void RewriteTest::SynthGetClassFunctionDecl() {
1236 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1237 llvm::SmallVector<QualType, 16> ArgTys;
1238 ArgTys.push_back(Context->getPointerType(
1239 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001240 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001241 &ArgTys[0], ArgTys.size(),
1242 false /*isVariadic*/);
1243 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1244 getClassIdent, getClassType,
1245 FunctionDecl::Extern, false, 0);
1246}
1247
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001248// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1249void RewriteTest::SynthGetMetaClassFunctionDecl() {
1250 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1251 llvm::SmallVector<QualType, 16> ArgTys;
1252 ArgTys.push_back(Context->getPointerType(
1253 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001254 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001255 &ArgTys[0], ArgTys.size(),
1256 false /*isVariadic*/);
1257 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1258 getClassIdent, getClassType,
1259 FunctionDecl::Extern, false, 0);
1260}
1261
Steve Naroff96984642007-11-08 14:30:50 +00001262// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1263void RewriteTest::SynthCFStringFunctionDecl() {
1264 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1265 llvm::SmallVector<QualType, 16> ArgTys;
1266 ArgTys.push_back(Context->getPointerType(
1267 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001268 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001269 &ArgTys[0], ArgTys.size(),
1270 false /*isVariadic*/);
1271 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1272 getClassIdent, getClassType,
1273 FunctionDecl::Extern, false, 0);
1274}
1275
Steve Naroffbeaf2992007-11-03 11:27:19 +00001276Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001277#if 1
1278 // This rewrite is specific to GCC, which has builtin support for CFString.
1279 if (!CFStringFunctionDecl)
1280 SynthCFStringFunctionDecl();
1281 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1282 llvm::SmallVector<Expr*, 8> StrExpr;
1283 StrExpr.push_back(Exp->getString());
1284 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1285 &StrExpr[0], StrExpr.size());
1286 // cast to NSConstantString *
1287 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +00001288 if (Rewrite.ReplaceStmt(Exp, cast)) {
1289 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001290 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1291 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001292 SourceRange Range = Exp->getSourceRange();
1293 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001294 }
Steve Naroff96984642007-11-08 14:30:50 +00001295 delete Exp;
1296 return cast;
1297#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001298 assert(ConstantStringClassReference && "Can't find constant string reference");
1299 llvm::SmallVector<Expr*, 4> InitExprs;
1300
1301 // Synthesize "(Class)&_NSConstantStringClassReference"
1302 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1303 ConstantStringClassReference->getType(),
1304 SourceLocation());
1305 QualType expType = Context->getPointerType(ClsRef->getType());
1306 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1307 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001308 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001309 SourceLocation());
1310 InitExprs.push_back(cast); // set the 'isa'.
1311 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1312 unsigned IntSize = static_cast<unsigned>(
1313 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1314 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1315 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1316 Exp->getLocStart());
1317 InitExprs.push_back(len); // set "int numBytes".
1318
1319 // struct NSConstantString
1320 QualType CFConstantStrType = Context->getCFConstantStringType();
1321 // (struct NSConstantString) { <exprs from above> }
1322 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1323 &InitExprs[0], InitExprs.size(),
1324 SourceLocation());
1325 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1326 // struct NSConstantString *
1327 expType = Context->getPointerType(StrRep->getType());
1328 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1329 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001330 // cast to NSConstantString *
1331 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001332 Rewrite.ReplaceStmt(Exp, cast);
1333 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001334 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001335#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001336}
1337
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001338ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001339 // check if we are sending a message to 'super'
1340 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001341 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1342 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1343 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1344 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001345 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001346 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001347 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001348 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001349 if (ObjCInterfaceType *IT =
1350 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001351 if (IT->getDecl() ==
1352 CurMethodDecl->getClassInterface()->getSuperClass())
1353 return IT->getDecl();
1354 }
1355 }
1356 }
1357 }
1358 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001359 }
Steve Naroff874e2322007-11-15 10:28:18 +00001360 }
1361 return 0;
1362}
1363
1364// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1365QualType RewriteTest::getSuperStructType() {
1366 if (!SuperStructDecl) {
1367 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1368 &Context->Idents.get("objc_super"), 0);
1369 QualType FieldTypes[2];
1370
1371 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001372 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001373 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001374 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001375 // Create fields
1376 FieldDecl *FieldDecls[2];
1377
1378 for (unsigned i = 0; i < 2; ++i)
1379 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1380
1381 SuperStructDecl->defineBody(FieldDecls, 4);
1382 }
1383 return Context->getTagDeclType(SuperStructDecl);
1384}
1385
Steve Naroff934f2762007-10-24 22:48:43 +00001386Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001387 if (!SelGetUidFunctionDecl)
1388 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001389 if (!MsgSendFunctionDecl)
1390 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001391 if (!MsgSendSuperFunctionDecl)
1392 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001393 if (!MsgSendStretFunctionDecl)
1394 SynthMsgSendStretFunctionDecl();
1395 if (!MsgSendSuperStretFunctionDecl)
1396 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001397 if (!MsgSendFpretFunctionDecl)
1398 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001399 if (!GetClassFunctionDecl)
1400 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001401 if (!GetMetaClassFunctionDecl)
1402 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001403
Steve Naroff874e2322007-11-15 10:28:18 +00001404 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001405 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1406 // May need to use objc_msgSend_stret() as well.
1407 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001408 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001409 QualType resultType = mDecl->getResultType();
1410 if (resultType.getCanonicalType()->isStructureType()
1411 || resultType.getCanonicalType()->isUnionType())
1412 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001413 else if (resultType.getCanonicalType()->isRealFloatingType())
1414 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001415 }
Steve Naroff874e2322007-11-15 10:28:18 +00001416
Steve Naroff934f2762007-10-24 22:48:43 +00001417 // Synthesize a call to objc_msgSend().
1418 llvm::SmallVector<Expr*, 8> MsgExprs;
1419 IdentifierInfo *clsName = Exp->getClassName();
1420
1421 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1422 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001423 if (!strcmp(clsName->getName(), "super")) {
1424 MsgSendFlavor = MsgSendSuperFunctionDecl;
1425 if (MsgSendStretFlavor)
1426 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1427 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1428
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001429 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001430 CurMethodDecl->getClassInterface()->getSuperClass();
1431
1432 llvm::SmallVector<Expr*, 4> InitExprs;
1433
1434 // set the receiver to self, the first argument to all methods.
1435 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001436 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001437 SourceLocation()));
1438 llvm::SmallVector<Expr*, 8> ClsExprs;
1439 QualType argType = Context->getPointerType(Context->CharTy);
1440 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1441 SuperDecl->getIdentifier()->getLength(),
1442 false, argType, SourceLocation(),
1443 SourceLocation()));
1444 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1445 &ClsExprs[0],
1446 ClsExprs.size());
1447 // To turn off a warning, type-cast to 'id'
1448 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001449 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001450 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1451 // struct objc_super
1452 QualType superType = getSuperStructType();
1453 // (struct objc_super) { <exprs from above> }
1454 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1455 &InitExprs[0], InitExprs.size(),
1456 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001457 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1458 superType, ILE);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001459 // struct objc_super *
1460 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1461 Context->getPointerType(SuperRep->getType()),
1462 SourceLocation());
1463 MsgExprs.push_back(Unop);
1464 } else {
1465 llvm::SmallVector<Expr*, 8> ClsExprs;
1466 QualType argType = Context->getPointerType(Context->CharTy);
1467 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1468 clsName->getLength(),
1469 false, argType, SourceLocation(),
1470 SourceLocation()));
1471 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1472 &ClsExprs[0],
1473 ClsExprs.size());
1474 MsgExprs.push_back(Cls);
1475 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001476 } else { // instance message.
1477 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001478
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001479 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001480 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001481 if (MsgSendStretFlavor)
1482 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001483 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1484
1485 llvm::SmallVector<Expr*, 4> InitExprs;
1486
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001487 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001488 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001489 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001490
1491 llvm::SmallVector<Expr*, 8> ClsExprs;
1492 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001493 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1494 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001495 false, argType, SourceLocation(),
1496 SourceLocation()));
1497 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001498 &ClsExprs[0],
1499 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001500 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001501 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001502 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001503 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001504 // struct objc_super
1505 QualType superType = getSuperStructType();
1506 // (struct objc_super) { <exprs from above> }
1507 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1508 &InitExprs[0], InitExprs.size(),
1509 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001510 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1511 superType, ILE);
Steve Naroff874e2322007-11-15 10:28:18 +00001512 // struct objc_super *
1513 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1514 Context->getPointerType(SuperRep->getType()),
1515 SourceLocation());
1516 MsgExprs.push_back(Unop);
1517 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001518 // Remove all type-casts because it may contain objc-style types; e.g.
1519 // Foo<Proto> *.
1520 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1521 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001522 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001523 MsgExprs.push_back(recExpr);
1524 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001525 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001526 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001527 llvm::SmallVector<Expr*, 8> SelExprs;
1528 QualType argType = Context->getPointerType(Context->CharTy);
1529 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1530 Exp->getSelector().getName().size(),
1531 false, argType, SourceLocation(),
1532 SourceLocation()));
1533 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1534 &SelExprs[0], SelExprs.size());
1535 MsgExprs.push_back(SelExp);
1536
1537 // Now push any user supplied arguments.
1538 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001539 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001540 // Make all implicit casts explicit...ICE comes in handy:-)
1541 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1542 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001543 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1544 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001545 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001546 }
1547 // Make id<P...> cast into an 'id' cast.
1548 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001549 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001550 while ((CE = dyn_cast<CastExpr>(userExpr)))
1551 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001552 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001553 userExpr, SourceLocation());
1554 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001555 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001556 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001557 // We've transferred the ownership to MsgExprs. Null out the argument in
1558 // the original expression, since we will delete it below.
1559 Exp->setArg(i, 0);
1560 }
Steve Naroffab972d32007-11-04 22:37:50 +00001561 // Generate the funky cast.
1562 CastExpr *cast;
1563 llvm::SmallVector<QualType, 8> ArgTypes;
1564 QualType returnType;
1565
1566 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001567 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1568 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1569 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001570 ArgTypes.push_back(Context->getObjCIdType());
1571 ArgTypes.push_back(Context->getObjCSelType());
1572 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001573 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001574 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001575 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1576 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001577 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001578 ArgTypes.push_back(t);
1579 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001580 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1581 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001582 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001583 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001584 }
1585 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001586 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001587
1588 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001589 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1590 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001591
1592 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1593 // If we don't do this cast, we get the following bizarre warning/note:
1594 // xx.m:13: warning: function called through a non-compatible type
1595 // xx.m:13: note: if this code is reached, the program will abort
1596 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1597 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001598
Steve Naroffab972d32007-11-04 22:37:50 +00001599 // Now do the "normal" pointer to function cast.
1600 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001601 &ArgTypes[0], ArgTypes.size(),
1602 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001603 castType = Context->getPointerType(castType);
1604 cast = new CastExpr(castType, cast, SourceLocation());
1605
1606 // Don't forget the parens to enforce the proper binding.
1607 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1608
1609 const FunctionType *FT = msgSendType->getAsFunctionType();
1610 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1611 FT->getResultType(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001612 if (MsgSendStretFlavor) {
1613 // We have the method which returns a struct/union. Must also generate
1614 // call to objc_msgSend_stret and hang both varieties on a conditional
1615 // expression which dictate which one to envoke depending on size of
1616 // method's return type.
1617
1618 // Create a reference to the objc_msgSend_stret() declaration.
1619 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1620 SourceLocation());
1621 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1622 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1623 SourceLocation());
1624 // Now do the "normal" pointer to function cast.
1625 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001626 &ArgTypes[0], ArgTypes.size(),
1627 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001628 castType = Context->getPointerType(castType);
1629 cast = new CastExpr(castType, cast, SourceLocation());
1630
1631 // Don't forget the parens to enforce the proper binding.
1632 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1633
1634 FT = msgSendType->getAsFunctionType();
1635 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1636 FT->getResultType(), SourceLocation());
1637
1638 // Build sizeof(returnType)
1639 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1640 returnType, Context->getSizeType(),
1641 SourceLocation(), SourceLocation());
1642 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1643 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1644 // For X86 it is more complicated and some kind of target specific routine
1645 // is needed to decide what to do.
1646 unsigned IntSize = static_cast<unsigned>(
1647 Context->getTypeSize(Context->IntTy, SourceLocation()));
1648
1649 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1650 Context->IntTy,
1651 SourceLocation());
1652 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1653 BinaryOperator::LE,
1654 Context->IntTy,
1655 SourceLocation());
1656 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1657 ConditionalOperator *CondExpr =
1658 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
1659 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
1660 // Now do the actual rewrite.
Steve Naroff5ca40202007-12-19 14:32:56 +00001661 if (Rewrite.ReplaceStmt(Exp, PE)) {
1662 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001663 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1664 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001665 SourceRange Range = Exp->getSourceRange();
1666 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001667 }
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001668 delete Exp;
1669 return PE;
1670 }
Steve Naroff934f2762007-10-24 22:48:43 +00001671 // Now do the actual rewrite.
Steve Naroff5ca40202007-12-19 14:32:56 +00001672 if (Rewrite.ReplaceStmt(Exp, CE)) {
1673 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001674 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1675 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001676 SourceRange Range = Exp->getSourceRange();
1677 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001678 }
Steve Naroff934f2762007-10-24 22:48:43 +00001679
Chris Lattnere64b7772007-10-24 16:57:36 +00001680 delete Exp;
Steve Naroffab972d32007-11-04 22:37:50 +00001681 return CE;
Steve Naroffebf2b562007-10-23 23:50:29 +00001682}
1683
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001684/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1685/// call to objc_getProtocol("proto-name").
1686Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1687 if (!GetProtocolFunctionDecl)
1688 SynthGetProtocolFunctionDecl();
1689 // Create a call to objc_getProtocol("ProtocolName").
1690 llvm::SmallVector<Expr*, 8> ProtoExprs;
1691 QualType argType = Context->getPointerType(Context->CharTy);
1692 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1693 strlen(Exp->getProtocol()->getName()),
1694 false, argType, SourceLocation(),
1695 SourceLocation()));
1696 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1697 &ProtoExprs[0],
1698 ProtoExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001699 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1700 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001701 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1702 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001703 SourceRange Range = Exp->getSourceRange();
1704 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001705 }
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001706 delete Exp;
1707 return ProtoExp;
1708
1709}
1710
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001711/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001712/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001713void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001714 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001715 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
1716 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001717 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001718 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001719 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001720 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001721 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001722 SourceLocation LocStart = CDecl->getLocStart();
1723 SourceLocation LocEnd = CDecl->getLocEnd();
1724
1725 const char *startBuf = SM->getCharacterData(LocStart);
1726 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001727 // If no ivars and no root or if its root, directly or indirectly,
1728 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001729 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001730 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1731 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1732 Result.c_str(), Result.size());
1733 return;
1734 }
1735
1736 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001737 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001738 Result += "\nstruct ";
1739 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001740
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001741 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001742 const char *cursor = strchr(startBuf, '{');
1743 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001744 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001745
1746 // rewrite the original header *without* disturbing the '{'
1747 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1748 Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001749 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00001750 Result = "\n struct ";
1751 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001752 // Note: We don't name the field decl. This simplifies the "codegen" for
1753 // accessing a superclasses instance variables (and is similar to what gcc
1754 // does internally). The unnamed struct field feature is enabled with
1755 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1756 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001757 Result += ";\n";
1758
1759 // insert the super class structure definition.
1760 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1761 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1762 }
1763 cursor++; // past '{'
1764
1765 // Now comment out any visibility specifiers.
1766 while (cursor < endBuf) {
1767 if (*cursor == '@') {
1768 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001769 // Skip whitespace.
1770 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1771 /*scan*/;
1772
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001773 // FIXME: presence of @public, etc. inside comment results in
1774 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001775 if (!strncmp(cursor, "public", strlen("public")) ||
1776 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001777 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001778 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001779 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001780 // FIXME: If there are cases where '<' is used in ivar declaration part
1781 // of user code, then scan the ivar list and use needToScanForQualifiers
1782 // for type checking.
1783 else if (*cursor == '<') {
1784 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1785 Rewrite.InsertText(atLoc, "/* ", 3);
1786 cursor = strchr(cursor, '>');
1787 cursor++;
1788 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1789 Rewrite.InsertText(atLoc, " */", 3);
1790 }
Steve Narofffea763e82007-11-14 19:25:57 +00001791 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001792 }
Steve Narofffea763e82007-11-14 19:25:57 +00001793 // Don't forget to add a ';'!!
1794 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1795 } else { // we don't have any instance variables - insert super struct.
1796 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1797 Result += " {\n struct ";
1798 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001799 // Note: We don't name the field decl. This simplifies the "codegen" for
1800 // accessing a superclasses instance variables (and is similar to what gcc
1801 // does internally). The unnamed struct field feature is enabled with
1802 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1803 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001804 Result += ";\n};\n";
1805 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1806 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001807 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001808 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001809 if (!ObjCSynthesizedStructs.insert(CDecl))
1810 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001811}
1812
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001813// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001814/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001815void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001816 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001817 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001818 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001819 const char *ClassName,
1820 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001821 if (MethodBegin == MethodEnd) return;
1822
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001823 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001824 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001825 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001826 SEL _cmd;
1827 char *method_types;
1828 void *_imp;
1829 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001830 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001831 Result += "\nstruct _objc_method {\n";
1832 Result += "\tSEL _cmd;\n";
1833 Result += "\tchar *method_types;\n";
1834 Result += "\tvoid *_imp;\n";
1835 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001836
1837 /* struct _objc_method_list {
1838 struct _objc_method_list *next_method;
1839 int method_count;
1840 struct _objc_method method_list[];
1841 }
1842 */
1843 Result += "\nstruct _objc_method_list {\n";
1844 Result += "\tstruct _objc_method_list *next_method;\n";
1845 Result += "\tint method_count;\n";
1846 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001847 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00001848 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001849
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001850 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001851 Result += "\nstatic struct _objc_method_list _OBJC_";
1852 Result += prefix;
1853 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
1854 Result += "_METHODS_";
1855 Result += ClassName;
1856 Result += " __attribute__ ((section (\"__OBJC, __";
1857 Result += IsInstanceMethod ? "inst" : "cls";
1858 Result += "_meth\")))= ";
1859 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001860
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001861 Result += "\t,{{(SEL)\"";
1862 Result += (*MethodBegin)->getSelector().getName().c_str();
1863 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001864 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001865 Result += "\", \"";
1866 Result += MethodTypeString;
1867 Result += "\", ";
1868 Result += MethodInternalNames[*MethodBegin];
1869 Result += "}\n";
1870 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
1871 Result += "\t ,{(SEL)\"";
1872 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001873 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001874 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001875 Result += "\", \"";
1876 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001877 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001878 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001879 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001880 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001881 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001882}
1883
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001884/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
1885void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001886 int NumProtocols,
1887 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001888 const char *ClassName,
1889 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001890 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001891 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001892 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001893 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001894 // Output struct protocol_methods holder of method selector and type.
1895 if (!objc_protocol_methods &&
1896 (PDecl->getNumInstanceMethods() > 0
1897 || PDecl->getNumClassMethods() > 0)) {
1898 /* struct protocol_methods {
1899 SEL _cmd;
1900 char *method_types;
1901 }
1902 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001903 Result += "\nstruct protocol_methods {\n";
1904 Result += "\tSEL _cmd;\n";
1905 Result += "\tchar *method_types;\n";
1906 Result += "};\n";
1907
1908 /* struct _objc_protocol_method_list {
1909 int protocol_method_count;
1910 struct protocol_methods protocols[];
1911 }
1912 */
1913 Result += "\nstruct _objc_protocol_method_list {\n";
1914 Result += "\tint protocol_method_count;\n";
1915 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001916 objc_protocol_methods = true;
1917 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001918
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00001919 int NumMethods = PDecl->getNumInstanceMethods();
1920 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001921 Result += "\nstatic struct _objc_protocol_method_list "
1922 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
1923 Result += PDecl->getName();
1924 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
1925 "{\n\t" + utostr(NumMethods) + "\n";
1926
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00001927 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001928 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00001929 E = PDecl->instmeth_end(); I != E; ++I) {
1930 if (I == PDecl->instmeth_begin())
1931 Result += "\t ,{{(SEL)\"";
1932 else
1933 Result += "\t ,{(SEL)\"";
1934 Result += (*I)->getSelector().getName().c_str();
1935 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001936 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00001937 Result += "\", \"";
1938 Result += MethodTypeString;
1939 Result += "\"}\n";
1940 }
1941 Result += "\t }\n};\n";
1942 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001943
1944 // Output class methods declared in this protocol.
1945 NumMethods = PDecl->getNumClassMethods();
1946 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001947 Result += "\nstatic struct _objc_protocol_method_list "
1948 "_OBJC_PROTOCOL_CLASS_METHODS_";
1949 Result += PDecl->getName();
1950 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
1951 "{\n\t";
1952 Result += utostr(NumMethods);
1953 Result += "\n";
1954
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00001955 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001956 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00001957 E = PDecl->classmeth_end(); I != E; ++I) {
1958 if (I == PDecl->classmeth_begin())
1959 Result += "\t ,{{(SEL)\"";
1960 else
1961 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001962 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001963 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001964 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00001965 Result += "\", \"";
1966 Result += MethodTypeString;
1967 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001968 }
1969 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001970 }
1971 // Output:
1972 /* struct _objc_protocol {
1973 // Objective-C 1.0 extensions
1974 struct _objc_protocol_extension *isa;
1975 char *protocol_name;
1976 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001977 struct _objc_protocol_method_list *instance_methods;
1978 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001979 };
1980 */
1981 static bool objc_protocol = false;
1982 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00001983 Result += "\nstruct _objc_protocol {\n";
1984 Result += "\tstruct _objc_protocol_extension *isa;\n";
1985 Result += "\tchar *protocol_name;\n";
1986 Result += "\tstruct _objc_protocol **protocol_list;\n";
1987 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
1988 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
1989 Result += "};\n";
1990
1991 /* struct _objc_protocol_list {
1992 struct _objc_protocol_list *next;
1993 int protocol_count;
1994 struct _objc_protocol *class_protocols[];
1995 }
1996 */
1997 Result += "\nstruct _objc_protocol_list {\n";
1998 Result += "\tstruct _objc_protocol_list *next;\n";
1999 Result += "\tint protocol_count;\n";
2000 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2001 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002002 objc_protocol = true;
2003 }
2004
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002005 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2006 Result += PDecl->getName();
2007 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2008 "{\n\t0, \"";
2009 Result += PDecl->getName();
2010 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002011 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002012 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2013 Result += PDecl->getName();
2014 Result += ", ";
2015 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002016 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002017 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002018 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002019 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2020 Result += PDecl->getName();
2021 Result += "\n";
2022 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002023 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002024 Result += "0\n";
2025 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002026 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002027 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002028 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2029 Result += prefix;
2030 Result += "_PROTOCOLS_";
2031 Result += ClassName;
2032 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2033 "{\n\t0, ";
2034 Result += utostr(NumProtocols);
2035 Result += "\n";
2036
2037 Result += "\t,{&_OBJC_PROTOCOL_";
2038 Result += Protocols[0]->getName();
2039 Result += " \n";
2040
2041 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002042 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002043 Result += "\t ,&_OBJC_PROTOCOL_";
2044 Result += PDecl->getName();
2045 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002046 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002047 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002048 }
2049}
2050
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002051/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002052/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002053void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002054 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002055 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002056 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002057 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002058 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2059 CDecl = CDecl->getNextClassCategory())
2060 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2061 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002062
Chris Lattnereb44eee2007-12-23 01:40:15 +00002063 std::string FullCategoryName = ClassDecl->getName();
2064 FullCategoryName += '_';
2065 FullCategoryName += IDecl->getName();
2066
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002067 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002068 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002069 true, "CATEGORY_", FullCategoryName.c_str(),
2070 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002071
2072 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002073 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002074 false, "CATEGORY_", FullCategoryName.c_str(),
2075 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002076
2077 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002078 // Null CDecl is case of a category implementation with no category interface
2079 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002080 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002081 CDecl->getNumReferencedProtocols(),
2082 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002083 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002084
2085 /* struct _objc_category {
2086 char *category_name;
2087 char *class_name;
2088 struct _objc_method_list *instance_methods;
2089 struct _objc_method_list *class_methods;
2090 struct _objc_protocol_list *protocols;
2091 // Objective-C 1.0 extensions
2092 uint32_t size; // sizeof (struct _objc_category)
2093 struct _objc_property_list *instance_properties; // category's own
2094 // @property decl.
2095 };
2096 */
2097
2098 static bool objc_category = false;
2099 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002100 Result += "\nstruct _objc_category {\n";
2101 Result += "\tchar *category_name;\n";
2102 Result += "\tchar *class_name;\n";
2103 Result += "\tstruct _objc_method_list *instance_methods;\n";
2104 Result += "\tstruct _objc_method_list *class_methods;\n";
2105 Result += "\tstruct _objc_protocol_list *protocols;\n";
2106 Result += "\tunsigned int size;\n";
2107 Result += "\tstruct _objc_property_list *instance_properties;\n";
2108 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002109 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002110 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002111 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2112 Result += FullCategoryName;
2113 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2114 Result += IDecl->getName();
2115 Result += "\"\n\t, \"";
2116 Result += ClassDecl->getName();
2117 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002118
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002119 if (IDecl->getNumInstanceMethods() > 0) {
2120 Result += "\t, (struct _objc_method_list *)"
2121 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2122 Result += FullCategoryName;
2123 Result += "\n";
2124 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002125 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002126 Result += "\t, 0\n";
2127 if (IDecl->getNumClassMethods() > 0) {
2128 Result += "\t, (struct _objc_method_list *)"
2129 "&_OBJC_CATEGORY_CLASS_METHODS_";
2130 Result += FullCategoryName;
2131 Result += "\n";
2132 }
2133 else
2134 Result += "\t, 0\n";
2135
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002136 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002137 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2138 Result += FullCategoryName;
2139 Result += "\n";
2140 }
2141 else
2142 Result += "\t, 0\n";
2143 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002144}
2145
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002146/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2147/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002148void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2149 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002150 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002151 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002152 Result += IDecl->getName();
2153 Result += ", ";
2154 Result += ivar->getName();
2155 Result += ")";
2156}
2157
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002158//===----------------------------------------------------------------------===//
2159// Meta Data Emission
2160//===----------------------------------------------------------------------===//
2161
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002162void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002163 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002164 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002165
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002166 // Explictly declared @interface's are already synthesized.
2167 if (CDecl->ImplicitInterfaceDecl()) {
2168 // FIXME: Implementation of a class with no @interface (legacy) doese not
2169 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002170 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002171 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002172
Chris Lattnerbe6df082007-12-12 07:56:42 +00002173 // Build _objc_ivar_list metadata for classes ivars if needed
2174 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2175 ? IDecl->getImplDeclNumIvars()
2176 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002177 if (NumIvars > 0) {
2178 static bool objc_ivar = false;
2179 if (!objc_ivar) {
2180 /* struct _objc_ivar {
2181 char *ivar_name;
2182 char *ivar_type;
2183 int ivar_offset;
2184 };
2185 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002186 Result += "\nstruct _objc_ivar {\n";
2187 Result += "\tchar *ivar_name;\n";
2188 Result += "\tchar *ivar_type;\n";
2189 Result += "\tint ivar_offset;\n";
2190 Result += "};\n";
2191
2192 /* struct _objc_ivar_list {
2193 int ivar_count;
2194 struct _objc_ivar ivar_list[];
2195 };
2196 */
2197 Result += "\nstruct _objc_ivar_list {\n";
2198 Result += "\tint ivar_count;\n";
2199 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002200 objc_ivar = true;
2201 }
2202
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002203 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2204 Result += IDecl->getName();
2205 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2206 "{\n\t";
2207 Result += utostr(NumIvars);
2208 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002209
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002210 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002211 if (IDecl->getImplDeclNumIvars() > 0) {
2212 IVI = IDecl->ivar_begin();
2213 IVE = IDecl->ivar_end();
2214 } else {
2215 IVI = CDecl->ivar_begin();
2216 IVE = CDecl->ivar_end();
2217 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002218 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002219 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002220 Result += "\", \"";
2221 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002222 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002223 Result += StrEncoding;
2224 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002225 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002226 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002227 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002228 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002229 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002230 Result += "\", \"";
2231 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002232 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002233 Result += StrEncoding;
2234 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002235 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002236 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002237 }
2238
2239 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002240 }
2241
2242 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002243 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002244 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002245
2246 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002247 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002248 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002249
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002250 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002251 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002252 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002253 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002254
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002255
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002256 // Declaration of class/meta-class metadata
2257 /* struct _objc_class {
2258 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002259 const char *super_class_name;
2260 char *name;
2261 long version;
2262 long info;
2263 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002264 struct _objc_ivar_list *ivars;
2265 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002266 struct objc_cache *cache;
2267 struct objc_protocol_list *protocols;
2268 const char *ivar_layout;
2269 struct _objc_class_ext *ext;
2270 };
2271 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002272 static bool objc_class = false;
2273 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002274 Result += "\nstruct _objc_class {\n";
2275 Result += "\tstruct _objc_class *isa;\n";
2276 Result += "\tconst char *super_class_name;\n";
2277 Result += "\tchar *name;\n";
2278 Result += "\tlong version;\n";
2279 Result += "\tlong info;\n";
2280 Result += "\tlong instance_size;\n";
2281 Result += "\tstruct _objc_ivar_list *ivars;\n";
2282 Result += "\tstruct _objc_method_list *methods;\n";
2283 Result += "\tstruct objc_cache *cache;\n";
2284 Result += "\tstruct _objc_protocol_list *protocols;\n";
2285 Result += "\tconst char *ivar_layout;\n";
2286 Result += "\tstruct _objc_class_ext *ext;\n";
2287 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002288 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002289 }
2290
2291 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002292 ObjCInterfaceDecl *RootClass = 0;
2293 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002294 while (SuperClass) {
2295 RootClass = SuperClass;
2296 SuperClass = SuperClass->getSuperClass();
2297 }
2298 SuperClass = CDecl->getSuperClass();
2299
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002300 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2301 Result += CDecl->getName();
2302 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2303 "{\n\t(struct _objc_class *)\"";
2304 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2305 Result += "\"";
2306
2307 if (SuperClass) {
2308 Result += ", \"";
2309 Result += SuperClass->getName();
2310 Result += "\", \"";
2311 Result += CDecl->getName();
2312 Result += "\"";
2313 }
2314 else {
2315 Result += ", 0, \"";
2316 Result += CDecl->getName();
2317 Result += "\"";
2318 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002319 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002320 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002321 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002322 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002323 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002324 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002325 Result += "\n";
2326 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002327 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002328 Result += ", 0\n";
2329 if (CDecl->getNumIntfRefProtocols() > 0) {
2330 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2331 Result += CDecl->getName();
2332 Result += ",0,0\n";
2333 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002334 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002335 Result += "\t,0,0,0,0\n";
2336 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002337
2338 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002339 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2340 Result += CDecl->getName();
2341 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2342 "{\n\t&_OBJC_METACLASS_";
2343 Result += CDecl->getName();
2344 if (SuperClass) {
2345 Result += ", \"";
2346 Result += SuperClass->getName();
2347 Result += "\", \"";
2348 Result += CDecl->getName();
2349 Result += "\"";
2350 }
2351 else {
2352 Result += ", 0, \"";
2353 Result += CDecl->getName();
2354 Result += "\"";
2355 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002356 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002357 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002358 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002359 Result += ",0";
2360 else {
2361 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002362 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002363 Result += CDecl->getName();
2364 Result += ")";
2365 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002366 if (NumIvars > 0) {
2367 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2368 Result += CDecl->getName();
2369 Result += "\n\t";
2370 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002371 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002372 Result += ",0";
2373 if (IDecl->getNumInstanceMethods() > 0) {
2374 Result += ", &_OBJC_INSTANCE_METHODS_";
2375 Result += CDecl->getName();
2376 Result += ", 0\n\t";
2377 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002378 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002379 Result += ",0,0";
2380 if (CDecl->getNumIntfRefProtocols() > 0) {
2381 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2382 Result += CDecl->getName();
2383 Result += ", 0,0\n";
2384 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002385 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002386 Result += ",0,0,0\n";
2387 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002388}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002389
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002390/// RewriteImplementations - This routine rewrites all method implementations
2391/// and emits meta-data.
2392
2393void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002394 int ClsDefCount = ClassImplementation.size();
2395 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002396
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002397 if (ClsDefCount == 0 && CatDefCount == 0)
2398 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002399 // Rewrite implemented methods
2400 for (int i = 0; i < ClsDefCount; i++)
2401 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002402
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002403 for (int i = 0; i < CatDefCount; i++)
2404 RewriteImplementationDecl(CategoryImplementation[i]);
2405
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002406 // This is needed for use of offsetof
2407 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002408
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002409 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002410 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002412
2413 // For each implemented category, write out all its meta data.
2414 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002415 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002416
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002417 // Write objc_symtab metadata
2418 /*
2419 struct _objc_symtab
2420 {
2421 long sel_ref_cnt;
2422 SEL *refs;
2423 short cls_def_cnt;
2424 short cat_def_cnt;
2425 void *defs[cls_def_cnt + cat_def_cnt];
2426 };
2427 */
2428
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002429 Result += "\nstruct _objc_symtab {\n";
2430 Result += "\tlong sel_ref_cnt;\n";
2431 Result += "\tSEL *refs;\n";
2432 Result += "\tshort cls_def_cnt;\n";
2433 Result += "\tshort cat_def_cnt;\n";
2434 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2435 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002436
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002437 Result += "static struct _objc_symtab "
2438 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2439 Result += "\t0, 0, " + utostr(ClsDefCount)
2440 + ", " + utostr(CatDefCount) + "\n";
2441 for (int i = 0; i < ClsDefCount; i++) {
2442 Result += "\t,&_OBJC_CLASS_";
2443 Result += ClassImplementation[i]->getName();
2444 Result += "\n";
2445 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002446
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002447 for (int i = 0; i < CatDefCount; i++) {
2448 Result += "\t,&_OBJC_CATEGORY_";
2449 Result += CategoryImplementation[i]->getClassInterface()->getName();
2450 Result += "_";
2451 Result += CategoryImplementation[i]->getName();
2452 Result += "\n";
2453 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002454
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002455 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002456
2457 // Write objc_module metadata
2458
2459 /*
2460 struct _objc_module {
2461 long version;
2462 long size;
2463 const char *name;
2464 struct _objc_symtab *symtab;
2465 }
2466 */
2467
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002468 Result += "\nstruct _objc_module {\n";
2469 Result += "\tlong version;\n";
2470 Result += "\tlong size;\n";
2471 Result += "\tconst char *name;\n";
2472 Result += "\tstruct _objc_symtab *symtab;\n";
2473 Result += "};\n\n";
2474 Result += "static struct _objc_module "
2475 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002476 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2477 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002478 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002479
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002480}
Chris Lattner311ff022007-10-16 22:36:42 +00002481