blob: ee7f72347c7c9f622177f9bdd1a1a7a152e7fde9 [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 Jahanian33b9c4e2008-01-08 22:06:28 +0000124 "#include <objc/objc.h>\n"
125 "struct __objcFastEnumerationState {\n\t"
126 "unsigned long state;\n\t"
127 "id *itemsPtr;\n\t"
128 "unsigned long *mutationsPtr;\n\t"
129 "unsigned long extra[5];\n};\n";
130
Ted Kremenek95041a22007-12-19 22:51:13 +0000131 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
Steve Naroffab972d32007-11-04 22:37:50 +0000132 s, strlen(s));
Chris Lattner77cd2a02007-10-11 00:43:27 +0000133 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000134
Chris Lattnerf04da132007-10-24 17:06:59 +0000135 // Top Level Driver code.
136 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000137 void HandleDeclInMainFile(Decl *D);
Chris Lattnere365c502007-11-30 22:25:36 +0000138 RewriteTest(Diagnostic &D) : Diags(D) {}
Chris Lattnerf04da132007-10-24 17:06:59 +0000139 ~RewriteTest();
140
141 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000142 void RewritePrologue(SourceLocation Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000143 void RewriteInclude(SourceLocation Loc);
Chris Lattnerf04da132007-10-24 17:06:59 +0000144 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000145 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
146 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000147 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000148 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
149 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
150 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
151 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
152 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
153 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000154 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000155 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000156 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000157 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000158 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000159
Chris Lattnerf04da132007-10-24 17:06:59 +0000160 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000161 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000162 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000163 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000164 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000165 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000166 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000167 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000168 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
169 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
170 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
171 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000172 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff934f2762007-10-24 22:48:43 +0000173 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
174 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000175 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
176 void SynthCountByEnumWithState(std::string &buf);
177
Steve Naroff09b266e2007-10-30 23:14:51 +0000178 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000179 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000180 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000181 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000182 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000183 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000184 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000185 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000186 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000187 void SynthGetProtocolFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000188
Chris Lattnerf04da132007-10-24 17:06:59 +0000189 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000190 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000191 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000192
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000193 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000194 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000195
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000196 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
197 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000198 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000199 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000200 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000201 const char *ClassName,
202 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000203
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000204 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000205 int NumProtocols,
206 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000207 const char *ClassName,
208 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000209 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000210 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000211 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
212 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000213 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000214 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000215 };
216}
217
Chris Lattnere365c502007-11-30 22:25:36 +0000218ASTConsumer *clang::CreateCodeRewriterTest(Diagnostic &Diags) {
219 return new RewriteTest(Diags);
220}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000221
Chris Lattnerf04da132007-10-24 17:06:59 +0000222//===----------------------------------------------------------------------===//
223// Top Level Driver Code
224//===----------------------------------------------------------------------===//
225
Chris Lattner8a12c272007-10-11 18:38:32 +0000226void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000227 // Two cases: either the decl could be in the main file, or it could be in a
228 // #included file. If the former, rewrite it now. If the later, check to see
229 // if we rewrote the #include/#import.
230 SourceLocation Loc = D->getLocation();
231 Loc = SM->getLogicalLoc(Loc);
232
233 // If this is for a builtin, ignore it.
234 if (Loc.isInvalid()) return;
235
Steve Naroffebf2b562007-10-23 23:50:29 +0000236 // Look for built-in declarations that we need to refer during the rewrite.
237 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000238 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000239 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
240 // declared in <Foundation/NSString.h>
241 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
242 ConstantStringClassReference = FVD;
243 return;
244 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000245 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000246 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000247 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000248 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000249 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000250 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000251 } else if (ObjCForwardProtocolDecl *FP =
252 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000253 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000254 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000255 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000256 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
257 return HandleDeclInMainFile(D);
258
Chris Lattnerf04da132007-10-24 17:06:59 +0000259 // Otherwise, see if there is a #import in the main file that should be
260 // rewritten.
Steve Naroff32174822007-11-09 12:50:28 +0000261 //RewriteInclude(Loc);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000262}
263
Chris Lattnerf04da132007-10-24 17:06:59 +0000264/// HandleDeclInMainFile - This is called for each top-level decl defined in the
265/// main file of the input.
266void RewriteTest::HandleDeclInMainFile(Decl *D) {
267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
268 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000269 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff71c0a952007-11-13 23:01:27 +0000270
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000271 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000272 if (Stmt *Body = MD->getBody()) {
273 //Body->dump();
274 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000275 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000276 CurMethodDecl = 0;
277 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000278 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000279 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000280 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000281 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000282 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000284 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000285 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000287 if (VD->getInit())
288 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
289 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000290 // Nothing yet.
291}
292
293RewriteTest::~RewriteTest() {
294 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000295
296 // Rewrite tabs if we care.
297 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000298
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000299 // Rewrite Objective-c meta data*
300 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000301 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000302
Chris Lattnerf04da132007-10-24 17:06:59 +0000303 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
304 // we are done.
305 if (const RewriteBuffer *RewriteBuf =
306 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000307 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000308 std::string S(RewriteBuf->begin(), RewriteBuf->end());
309 printf("%s\n", S.c_str());
310 } else {
311 printf("No changes\n");
312 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000313 // Emit metadata.
314 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000315}
316
Chris Lattnerf04da132007-10-24 17:06:59 +0000317//===----------------------------------------------------------------------===//
318// Syntactic (non-AST) Rewriting Code
319//===----------------------------------------------------------------------===//
320
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000321void RewriteTest::RewriteInclude(SourceLocation Loc) {
322 // Rip up the #include stack to the main file.
323 SourceLocation IncLoc = Loc, NextLoc = Loc;
324 do {
325 IncLoc = Loc;
326 Loc = SM->getLogicalLoc(NextLoc);
327 NextLoc = SM->getIncludeLoc(Loc);
328 } while (!NextLoc.isInvalid());
329
330 // Loc is now the location of the #include filename "foo" or <foo/bar.h>.
331 // IncLoc indicates the header that was included if it is useful.
332 IncLoc = SM->getLogicalLoc(IncLoc);
333 if (SM->getDecomposedFileLoc(Loc).first != MainFileID ||
334 Loc == LastIncLoc)
335 return;
336 LastIncLoc = Loc;
337
338 unsigned IncCol = SM->getColumnNumber(Loc);
339 SourceLocation LineStartLoc = Loc.getFileLocWithOffset(-IncCol+1);
340
341 // Replace the #import with #include.
342 Rewrite.ReplaceText(LineStartLoc, IncCol-1, "#include ", strlen("#include "));
343}
344
Chris Lattnerf04da132007-10-24 17:06:59 +0000345void RewriteTest::RewriteTabs() {
346 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
347 const char *MainBufStart = MainBuf.first;
348 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000349
Chris Lattnerf04da132007-10-24 17:06:59 +0000350 // Loop over the whole file, looking for tabs.
351 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
352 if (*BufPtr != '\t')
353 continue;
354
355 // Okay, we found a tab. This tab will turn into at least one character,
356 // but it depends on which 'virtual column' it is in. Compute that now.
357 unsigned VCol = 0;
358 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
359 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
360 ++VCol;
361
362 // Okay, now that we know the virtual column, we know how many spaces to
363 // insert. We assume 8-character tab-stops.
364 unsigned Spaces = 8-(VCol & 7);
365
366 // Get the location of the tab.
367 SourceLocation TabLoc =
368 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
369
370 // Rewrite the single tab character into a sequence of spaces.
371 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
372 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000373}
374
375
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000376void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000377 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000378 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000379
380 // Get the start location and compute the semi location.
381 SourceLocation startLoc = ClassDecl->getLocation();
382 const char *startBuf = SM->getCharacterData(startLoc);
383 const char *semiPtr = strchr(startBuf, ';');
384
385 // Translate to typedef's that forward reference structs with the same name
386 // as the class. As a convenience, we include the original declaration
387 // as a comment.
388 std::string typedefString;
389 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000390 typedefString.append(startBuf, semiPtr-startBuf+1);
391 typedefString += "\n";
392 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000393 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000394 typedefString += "#ifndef _REWRITER_typedef_";
395 typedefString += ForwardDecl->getName();
396 typedefString += "\n";
397 typedefString += "#define _REWRITER_typedef_";
398 typedefString += ForwardDecl->getName();
399 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000400 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000401 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000402 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000403 }
404
405 // Replace the @class with typedefs corresponding to the classes.
406 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
407 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000408}
409
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000410void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000411 SourceLocation LocStart = Method->getLocStart();
412 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000413
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000414 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
415 Rewrite.InsertText(LocStart, "/* ", 3);
416 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
417 } else {
418 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000419 }
420}
421
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000422void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000423{
424 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000425 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000426 SourceLocation Loc = Property->getLocation();
427
428 Rewrite.ReplaceText(Loc, 0, "// ", 3);
429
430 // FIXME: handle properties that are declared across multiple lines.
431 }
432}
433
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000434void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000435 SourceLocation LocStart = CatDecl->getLocStart();
436
437 // FIXME: handle category headers that are declared across multiple lines.
438 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
439
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000440 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000441 E = CatDecl->instmeth_end(); I != E; ++I)
442 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000443 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000444 E = CatDecl->classmeth_end(); I != E; ++I)
445 RewriteMethodDeclaration(*I);
446
Steve Naroff423cb562007-10-30 13:30:57 +0000447 // Lastly, comment out the @end.
448 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
449}
450
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000451void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000452 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000453
Steve Naroff752d6ef2007-10-30 16:42:30 +0000454 SourceLocation LocStart = PDecl->getLocStart();
455
456 // FIXME: handle protocol headers that are declared across multiple lines.
457 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
458
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000459 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000460 E = PDecl->instmeth_end(); I != E; ++I)
461 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000462 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000463 E = PDecl->classmeth_end(); I != E; ++I)
464 RewriteMethodDeclaration(*I);
465
Steve Naroff752d6ef2007-10-30 16:42:30 +0000466 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000467 SourceLocation LocEnd = PDecl->getAtEndLoc();
468 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000469
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000470 // Must comment out @optional/@required
471 const char *startBuf = SM->getCharacterData(LocStart);
472 const char *endBuf = SM->getCharacterData(LocEnd);
473 for (const char *p = startBuf; p < endBuf; p++) {
474 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
475 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000476 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000477 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
478 CommentedOptional.c_str(), CommentedOptional.size());
479
480 }
481 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
482 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000483 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000484 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
485 CommentedRequired.c_str(), CommentedRequired.size());
486
487 }
488 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000489}
490
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000491void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000492 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000493 if (LocStart.isInvalid())
494 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000495 // FIXME: handle forward protocol that are declared across multiple lines.
496 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
497}
498
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000499void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000500 std::string &ResultStr) {
501 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000502 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000503 ResultStr += "id";
504 else
505 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000506 ResultStr += "\n";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000507
508 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000509 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000510
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000511 if (OMD->isInstance())
512 NameStr += "_I_";
513 else
514 NameStr += "_C_";
515
516 NameStr += OMD->getClassInterface()->getName();
517 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000518
519 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000520 if (ObjCCategoryImplDecl *CID =
521 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000522 NameStr += CID->getName();
523 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000524 }
525 // Append selector names, replacing ':' with '_'
526 const char *selName = OMD->getSelector().getName().c_str();
527 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000528 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000529 else {
530 std::string selString = OMD->getSelector().getName();
531 int len = selString.size();
532 for (int i = 0; i < len; i++)
533 if (selString[i] == ':')
534 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000535 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000536 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000537 // Remember this name for metadata emission
538 MethodInternalNames[OMD] = NameStr;
539 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000540
541 // Rewrite arguments
542 ResultStr += "(";
543
544 // invisible arguments
545 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000546 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000547 selfTy = Context->getPointerType(selfTy);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000548 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000549 ResultStr += "struct ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000550 ResultStr += selfTy.getAsString();
551 }
552 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000553 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000554
555 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000556 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000557 ResultStr += " _cmd";
558
559 // Method arguments.
560 for (int i = 0; i < OMD->getNumParams(); i++) {
561 ParmVarDecl *PDecl = OMD->getParamDecl(i);
562 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000563 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000564 ResultStr += "id";
565 else
566 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000567 ResultStr += " ";
568 ResultStr += PDecl->getName();
569 }
570 ResultStr += ")";
571
572}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000573void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000574 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
575 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000576
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000577 if (IMD)
578 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
579 else
580 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000581
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000582 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000583 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
584 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000585 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000586 ObjCMethodDecl *OMD = *I;
587 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000588 SourceLocation LocStart = OMD->getLocStart();
589 SourceLocation LocEnd = OMD->getBody()->getLocStart();
590
591 const char *startBuf = SM->getCharacterData(LocStart);
592 const char *endBuf = SM->getCharacterData(LocEnd);
593 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
594 ResultStr.c_str(), ResultStr.size());
595 }
596
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000597 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000598 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
599 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000600 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000601 ObjCMethodDecl *OMD = *I;
602 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000603 SourceLocation LocStart = OMD->getLocStart();
604 SourceLocation LocEnd = OMD->getBody()->getLocStart();
605
606 const char *startBuf = SM->getCharacterData(LocStart);
607 const char *endBuf = SM->getCharacterData(LocEnd);
608 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
609 ResultStr.c_str(), ResultStr.size());
610 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000611 if (IMD)
612 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
613 else
614 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000615}
616
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000617void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000618 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000619 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000620 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000621 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000622 ResultStr += ClassDecl->getName();
623 ResultStr += "\n";
624 ResultStr += "#define _REWRITER_typedef_";
625 ResultStr += ClassDecl->getName();
626 ResultStr += "\n";
Fariborz Jahanian87ce5d12007-12-03 22:25:42 +0000627 ResultStr += "typedef struct ";
628 ResultStr += ClassDecl->getName();
629 ResultStr += " ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000630 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000631 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000632
633 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000634 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000635 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000636 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000637
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000638 RewriteProperties(ClassDecl->getNumPropertyDecl(),
639 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000640 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000641 E = ClassDecl->instmeth_end(); I != E; ++I)
642 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000643 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000644 E = ClassDecl->classmeth_end(); I != E; ++I)
645 RewriteMethodDeclaration(*I);
646
Steve Naroff2feac5e2007-10-30 03:43:13 +0000647 // Lastly, comment out the @end.
648 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000649}
650
Steve Naroff7e3411b2007-11-15 02:58:25 +0000651Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000652 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff7e3411b2007-11-15 02:58:25 +0000653 if (IV->isFreeIvar()) {
654 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
655 IV->getLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +0000656 if (Rewrite.ReplaceStmt(IV, Replacement)) {
657 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000658 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
659 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000660 SourceRange Range = IV->getSourceRange();
661 Diags.Report(Context->getFullLoc(IV->getLocation()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000662 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000663 delete IV;
664 return Replacement;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000665 } else {
666 if (CurMethodDecl) {
667 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000668 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffc2a689b2007-11-15 11:33:00 +0000669 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
670 IdentifierInfo *II = intT->getDecl()->getIdentifier();
671 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
672 II, 0);
673 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
674
675 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
676 // Don't forget the parens to enforce the proper binding.
677 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroff5ca40202007-12-19 14:32:56 +0000678 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
679 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +0000680 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
681 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +0000682 SourceRange Range = IV->getBase()->getSourceRange();
683 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +0000684 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000685 delete IV->getBase();
686 return PE;
687 }
688 }
689 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000690 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +0000691 }
Steve Naroff7e3411b2007-11-15 02:58:25 +0000692}
693
Chris Lattnerf04da132007-10-24 17:06:59 +0000694//===----------------------------------------------------------------------===//
695// Function Body / Expression rewriting
696//===----------------------------------------------------------------------===//
697
Steve Narofff3473a72007-11-09 15:20:18 +0000698Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Chris Lattner311ff022007-10-16 22:36:42 +0000699 // Otherwise, just rewrite all children.
700 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
701 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000702 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000703 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000704 if (newStmt)
705 *CI = newStmt;
706 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000707
708 // Handle specific things.
709 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
710 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000711
712 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
713 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000714
715 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
716 return RewriteAtSelector(AtSelector);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000717
718 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
719 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000720
Steve Naroff934f2762007-10-24 22:48:43 +0000721 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
722 // Before we rewrite it, put the original message expression in a comment.
723 SourceLocation startLoc = MessExpr->getLocStart();
724 SourceLocation endLoc = MessExpr->getLocEnd();
725
726 const char *startBuf = SM->getCharacterData(startLoc);
727 const char *endBuf = SM->getCharacterData(endLoc);
728
729 std::string messString;
730 messString += "// ";
731 messString.append(startBuf, endBuf-startBuf+1);
732 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000733
Steve Naroff934f2762007-10-24 22:48:43 +0000734 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
735 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
736 // Tried this, but it didn't work either...
Steve Naroff752d6ef2007-10-30 16:42:30 +0000737 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000738 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000739 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000740
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000741 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
742 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000743
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000744 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
745 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000746
747 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
748 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000749
750 if (ObjCForCollectionStmt *StmtForCollection =
751 dyn_cast<ObjCForCollectionStmt>(S))
752 return RewriteObjCForCollectionStmt(StmtForCollection);
753
Steve Naroff874e2322007-11-15 10:28:18 +0000754#if 0
755 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
756 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
757 // Get the new text.
758 std::ostringstream Buf;
759 Replacement->printPretty(Buf);
760 const std::string &Str = Buf.str();
761
762 printf("CAST = %s\n", &Str[0]);
763 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
764 delete S;
765 return Replacement;
766 }
767#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000768 // Return this stmt unmodified.
769 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000770}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000771
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000772/// SynthCountByEnumWithState - To print:
773/// ((unsigned int (*)
774/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
775/// (void *)objc_msgSend)((id)l_collection,
776/// sel_registerName(
777/// "countByEnumeratingWithState:objects:count:"),
778/// &enumState,
779/// (id *)items, (unsigned int)16)
780///
781void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
782 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
783 "id *, unsigned int))(void *)objc_msgSend)";
784 buf += "\n\t\t";
785 buf += "((id)l_collection,\n\t\t";
786 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
787 buf += "\n\t\t";
788 buf += "&enumState, "
789 "(id *)items, (unsigned int)16)";
790}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000791
792/// RewriteObjCTryStmt - Rewriter for ObjC2's feareach statement.
793/// It rewrites:
794/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000795
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000796/// Into:
797/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000798/// type elem;
799/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000800/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000801/// id l_collection = (id)collection;
802/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
803/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000804/// if (limit) {
805/// unsigned long startMutations = *enumState.mutationsPtr;
806/// do {
807/// unsigned long counter = 0;
808/// do {
809/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000810/// objc_enumerationMutation(l_collection);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000811/// elem = enumState.itemsPtr[counter++];
812/// stmts;
813/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000814/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
815/// objects:items count:16]);
816/// elem = nil;
817/// loopend: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000818/// }
819/// else
820/// elem = nil;
821/// }
822///
823Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000824 SourceLocation startLoc = S->getLocStart();
825 SourceLocation collectionLoc = S->getCollection()->getLocStart();
826 const char *startBuf = SM->getCharacterData(startLoc);
827 const char *startCollectionBuf = SM->getCharacterData(collectionLoc);
828 const char *elementName;
829 std::string buf;
830 buf = "\n{\n\t";
831 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
832 // type elem;
833 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
834 buf += ElementType.getAsString();
835 buf += " ";
836 elementName = DS->getDecl()->getName();
837 buf += elementName;
838 buf += ";\n\t";
839 }
840 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement()))
841 elementName = DR->getDecl()->getName();
842 else
843 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
844
845 // struct __objcFastEnumerationState enumState = { 0 };
846 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
847 // id items[16];
848 buf += "id items[16];\n\t";
849 // id l_collection = (id)
850 buf += "id l_collection = (id)";
851 // Replace: "for (type element in" with string constructed thus far.
852 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
853 buf.c_str(), buf.size());
854 // Replace ')' in for '(' type elem in collection ')' with ';'
855 SourceLocation endCollectionLoc = S->getCollection()->getLocEnd();
856 const char *endCollectionBuf = SM->getCharacterData(endCollectionLoc);
857 const char *lparenBuf = strchr(endCollectionBuf, ')');
858 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(lparenBuf-startBuf);
859 buf = ";\n\t";
860
861 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
862 // objects:items count:16];
863 // which is synthesized into:
864 // unsigned int limit =
865 // ((unsigned int (*)
866 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
867 // (void *)objc_msgSend)((id)l_collection,
868 // sel_registerName(
869 // "countByEnumeratingWithState:objects:count:"),
870 // (struct __objcFastEnumerationState *)&state,
871 // (id *)items, (unsigned int)16);
872 buf += "unsigned long limit =\n\t\t";
873 SynthCountByEnumWithState(buf);
874 buf += ";\n\t";
875 /// if (limit) {
876 /// unsigned long startMutations = *enumState.mutationsPtr;
877 /// do {
878 /// unsigned long counter = 0;
879 /// do {
880 /// if (startMutations != *enumState.mutationsPtr)
881 /// objc_enumerationMutation(l_collection);
882 /// elem = enumState.itemsPtr[counter++];
883 buf += "if (limit) {\n\t";
884 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
885 buf += "do {\n\t\t";
886 buf += "unsigned long counter = 0;\n\t\t";
887 buf += "do {\n\t\t\t";
888 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
889 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
890 buf += elementName;
891 buf += " = enumState.itemsPtr[counter++];";
892 // Replace ')' in for '(' type elem in collection ')' with all of these.
893 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
894
895 /// } while (counter < limit);
896 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
897 /// objects:items count:16]);
898 /// elem = nil;
899 /// loopend: ;
900 /// }
901 /// else
902 /// elem = nil;
903 /// }
904 buf = ";\n\t\t";
905 buf += "} while (counter < limit);\n\t";
906 buf += "} while (limit = ";
907 SynthCountByEnumWithState(buf);
908 buf += ");\n\t";
909 buf += elementName;
910 buf += " = nil;\n\t";
911 // TODO: Generate a unique label to exit the for loop on break statement.
912 // buf += "loopend: ;\n\t";
913 buf += "}\n\t";
914 buf += "else\n\t\t";
915 buf += elementName;
916 buf += " = nil;\n";
917 buf += "}\n";
918 // Insert all these *after* the statement body.
919 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
920 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
921 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
922 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
923
924 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000925}
926
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000927Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +0000928 // Get the start location and compute the semi location.
929 SourceLocation startLoc = S->getLocStart();
930 const char *startBuf = SM->getCharacterData(startLoc);
931
932 assert((*startBuf == '@') && "bogus @try location");
933
934 std::string buf;
935 // declare a new scope with two variables, _stack and _rethrow.
936 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
937 buf += "int buf[18/*32-bit i386*/];\n";
938 buf += "char *pointers[4];} _stack;\n";
939 buf += "id volatile _rethrow = 0;\n";
940 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000941 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +0000942
943 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
944
945 startLoc = S->getTryBody()->getLocEnd();
946 startBuf = SM->getCharacterData(startLoc);
947
948 assert((*startBuf == '}') && "bogus @try block");
949
950 SourceLocation lastCurlyLoc = startLoc;
951
952 startLoc = startLoc.getFileLocWithOffset(1);
953 buf = " /* @catch begin */ else {\n";
954 buf += " id _caught = objc_exception_extract(&_stack);\n";
955 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +0000956 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +0000957 buf += " _rethrow = objc_exception_extract(&_stack);\n";
958 buf += " else { /* @catch continue */";
959
Chris Lattner28d1fe82007-11-08 04:41:51 +0000960 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +0000961
962 bool sawIdTypedCatch = false;
963 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000964 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +0000965 while (catchList) {
966 Stmt *catchStmt = catchList->getCatchParamStmt();
967
968 if (catchList == S->getCatchStmts())
969 buf = "if ("; // we are generating code for the first catch clause
970 else
971 buf = "else if (";
972 startLoc = catchList->getLocStart();
973 startBuf = SM->getCharacterData(startLoc);
974
975 assert((*startBuf == '@') && "bogus @catch location");
976
977 const char *lParenLoc = strchr(startBuf, '(');
978
979 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
980 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000981 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +0000982 buf += "1) { ";
983 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
984 buf.c_str(), buf.size());
985 sawIdTypedCatch = true;
986 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000987 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +0000988
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +0000990 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +0000991 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +0000992 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +0000993 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroff75730982007-11-07 04:08:17 +0000994 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
995 buf.c_str(), buf.size());
996 }
997 }
998 // Now rewrite the body...
999 lastCatchBody = catchList->getCatchBody();
1000 SourceLocation rParenLoc = catchList->getRParenLoc();
1001 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1002 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1003 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1004 assert((*rParenBuf == ')') && "bogus @catch paren location");
1005 assert((*bodyBuf == '{') && "bogus @catch body location");
1006
1007 buf = " = _caught;";
1008 // Here we replace ") {" with "= _caught;" (which initializes and
1009 // declares the @catch parameter).
1010 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1011 buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001012 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001013 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001014 }
Steve Naroff75730982007-11-07 04:08:17 +00001015 catchList = catchList->getNextCatchStmt();
1016 }
1017 // Complete the catch list...
1018 if (lastCatchBody) {
1019 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1020 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1021 assert((*bodyBuf == '}') && "bogus @catch body location");
1022 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1023 buf = " } } /* @catch end */\n";
1024
Chris Lattner28d1fe82007-11-08 04:41:51 +00001025 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001026
1027 // Set lastCurlyLoc
1028 lastCurlyLoc = lastCatchBody->getLocEnd();
1029 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001030 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001031 startLoc = finalStmt->getLocStart();
1032 startBuf = SM->getCharacterData(startLoc);
1033 assert((*startBuf == '@') && "bogus @finally start");
1034
1035 buf = "/* @finally */";
1036 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1037
1038 Stmt *body = finalStmt->getFinallyBody();
1039 SourceLocation startLoc = body->getLocStart();
1040 SourceLocation endLoc = body->getLocEnd();
1041 const char *startBuf = SM->getCharacterData(startLoc);
1042 const char *endBuf = SM->getCharacterData(endLoc);
1043 assert((*startBuf == '{') && "bogus @finally body location");
1044 assert((*endBuf == '}') && "bogus @finally body location");
1045
1046 startLoc = startLoc.getFileLocWithOffset(1);
1047 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001048 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001049 endLoc = endLoc.getFileLocWithOffset(-1);
1050 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001051 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001052
1053 // Set lastCurlyLoc
1054 lastCurlyLoc = body->getLocEnd();
1055 }
1056 // Now emit the final closing curly brace...
1057 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1058 buf = " } /* @try scope end */\n";
Chris Lattner28d1fe82007-11-08 04:41:51 +00001059 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001060 return 0;
1061}
1062
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001063Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001064 return 0;
1065}
1066
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001067Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001068 return 0;
1069}
1070
Steve Naroff2bd03922007-11-07 15:32:26 +00001071// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1072// the throw expression is typically a message expression that's already
1073// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001074Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001075 // Get the start location and compute the semi location.
1076 SourceLocation startLoc = S->getLocStart();
1077 const char *startBuf = SM->getCharacterData(startLoc);
1078
1079 assert((*startBuf == '@') && "bogus @throw location");
1080
1081 std::string buf;
1082 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1083 buf = "objc_exception_throw(";
1084 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1085 const char *semiBuf = strchr(startBuf, ';');
1086 assert((*semiBuf == ';') && "@throw: can't find ';'");
1087 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1088 buf = ");";
1089 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1090 return 0;
1091}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001092
Chris Lattnere64b7772007-10-24 16:57:36 +00001093Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001094 // Create a new string expression.
1095 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001096 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001097 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001098 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1099 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001100 SourceLocation(), SourceLocation());
Chris Lattnere365c502007-11-30 22:25:36 +00001101 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1102 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001103 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1104 "rewriting sub-expression within a macro (may not be correct)");
Chris Lattner182745a2007-12-02 01:09:57 +00001105 SourceRange Range = Exp->getSourceRange();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00001106 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Chris Lattnere365c502007-11-30 22:25:36 +00001107 }
1108
Chris Lattner07506182007-11-30 22:53:43 +00001109 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001110 delete Exp;
1111 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001112}
1113
Steve Naroffb42f8412007-11-05 14:50:49 +00001114Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1115 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1116 // Create a call to sel_registerName("selName").
1117 llvm::SmallVector<Expr*, 8> SelExprs;
1118 QualType argType = Context->getPointerType(Context->CharTy);
1119 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1120 Exp->getSelector().getName().size(),
1121 false, argType, SourceLocation(),
1122 SourceLocation()));
1123 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1124 &SelExprs[0], SelExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001125 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1126 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001127 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1128 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001129 SourceRange Range = Exp->getSourceRange();
1130 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001131 }
Steve Naroffb42f8412007-11-05 14:50:49 +00001132 delete Exp;
1133 return SelExp;
1134}
1135
Steve Naroff934f2762007-10-24 22:48:43 +00001136CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1137 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001138 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001139 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001140
1141 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001142 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001143
1144 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001145 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001146 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1147
1148 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001149
Steve Naroff934f2762007-10-24 22:48:43 +00001150 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1151}
1152
Steve Naroffd5255f52007-11-01 13:24:47 +00001153static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1154 const char *&startRef, const char *&endRef) {
1155 while (startBuf < endBuf) {
1156 if (*startBuf == '<')
1157 startRef = startBuf; // mark the start.
1158 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001159 if (startRef && *startRef == '<') {
1160 endRef = startBuf; // mark the end.
1161 return true;
1162 }
1163 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001164 }
1165 startBuf++;
1166 }
1167 return false;
1168}
1169
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001170static void scanToNextArgument(const char *&argRef) {
1171 int angle = 0;
1172 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1173 if (*argRef == '<')
1174 angle++;
1175 else if (*argRef == '>')
1176 angle--;
1177 argRef++;
1178 }
1179 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1180}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001181
Steve Naroffd5255f52007-11-01 13:24:47 +00001182bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001183
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001184 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001185 return true;
1186
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001187 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001188 return true;
1189
Steve Naroffd5255f52007-11-01 13:24:47 +00001190 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001191 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001192 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001193 return true; // we have "Class <Protocol> *".
1194 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001195 return false;
1196}
1197
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001198void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001199 SourceLocation Loc;
1200 QualType Type;
1201 const FunctionTypeProto *proto = 0;
1202 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1203 Loc = VD->getLocation();
1204 Type = VD->getType();
1205 }
1206 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1207 Loc = FD->getLocation();
1208 // Check for ObjC 'id' and class types that have been adorned with protocol
1209 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1210 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1211 assert(funcType && "missing function type");
1212 proto = dyn_cast<FunctionTypeProto>(funcType);
1213 if (!proto)
1214 return;
1215 Type = proto->getResultType();
1216 }
1217 else
1218 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001219
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001220 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001221 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001222
1223 const char *endBuf = SM->getCharacterData(Loc);
1224 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001225 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001226 startBuf--; // scan backward (from the decl location) for return type.
1227 const char *startRef = 0, *endRef = 0;
1228 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1229 // Get the locations of the startRef, endRef.
1230 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1231 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1232 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001233 Rewrite.InsertText(LessLoc, "/*", 2);
1234 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001235 }
1236 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001237 if (!proto)
1238 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001239 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001240 const char *startBuf = SM->getCharacterData(Loc);
1241 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001242 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1243 if (needToScanForQualifiers(proto->getArgType(i))) {
1244 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001245
Steve Naroffd5255f52007-11-01 13:24:47 +00001246 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001247 // scan forward (from the decl location) for argument types.
1248 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001249 const char *startRef = 0, *endRef = 0;
1250 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1251 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001252 SourceLocation LessLoc =
1253 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1254 SourceLocation GreaterLoc =
1255 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001256 // Comment out the protocol references.
Chris Lattner28d1fe82007-11-08 04:41:51 +00001257 Rewrite.InsertText(LessLoc, "/*", 2);
1258 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001259 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001260 startBuf = ++endBuf;
1261 }
1262 else {
1263 while (*startBuf != ')' && *startBuf != ',')
1264 startBuf++; // scan forward (from the decl location) for argument types.
1265 startBuf++;
1266 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001267 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001268}
1269
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001270// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1271void RewriteTest::SynthSelGetUidFunctionDecl() {
1272 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1273 llvm::SmallVector<QualType, 16> ArgTys;
1274 ArgTys.push_back(Context->getPointerType(
1275 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001276 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001277 &ArgTys[0], ArgTys.size(),
1278 false /*isVariadic*/);
1279 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1280 SelGetUidIdent, getFuncType,
1281 FunctionDecl::Extern, false, 0);
1282}
1283
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001284// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1285void RewriteTest::SynthGetProtocolFunctionDecl() {
1286 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1287 llvm::SmallVector<QualType, 16> ArgTys;
1288 ArgTys.push_back(Context->getPointerType(
1289 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001290 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001291 &ArgTys[0], ArgTys.size(),
1292 false /*isVariadic*/);
1293 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1294 SelGetProtoIdent, getFuncType,
1295 FunctionDecl::Extern, false, 0);
1296}
1297
Steve Naroff09b266e2007-10-30 23:14:51 +00001298void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1299 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001300 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001301 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001302 return;
1303 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001304 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001305}
1306
1307// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1308void RewriteTest::SynthMsgSendFunctionDecl() {
1309 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1310 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001311 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001312 assert(!argT.isNull() && "Can't find 'id' type");
1313 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001314 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001315 assert(!argT.isNull() && "Can't find 'SEL' type");
1316 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001317 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001318 &ArgTys[0], ArgTys.size(),
1319 true /*isVariadic*/);
1320 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1321 msgSendIdent, msgSendType,
1322 FunctionDecl::Extern, false, 0);
1323}
1324
Steve Naroff874e2322007-11-15 10:28:18 +00001325// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1326void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1327 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1328 llvm::SmallVector<QualType, 16> ArgTys;
1329 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1330 &Context->Idents.get("objc_super"), 0);
1331 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1332 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1333 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001334 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001335 assert(!argT.isNull() && "Can't find 'SEL' type");
1336 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001337 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001338 &ArgTys[0], ArgTys.size(),
1339 true /*isVariadic*/);
1340 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1341 msgSendIdent, msgSendType,
1342 FunctionDecl::Extern, false, 0);
1343}
1344
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001345// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1346void RewriteTest::SynthMsgSendStretFunctionDecl() {
1347 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1348 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001349 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001350 assert(!argT.isNull() && "Can't find 'id' type");
1351 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001352 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001353 assert(!argT.isNull() && "Can't find 'SEL' type");
1354 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001355 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001356 &ArgTys[0], ArgTys.size(),
1357 true /*isVariadic*/);
1358 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1359 msgSendIdent, msgSendType,
1360 FunctionDecl::Extern, false, 0);
1361}
1362
1363// SynthMsgSendSuperStretFunctionDecl -
1364// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1365void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1366 IdentifierInfo *msgSendIdent =
1367 &Context->Idents.get("objc_msgSendSuper_stret");
1368 llvm::SmallVector<QualType, 16> ArgTys;
1369 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1370 &Context->Idents.get("objc_super"), 0);
1371 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1372 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1373 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001374 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001375 assert(!argT.isNull() && "Can't find 'SEL' type");
1376 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001377 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001378 &ArgTys[0], ArgTys.size(),
1379 true /*isVariadic*/);
1380 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1381 msgSendIdent, msgSendType,
1382 FunctionDecl::Extern, false, 0);
1383}
1384
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001385// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1386void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1387 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1388 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001389 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001390 assert(!argT.isNull() && "Can't find 'id' type");
1391 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001392 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001393 assert(!argT.isNull() && "Can't find 'SEL' type");
1394 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001395 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001396 &ArgTys[0], ArgTys.size(),
1397 true /*isVariadic*/);
1398 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1399 msgSendIdent, msgSendType,
1400 FunctionDecl::Extern, false, 0);
1401}
1402
Steve Naroff09b266e2007-10-30 23:14:51 +00001403// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1404void RewriteTest::SynthGetClassFunctionDecl() {
1405 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1406 llvm::SmallVector<QualType, 16> ArgTys;
1407 ArgTys.push_back(Context->getPointerType(
1408 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001409 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001410 &ArgTys[0], ArgTys.size(),
1411 false /*isVariadic*/);
1412 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1413 getClassIdent, getClassType,
1414 FunctionDecl::Extern, false, 0);
1415}
1416
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001417// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1418void RewriteTest::SynthGetMetaClassFunctionDecl() {
1419 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1420 llvm::SmallVector<QualType, 16> ArgTys;
1421 ArgTys.push_back(Context->getPointerType(
1422 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001423 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001424 &ArgTys[0], ArgTys.size(),
1425 false /*isVariadic*/);
1426 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1427 getClassIdent, getClassType,
1428 FunctionDecl::Extern, false, 0);
1429}
1430
Steve Naroff96984642007-11-08 14:30:50 +00001431// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1432void RewriteTest::SynthCFStringFunctionDecl() {
1433 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1434 llvm::SmallVector<QualType, 16> ArgTys;
1435 ArgTys.push_back(Context->getPointerType(
1436 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001437 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001438 &ArgTys[0], ArgTys.size(),
1439 false /*isVariadic*/);
1440 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1441 getClassIdent, getClassType,
1442 FunctionDecl::Extern, false, 0);
1443}
1444
Steve Naroffbeaf2992007-11-03 11:27:19 +00001445Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001446#if 1
1447 // This rewrite is specific to GCC, which has builtin support for CFString.
1448 if (!CFStringFunctionDecl)
1449 SynthCFStringFunctionDecl();
1450 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1451 llvm::SmallVector<Expr*, 8> StrExpr;
1452 StrExpr.push_back(Exp->getString());
1453 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1454 &StrExpr[0], StrExpr.size());
1455 // cast to NSConstantString *
1456 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroff5ca40202007-12-19 14:32:56 +00001457 if (Rewrite.ReplaceStmt(Exp, cast)) {
1458 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001459 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1460 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001461 SourceRange Range = Exp->getSourceRange();
1462 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001463 }
Steve Naroff96984642007-11-08 14:30:50 +00001464 delete Exp;
1465 return cast;
1466#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001467 assert(ConstantStringClassReference && "Can't find constant string reference");
1468 llvm::SmallVector<Expr*, 4> InitExprs;
1469
1470 // Synthesize "(Class)&_NSConstantStringClassReference"
1471 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1472 ConstantStringClassReference->getType(),
1473 SourceLocation());
1474 QualType expType = Context->getPointerType(ClsRef->getType());
1475 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1476 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001477 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001478 SourceLocation());
1479 InitExprs.push_back(cast); // set the 'isa'.
1480 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1481 unsigned IntSize = static_cast<unsigned>(
1482 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1483 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1484 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1485 Exp->getLocStart());
1486 InitExprs.push_back(len); // set "int numBytes".
1487
1488 // struct NSConstantString
1489 QualType CFConstantStrType = Context->getCFConstantStringType();
1490 // (struct NSConstantString) { <exprs from above> }
1491 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1492 &InitExprs[0], InitExprs.size(),
1493 SourceLocation());
1494 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE);
1495 // struct NSConstantString *
1496 expType = Context->getPointerType(StrRep->getType());
1497 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1498 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001499 // cast to NSConstantString *
1500 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroffbeaf2992007-11-03 11:27:19 +00001501 Rewrite.ReplaceStmt(Exp, cast);
1502 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001503 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001504#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001505}
1506
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001507ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001508 // check if we are sending a message to 'super'
1509 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001510 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1511 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1512 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1513 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001514 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001515 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001516 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001517 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001518 if (ObjCInterfaceType *IT =
1519 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001520 if (IT->getDecl() ==
1521 CurMethodDecl->getClassInterface()->getSuperClass())
1522 return IT->getDecl();
1523 }
1524 }
1525 }
1526 }
1527 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001528 }
Steve Naroff874e2322007-11-15 10:28:18 +00001529 }
1530 return 0;
1531}
1532
1533// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1534QualType RewriteTest::getSuperStructType() {
1535 if (!SuperStructDecl) {
1536 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1537 &Context->Idents.get("objc_super"), 0);
1538 QualType FieldTypes[2];
1539
1540 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001541 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001542 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001543 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001544 // Create fields
1545 FieldDecl *FieldDecls[2];
1546
1547 for (unsigned i = 0; i < 2; ++i)
1548 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1549
1550 SuperStructDecl->defineBody(FieldDecls, 4);
1551 }
1552 return Context->getTagDeclType(SuperStructDecl);
1553}
1554
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001555Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001556 if (!SelGetUidFunctionDecl)
1557 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001558 if (!MsgSendFunctionDecl)
1559 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001560 if (!MsgSendSuperFunctionDecl)
1561 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001562 if (!MsgSendStretFunctionDecl)
1563 SynthMsgSendStretFunctionDecl();
1564 if (!MsgSendSuperStretFunctionDecl)
1565 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001566 if (!MsgSendFpretFunctionDecl)
1567 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001568 if (!GetClassFunctionDecl)
1569 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001570 if (!GetMetaClassFunctionDecl)
1571 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001572
Steve Naroff874e2322007-11-15 10:28:18 +00001573 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001574 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1575 // May need to use objc_msgSend_stret() as well.
1576 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001577 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001578 QualType resultType = mDecl->getResultType();
1579 if (resultType.getCanonicalType()->isStructureType()
1580 || resultType.getCanonicalType()->isUnionType())
1581 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001582 else if (resultType.getCanonicalType()->isRealFloatingType())
1583 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001584 }
Steve Naroff874e2322007-11-15 10:28:18 +00001585
Steve Naroff934f2762007-10-24 22:48:43 +00001586 // Synthesize a call to objc_msgSend().
1587 llvm::SmallVector<Expr*, 8> MsgExprs;
1588 IdentifierInfo *clsName = Exp->getClassName();
1589
1590 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1591 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001592 if (!strcmp(clsName->getName(), "super")) {
1593 MsgSendFlavor = MsgSendSuperFunctionDecl;
1594 if (MsgSendStretFlavor)
1595 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1596 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1597
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001598 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001599 CurMethodDecl->getClassInterface()->getSuperClass();
1600
1601 llvm::SmallVector<Expr*, 4> InitExprs;
1602
1603 // set the receiver to self, the first argument to all methods.
1604 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001605 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001606 SourceLocation()));
1607 llvm::SmallVector<Expr*, 8> ClsExprs;
1608 QualType argType = Context->getPointerType(Context->CharTy);
1609 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1610 SuperDecl->getIdentifier()->getLength(),
1611 false, argType, SourceLocation(),
1612 SourceLocation()));
1613 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1614 &ClsExprs[0],
1615 ClsExprs.size());
1616 // To turn off a warning, type-cast to 'id'
1617 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001618 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001619 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1620 // struct objc_super
1621 QualType superType = getSuperStructType();
1622 // (struct objc_super) { <exprs from above> }
1623 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1624 &InitExprs[0], InitExprs.size(),
1625 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001626 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1627 superType, ILE);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001628 // struct objc_super *
1629 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1630 Context->getPointerType(SuperRep->getType()),
1631 SourceLocation());
1632 MsgExprs.push_back(Unop);
1633 } else {
1634 llvm::SmallVector<Expr*, 8> ClsExprs;
1635 QualType argType = Context->getPointerType(Context->CharTy);
1636 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1637 clsName->getLength(),
1638 false, argType, SourceLocation(),
1639 SourceLocation()));
1640 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1641 &ClsExprs[0],
1642 ClsExprs.size());
1643 MsgExprs.push_back(Cls);
1644 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001645 } else { // instance message.
1646 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001647
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001648 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001649 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001650 if (MsgSendStretFlavor)
1651 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001652 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1653
1654 llvm::SmallVector<Expr*, 4> InitExprs;
1655
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001656 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001657 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001658 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001659
1660 llvm::SmallVector<Expr*, 8> ClsExprs;
1661 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001662 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1663 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001664 false, argType, SourceLocation(),
1665 SourceLocation()));
1666 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001667 &ClsExprs[0],
1668 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001669 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001670 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001671 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001672 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001673 // struct objc_super
1674 QualType superType = getSuperStructType();
1675 // (struct objc_super) { <exprs from above> }
1676 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1677 &InitExprs[0], InitExprs.size(),
1678 SourceLocation());
Chris Lattner0fc53df2008-01-02 21:46:24 +00001679 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
1680 superType, ILE);
Steve Naroff874e2322007-11-15 10:28:18 +00001681 // struct objc_super *
1682 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1683 Context->getPointerType(SuperRep->getType()),
1684 SourceLocation());
1685 MsgExprs.push_back(Unop);
1686 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001687 // Remove all type-casts because it may contain objc-style types; e.g.
1688 // Foo<Proto> *.
1689 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1690 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001691 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001692 MsgExprs.push_back(recExpr);
1693 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001694 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001695 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001696 llvm::SmallVector<Expr*, 8> SelExprs;
1697 QualType argType = Context->getPointerType(Context->CharTy);
1698 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1699 Exp->getSelector().getName().size(),
1700 false, argType, SourceLocation(),
1701 SourceLocation()));
1702 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1703 &SelExprs[0], SelExprs.size());
1704 MsgExprs.push_back(SelExp);
1705
1706 // Now push any user supplied arguments.
1707 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001708 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001709 // Make all implicit casts explicit...ICE comes in handy:-)
1710 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1711 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001712 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1713 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001714 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001715 }
1716 // Make id<P...> cast into an 'id' cast.
1717 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001718 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001719 while ((CE = dyn_cast<CastExpr>(userExpr)))
1720 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001721 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00001722 userExpr, SourceLocation());
1723 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001724 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001725 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00001726 // We've transferred the ownership to MsgExprs. Null out the argument in
1727 // the original expression, since we will delete it below.
1728 Exp->setArg(i, 0);
1729 }
Steve Naroffab972d32007-11-04 22:37:50 +00001730 // Generate the funky cast.
1731 CastExpr *cast;
1732 llvm::SmallVector<QualType, 8> ArgTypes;
1733 QualType returnType;
1734
1735 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00001736 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1737 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1738 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001739 ArgTypes.push_back(Context->getObjCIdType());
1740 ArgTypes.push_back(Context->getObjCSelType());
1741 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00001742 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00001743 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001744 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1745 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001746 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00001747 ArgTypes.push_back(t);
1748 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001749 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1750 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00001751 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001752 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00001753 }
1754 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00001755 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00001756
1757 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001758 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1759 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00001760
1761 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1762 // If we don't do this cast, we get the following bizarre warning/note:
1763 // xx.m:13: warning: function called through a non-compatible type
1764 // xx.m:13: note: if this code is reached, the program will abort
1765 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1766 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00001767
Steve Naroffab972d32007-11-04 22:37:50 +00001768 // Now do the "normal" pointer to function cast.
1769 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001770 &ArgTypes[0], ArgTypes.size(),
1771 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00001772 castType = Context->getPointerType(castType);
1773 cast = new CastExpr(castType, cast, SourceLocation());
1774
1775 // Don't forget the parens to enforce the proper binding.
1776 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1777
1778 const FunctionType *FT = msgSendType->getAsFunctionType();
1779 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1780 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001781 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001782 if (MsgSendStretFlavor) {
1783 // We have the method which returns a struct/union. Must also generate
1784 // call to objc_msgSend_stret and hang both varieties on a conditional
1785 // expression which dictate which one to envoke depending on size of
1786 // method's return type.
1787
1788 // Create a reference to the objc_msgSend_stret() declaration.
1789 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1790 SourceLocation());
1791 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1792 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1793 SourceLocation());
1794 // Now do the "normal" pointer to function cast.
1795 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00001796 &ArgTypes[0], ArgTypes.size(),
1797 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001798 castType = Context->getPointerType(castType);
1799 cast = new CastExpr(castType, cast, SourceLocation());
1800
1801 // Don't forget the parens to enforce the proper binding.
1802 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1803
1804 FT = msgSendType->getAsFunctionType();
1805 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1806 FT->getResultType(), SourceLocation());
1807
1808 // Build sizeof(returnType)
1809 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
1810 returnType, Context->getSizeType(),
1811 SourceLocation(), SourceLocation());
1812 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1813 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
1814 // For X86 it is more complicated and some kind of target specific routine
1815 // is needed to decide what to do.
1816 unsigned IntSize = static_cast<unsigned>(
1817 Context->getTypeSize(Context->IntTy, SourceLocation()));
1818
1819 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
1820 Context->IntTy,
1821 SourceLocation());
1822 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
1823 BinaryOperator::LE,
1824 Context->IntTy,
1825 SourceLocation());
1826 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
1827 ConditionalOperator *CondExpr =
1828 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001829 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001830 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001831 return ReplacingStmt;
1832}
1833
1834Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
1835 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00001836 // Now do the actual rewrite.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001837 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroff5ca40202007-12-19 14:32:56 +00001838 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001839 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1840 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001841 SourceRange Range = Exp->getSourceRange();
1842 Diags.Report(Context->getFullLoc(Exp->getLocStart()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001843 }
Steve Naroff934f2762007-10-24 22:48:43 +00001844
Chris Lattnere64b7772007-10-24 16:57:36 +00001845 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001846 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00001847}
1848
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001849/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
1850/// call to objc_getProtocol("proto-name").
1851Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
1852 if (!GetProtocolFunctionDecl)
1853 SynthGetProtocolFunctionDecl();
1854 // Create a call to objc_getProtocol("ProtocolName").
1855 llvm::SmallVector<Expr*, 8> ProtoExprs;
1856 QualType argType = Context->getPointerType(Context->CharTy);
1857 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
1858 strlen(Exp->getProtocol()->getName()),
1859 false, argType, SourceLocation(),
1860 SourceLocation()));
1861 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
1862 &ProtoExprs[0],
1863 ProtoExprs.size());
Steve Naroff5ca40202007-12-19 14:32:56 +00001864 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
1865 // replacement failed.
Steve Naroff23ae0912007-12-19 19:16:49 +00001866 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Warning,
1867 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff5ca40202007-12-19 14:32:56 +00001868 SourceRange Range = Exp->getSourceRange();
1869 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), DiagID, 0, 0, &Range, 1);
Steve Naroff5ca40202007-12-19 14:32:56 +00001870 }
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001871 delete Exp;
1872 return ProtoExp;
1873
1874}
1875
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001876/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001877/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001878void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001879 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001880 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
1881 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001882 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001883 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00001884 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001885 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00001886 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00001887 SourceLocation LocStart = CDecl->getLocStart();
1888 SourceLocation LocEnd = CDecl->getLocEnd();
1889
1890 const char *startBuf = SM->getCharacterData(LocStart);
1891 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001892 // If no ivars and no root or if its root, directly or indirectly,
1893 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001894 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001895 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1896 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1897 Result.c_str(), Result.size());
1898 return;
1899 }
1900
1901 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001902 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00001903 Result += "\nstruct ";
1904 Result += CDecl->getName();
Steve Narofffea763e82007-11-14 19:25:57 +00001905
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001906 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00001907 const char *cursor = strchr(startBuf, '{');
1908 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001909 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00001910
1911 // rewrite the original header *without* disturbing the '{'
1912 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
1913 Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001914 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00001915 Result = "\n struct ";
1916 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001917 // Note: We don't name the field decl. This simplifies the "codegen" for
1918 // accessing a superclasses instance variables (and is similar to what gcc
1919 // does internally). The unnamed struct field feature is enabled with
1920 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1921 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001922 Result += ";\n";
1923
1924 // insert the super class structure definition.
1925 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
1926 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
1927 }
1928 cursor++; // past '{'
1929
1930 // Now comment out any visibility specifiers.
1931 while (cursor < endBuf) {
1932 if (*cursor == '@') {
1933 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00001934 // Skip whitespace.
1935 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
1936 /*scan*/;
1937
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001938 // FIXME: presence of @public, etc. inside comment results in
1939 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00001940 if (!strncmp(cursor, "public", strlen("public")) ||
1941 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00001942 !strncmp(cursor, "protected", strlen("protected")))
Steve Narofffea763e82007-11-14 19:25:57 +00001943 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001944 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00001945 // FIXME: If there are cases where '<' is used in ivar declaration part
1946 // of user code, then scan the ivar list and use needToScanForQualifiers
1947 // for type checking.
1948 else if (*cursor == '<') {
1949 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1950 Rewrite.InsertText(atLoc, "/* ", 3);
1951 cursor = strchr(cursor, '>');
1952 cursor++;
1953 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
1954 Rewrite.InsertText(atLoc, " */", 3);
1955 }
Steve Narofffea763e82007-11-14 19:25:57 +00001956 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00001957 }
Steve Narofffea763e82007-11-14 19:25:57 +00001958 // Don't forget to add a ';'!!
1959 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
1960 } else { // we don't have any instance variables - insert super struct.
1961 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
1962 Result += " {\n struct ";
1963 Result += RCDecl->getName();
Steve Naroff75ae7762007-12-07 22:15:58 +00001964 // Note: We don't name the field decl. This simplifies the "codegen" for
1965 // accessing a superclasses instance variables (and is similar to what gcc
1966 // does internally). The unnamed struct field feature is enabled with
1967 // -fms-extensions. If the struct definition were "inlined", we wouldn't
1968 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00001969 Result += ";\n};\n";
1970 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
1971 Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001972 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001973 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001974 if (!ObjCSynthesizedStructs.insert(CDecl))
1975 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00001976}
1977
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001978// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001979/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001980void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001981 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00001982 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001983 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00001984 const char *ClassName,
1985 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001986 if (MethodBegin == MethodEnd) return;
1987
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001988 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00001989 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001990 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00001991 SEL _cmd;
1992 char *method_types;
1993 void *_imp;
1994 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00001995 */
Chris Lattner158ecb92007-10-25 17:07:24 +00001996 Result += "\nstruct _objc_method {\n";
1997 Result += "\tSEL _cmd;\n";
1998 Result += "\tchar *method_types;\n";
1999 Result += "\tvoid *_imp;\n";
2000 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002001
2002 /* struct _objc_method_list {
2003 struct _objc_method_list *next_method;
2004 int method_count;
2005 struct _objc_method method_list[];
2006 }
2007 */
2008 Result += "\nstruct _objc_method_list {\n";
2009 Result += "\tstruct _objc_method_list *next_method;\n";
2010 Result += "\tint method_count;\n";
2011 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002012 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002013 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002014
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002015 // Build _objc_method_list for class's methods if needed
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002016 Result += "\nstatic struct _objc_method_list _OBJC_";
2017 Result += prefix;
2018 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2019 Result += "_METHODS_";
2020 Result += ClassName;
2021 Result += " __attribute__ ((section (\"__OBJC, __";
2022 Result += IsInstanceMethod ? "inst" : "cls";
2023 Result += "_meth\")))= ";
2024 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002025
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002026 Result += "\t,{{(SEL)\"";
2027 Result += (*MethodBegin)->getSelector().getName().c_str();
2028 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002029 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002030 Result += "\", \"";
2031 Result += MethodTypeString;
2032 Result += "\", ";
2033 Result += MethodInternalNames[*MethodBegin];
2034 Result += "}\n";
2035 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2036 Result += "\t ,{(SEL)\"";
2037 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002038 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002039 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002040 Result += "\", \"";
2041 Result += MethodTypeString;
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002042 Result += "\", ";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002043 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002044 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002045 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002046 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002047}
2048
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002049/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2050void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002051 int NumProtocols,
2052 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002053 const char *ClassName,
2054 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002055 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002056 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002057 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002058 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002059 // Output struct protocol_methods holder of method selector and type.
2060 if (!objc_protocol_methods &&
2061 (PDecl->getNumInstanceMethods() > 0
2062 || PDecl->getNumClassMethods() > 0)) {
2063 /* struct protocol_methods {
2064 SEL _cmd;
2065 char *method_types;
2066 }
2067 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002068 Result += "\nstruct protocol_methods {\n";
2069 Result += "\tSEL _cmd;\n";
2070 Result += "\tchar *method_types;\n";
2071 Result += "};\n";
2072
2073 /* struct _objc_protocol_method_list {
2074 int protocol_method_count;
2075 struct protocol_methods protocols[];
2076 }
2077 */
2078 Result += "\nstruct _objc_protocol_method_list {\n";
2079 Result += "\tint protocol_method_count;\n";
2080 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002081 objc_protocol_methods = true;
2082 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002083
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002084 int NumMethods = PDecl->getNumInstanceMethods();
2085 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002086 Result += "\nstatic struct _objc_protocol_method_list "
2087 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2088 Result += PDecl->getName();
2089 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2090 "{\n\t" + utostr(NumMethods) + "\n";
2091
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002092 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002093 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002094 E = PDecl->instmeth_end(); I != E; ++I) {
2095 if (I == PDecl->instmeth_begin())
2096 Result += "\t ,{{(SEL)\"";
2097 else
2098 Result += "\t ,{(SEL)\"";
2099 Result += (*I)->getSelector().getName().c_str();
2100 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002101 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002102 Result += "\", \"";
2103 Result += MethodTypeString;
2104 Result += "\"}\n";
2105 }
2106 Result += "\t }\n};\n";
2107 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002108
2109 // Output class methods declared in this protocol.
2110 NumMethods = PDecl->getNumClassMethods();
2111 if (NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002112 Result += "\nstatic struct _objc_protocol_method_list "
2113 "_OBJC_PROTOCOL_CLASS_METHODS_";
2114 Result += PDecl->getName();
2115 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2116 "{\n\t";
2117 Result += utostr(NumMethods);
2118 Result += "\n";
2119
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002120 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002121 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002122 E = PDecl->classmeth_end(); I != E; ++I) {
2123 if (I == PDecl->classmeth_begin())
2124 Result += "\t ,{{(SEL)\"";
2125 else
2126 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002127 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002128 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002129 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002130 Result += "\", \"";
2131 Result += MethodTypeString;
2132 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002133 }
2134 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002135 }
2136 // Output:
2137 /* struct _objc_protocol {
2138 // Objective-C 1.0 extensions
2139 struct _objc_protocol_extension *isa;
2140 char *protocol_name;
2141 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002142 struct _objc_protocol_method_list *instance_methods;
2143 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002144 };
2145 */
2146 static bool objc_protocol = false;
2147 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002148 Result += "\nstruct _objc_protocol {\n";
2149 Result += "\tstruct _objc_protocol_extension *isa;\n";
2150 Result += "\tchar *protocol_name;\n";
2151 Result += "\tstruct _objc_protocol **protocol_list;\n";
2152 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2153 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2154 Result += "};\n";
2155
2156 /* struct _objc_protocol_list {
2157 struct _objc_protocol_list *next;
2158 int protocol_count;
2159 struct _objc_protocol *class_protocols[];
2160 }
2161 */
2162 Result += "\nstruct _objc_protocol_list {\n";
2163 Result += "\tstruct _objc_protocol_list *next;\n";
2164 Result += "\tint protocol_count;\n";
2165 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2166 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002167 objc_protocol = true;
2168 }
2169
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002170 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2171 Result += PDecl->getName();
2172 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2173 "{\n\t0, \"";
2174 Result += PDecl->getName();
2175 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002176 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002177 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2178 Result += PDecl->getName();
2179 Result += ", ";
2180 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002181 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002182 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002183 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002184 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2185 Result += PDecl->getName();
2186 Result += "\n";
2187 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002188 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002189 Result += "0\n";
2190 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002191 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002192 // Output the top lovel protocol meta-data for the class.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002193 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2194 Result += prefix;
2195 Result += "_PROTOCOLS_";
2196 Result += ClassName;
2197 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2198 "{\n\t0, ";
2199 Result += utostr(NumProtocols);
2200 Result += "\n";
2201
2202 Result += "\t,{&_OBJC_PROTOCOL_";
2203 Result += Protocols[0]->getName();
2204 Result += " \n";
2205
2206 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002207 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002208 Result += "\t ,&_OBJC_PROTOCOL_";
2209 Result += PDecl->getName();
2210 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002211 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002212 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002213 }
2214}
2215
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002216/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002217/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002218void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002219 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002220 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002221 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002222 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002223 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2224 CDecl = CDecl->getNextClassCategory())
2225 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2226 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002227
Chris Lattnereb44eee2007-12-23 01:40:15 +00002228 std::string FullCategoryName = ClassDecl->getName();
2229 FullCategoryName += '_';
2230 FullCategoryName += IDecl->getName();
2231
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002232 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002233 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002234 true, "CATEGORY_", FullCategoryName.c_str(),
2235 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002236
2237 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002238 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002239 false, "CATEGORY_", FullCategoryName.c_str(),
2240 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002241
2242 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002243 // Null CDecl is case of a category implementation with no category interface
2244 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002245 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002246 CDecl->getNumReferencedProtocols(),
2247 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002248 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002249
2250 /* struct _objc_category {
2251 char *category_name;
2252 char *class_name;
2253 struct _objc_method_list *instance_methods;
2254 struct _objc_method_list *class_methods;
2255 struct _objc_protocol_list *protocols;
2256 // Objective-C 1.0 extensions
2257 uint32_t size; // sizeof (struct _objc_category)
2258 struct _objc_property_list *instance_properties; // category's own
2259 // @property decl.
2260 };
2261 */
2262
2263 static bool objc_category = false;
2264 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002265 Result += "\nstruct _objc_category {\n";
2266 Result += "\tchar *category_name;\n";
2267 Result += "\tchar *class_name;\n";
2268 Result += "\tstruct _objc_method_list *instance_methods;\n";
2269 Result += "\tstruct _objc_method_list *class_methods;\n";
2270 Result += "\tstruct _objc_protocol_list *protocols;\n";
2271 Result += "\tunsigned int size;\n";
2272 Result += "\tstruct _objc_property_list *instance_properties;\n";
2273 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002274 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002275 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002276 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2277 Result += FullCategoryName;
2278 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2279 Result += IDecl->getName();
2280 Result += "\"\n\t, \"";
2281 Result += ClassDecl->getName();
2282 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002283
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002284 if (IDecl->getNumInstanceMethods() > 0) {
2285 Result += "\t, (struct _objc_method_list *)"
2286 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2287 Result += FullCategoryName;
2288 Result += "\n";
2289 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002290 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002291 Result += "\t, 0\n";
2292 if (IDecl->getNumClassMethods() > 0) {
2293 Result += "\t, (struct _objc_method_list *)"
2294 "&_OBJC_CATEGORY_CLASS_METHODS_";
2295 Result += FullCategoryName;
2296 Result += "\n";
2297 }
2298 else
2299 Result += "\t, 0\n";
2300
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002301 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002302 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2303 Result += FullCategoryName;
2304 Result += "\n";
2305 }
2306 else
2307 Result += "\t, 0\n";
2308 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002309}
2310
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002311/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2312/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002313void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2314 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002315 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002316 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002317 Result += IDecl->getName();
2318 Result += ", ";
2319 Result += ivar->getName();
2320 Result += ")";
2321}
2322
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002323//===----------------------------------------------------------------------===//
2324// Meta Data Emission
2325//===----------------------------------------------------------------------===//
2326
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002327void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002328 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002329 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002330
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002331 // Explictly declared @interface's are already synthesized.
2332 if (CDecl->ImplicitInterfaceDecl()) {
2333 // FIXME: Implementation of a class with no @interface (legacy) doese not
2334 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002335 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002336 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002337
Chris Lattnerbe6df082007-12-12 07:56:42 +00002338 // Build _objc_ivar_list metadata for classes ivars if needed
2339 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2340 ? IDecl->getImplDeclNumIvars()
2341 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002342 if (NumIvars > 0) {
2343 static bool objc_ivar = false;
2344 if (!objc_ivar) {
2345 /* struct _objc_ivar {
2346 char *ivar_name;
2347 char *ivar_type;
2348 int ivar_offset;
2349 };
2350 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002351 Result += "\nstruct _objc_ivar {\n";
2352 Result += "\tchar *ivar_name;\n";
2353 Result += "\tchar *ivar_type;\n";
2354 Result += "\tint ivar_offset;\n";
2355 Result += "};\n";
2356
2357 /* struct _objc_ivar_list {
2358 int ivar_count;
2359 struct _objc_ivar ivar_list[];
2360 };
2361 */
2362 Result += "\nstruct _objc_ivar_list {\n";
2363 Result += "\tint ivar_count;\n";
2364 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002365 objc_ivar = true;
2366 }
2367
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002368 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2369 Result += IDecl->getName();
2370 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2371 "{\n\t";
2372 Result += utostr(NumIvars);
2373 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002374
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002375 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002376 if (IDecl->getImplDeclNumIvars() > 0) {
2377 IVI = IDecl->ivar_begin();
2378 IVE = IDecl->ivar_end();
2379 } else {
2380 IVI = CDecl->ivar_begin();
2381 IVE = CDecl->ivar_end();
2382 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002383 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002384 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002385 Result += "\", \"";
2386 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002387 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002388 Result += StrEncoding;
2389 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002390 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002391 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002392 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002393 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002394 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002395 Result += "\", \"";
2396 std::string StrEncoding;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002397 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002398 Result += StrEncoding;
2399 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002400 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002401 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002402 }
2403
2404 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002405 }
2406
2407 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002408 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002409 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002410
2411 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002412 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002413 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002414
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002415 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002416 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002417 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002418 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002419
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002420
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002421 // Declaration of class/meta-class metadata
2422 /* struct _objc_class {
2423 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002424 const char *super_class_name;
2425 char *name;
2426 long version;
2427 long info;
2428 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002429 struct _objc_ivar_list *ivars;
2430 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002431 struct objc_cache *cache;
2432 struct objc_protocol_list *protocols;
2433 const char *ivar_layout;
2434 struct _objc_class_ext *ext;
2435 };
2436 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002437 static bool objc_class = false;
2438 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002439 Result += "\nstruct _objc_class {\n";
2440 Result += "\tstruct _objc_class *isa;\n";
2441 Result += "\tconst char *super_class_name;\n";
2442 Result += "\tchar *name;\n";
2443 Result += "\tlong version;\n";
2444 Result += "\tlong info;\n";
2445 Result += "\tlong instance_size;\n";
2446 Result += "\tstruct _objc_ivar_list *ivars;\n";
2447 Result += "\tstruct _objc_method_list *methods;\n";
2448 Result += "\tstruct objc_cache *cache;\n";
2449 Result += "\tstruct _objc_protocol_list *protocols;\n";
2450 Result += "\tconst char *ivar_layout;\n";
2451 Result += "\tstruct _objc_class_ext *ext;\n";
2452 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002453 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002454 }
2455
2456 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002457 ObjCInterfaceDecl *RootClass = 0;
2458 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002459 while (SuperClass) {
2460 RootClass = SuperClass;
2461 SuperClass = SuperClass->getSuperClass();
2462 }
2463 SuperClass = CDecl->getSuperClass();
2464
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002465 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2466 Result += CDecl->getName();
2467 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2468 "{\n\t(struct _objc_class *)\"";
2469 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2470 Result += "\"";
2471
2472 if (SuperClass) {
2473 Result += ", \"";
2474 Result += SuperClass->getName();
2475 Result += "\", \"";
2476 Result += CDecl->getName();
2477 Result += "\"";
2478 }
2479 else {
2480 Result += ", 0, \"";
2481 Result += CDecl->getName();
2482 Result += "\"";
2483 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002484 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002485 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002486 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002487 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002488 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002489 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002490 Result += "\n";
2491 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002492 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002493 Result += ", 0\n";
2494 if (CDecl->getNumIntfRefProtocols() > 0) {
2495 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2496 Result += CDecl->getName();
2497 Result += ",0,0\n";
2498 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002499 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002500 Result += "\t,0,0,0,0\n";
2501 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002502
2503 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002504 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2505 Result += CDecl->getName();
2506 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2507 "{\n\t&_OBJC_METACLASS_";
2508 Result += CDecl->getName();
2509 if (SuperClass) {
2510 Result += ", \"";
2511 Result += SuperClass->getName();
2512 Result += "\", \"";
2513 Result += CDecl->getName();
2514 Result += "\"";
2515 }
2516 else {
2517 Result += ", 0, \"";
2518 Result += CDecl->getName();
2519 Result += "\"";
2520 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002521 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002522 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002523 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002524 Result += ",0";
2525 else {
2526 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002527 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002528 Result += CDecl->getName();
2529 Result += ")";
2530 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002531 if (NumIvars > 0) {
2532 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2533 Result += CDecl->getName();
2534 Result += "\n\t";
2535 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002536 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002537 Result += ",0";
2538 if (IDecl->getNumInstanceMethods() > 0) {
2539 Result += ", &_OBJC_INSTANCE_METHODS_";
2540 Result += CDecl->getName();
2541 Result += ", 0\n\t";
2542 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002543 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002544 Result += ",0,0";
2545 if (CDecl->getNumIntfRefProtocols() > 0) {
2546 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2547 Result += CDecl->getName();
2548 Result += ", 0,0\n";
2549 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002550 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002551 Result += ",0,0,0\n";
2552 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002553}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002554
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002555/// RewriteImplementations - This routine rewrites all method implementations
2556/// and emits meta-data.
2557
2558void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002559 int ClsDefCount = ClassImplementation.size();
2560 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002561
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002562 if (ClsDefCount == 0 && CatDefCount == 0)
2563 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002564 // Rewrite implemented methods
2565 for (int i = 0; i < ClsDefCount; i++)
2566 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002567
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002568 for (int i = 0; i < CatDefCount; i++)
2569 RewriteImplementationDecl(CategoryImplementation[i]);
2570
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002571 // This is needed for use of offsetof
2572 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002573
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002574 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002575 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002576 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002577
2578 // For each implemented category, write out all its meta data.
2579 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002580 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002581
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002582 // Write objc_symtab metadata
2583 /*
2584 struct _objc_symtab
2585 {
2586 long sel_ref_cnt;
2587 SEL *refs;
2588 short cls_def_cnt;
2589 short cat_def_cnt;
2590 void *defs[cls_def_cnt + cat_def_cnt];
2591 };
2592 */
2593
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002594 Result += "\nstruct _objc_symtab {\n";
2595 Result += "\tlong sel_ref_cnt;\n";
2596 Result += "\tSEL *refs;\n";
2597 Result += "\tshort cls_def_cnt;\n";
2598 Result += "\tshort cat_def_cnt;\n";
2599 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2600 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002601
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002602 Result += "static struct _objc_symtab "
2603 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2604 Result += "\t0, 0, " + utostr(ClsDefCount)
2605 + ", " + utostr(CatDefCount) + "\n";
2606 for (int i = 0; i < ClsDefCount; i++) {
2607 Result += "\t,&_OBJC_CLASS_";
2608 Result += ClassImplementation[i]->getName();
2609 Result += "\n";
2610 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002611
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002612 for (int i = 0; i < CatDefCount; i++) {
2613 Result += "\t,&_OBJC_CATEGORY_";
2614 Result += CategoryImplementation[i]->getClassInterface()->getName();
2615 Result += "_";
2616 Result += CategoryImplementation[i]->getName();
2617 Result += "\n";
2618 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002619
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002620 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002621
2622 // Write objc_module metadata
2623
2624 /*
2625 struct _objc_module {
2626 long version;
2627 long size;
2628 const char *name;
2629 struct _objc_symtab *symtab;
2630 }
2631 */
2632
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002633 Result += "\nstruct _objc_module {\n";
2634 Result += "\tlong version;\n";
2635 Result += "\tlong size;\n";
2636 Result += "\tconst char *name;\n";
2637 Result += "\tstruct _objc_symtab *symtab;\n";
2638 Result += "};\n\n";
2639 Result += "static struct _objc_module "
2640 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002641 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2642 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002643 Result += "};\n\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002644
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002645}
Chris Lattner311ff022007-10-16 22:36:42 +00002646