blob: d873a3472121963e2bb7b93cbac3372573e310c1 [file] [log] [blame]
Chris Lattnerb429ae42007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattnerb429ae42007-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 Lattner569faa62007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnerb429ae42007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner569faa62007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffe9780582007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner4478db92007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanianf185aef2007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerae43eb72007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff1c46cf12008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Steve Naroff764c1ae2007-11-15 10:28:18 +000026#include <sstream>
Chris Lattnerb429ae42007-10-11 00:43:27 +000027using namespace clang;
Chris Lattnerc3aa5c42007-10-25 17:07:24 +000028using llvm::utostr;
Chris Lattnerb429ae42007-10-11 00:43:27 +000029
Steve Naroff1c46cf12008-01-28 21:34:52 +000030static llvm::cl::opt<bool>
31SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
32 llvm::cl::desc("Silence ObjC rewriting warnings"));
33
Chris Lattnerb429ae42007-10-11 00:43:27 +000034namespace {
Chris Lattner569faa62007-10-11 18:38:32 +000035 class RewriteTest : public ASTConsumer {
Chris Lattner74db1682007-10-16 21:07:07 +000036 Rewriter Rewrite;
Chris Lattner258f26c2007-11-30 22:25:36 +000037 Diagnostic &Diags;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000038 unsigned RewriteFailedDiag;
39
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000040 ASTContext *Context;
Chris Lattnerb429ae42007-10-11 00:43:27 +000041 SourceManager *SM;
Chris Lattner569faa62007-10-11 18:38:32 +000042 unsigned MainFileID;
Chris Lattnerae43eb72007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner74db1682007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Ted Kremenek42730c52008-01-07 19:49:32 +000045 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
46 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
47 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
49 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000050 llvm::SmallVector<Stmt *, 32> Stmts;
51 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian248db262008-01-22 22:44:46 +000052 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffe9780582007-10-23 23:50:29 +000053
54 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000055 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000056 FunctionDecl *MsgSendStretFunctionDecl;
57 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000058 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffe9780582007-10-23 23:50:29 +000059 FunctionDecl *GetClassFunctionDecl;
Steve Naroff3b1caac2007-12-07 03:50:46 +000060 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff71226032007-10-24 22:48:43 +000061 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroffabb96362007-11-08 14:30:50 +000062 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000063 FunctionDecl *GetProtocolFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000064
Steve Naroff0add5d22007-11-03 11:27:19 +000065 // ObjC string constant support.
66 FileVarDecl *ConstantStringClassReference;
67 RecordDecl *NSStringRecord;
Steve Naroff0744c472007-11-04 22:37:50 +000068
Fariborz Jahanian22277422008-01-16 00:09:11 +000069 // ObjC foreach break/continue generation support.
Fariborz Jahanian13dad332008-01-15 23:58:23 +000070 int BcLabelCount;
71
Steve Naroff764c1ae2007-11-15 10:28:18 +000072 // Needed for super.
Ted Kremenek42730c52008-01-07 19:49:32 +000073 ObjCMethodDecl *CurMethodDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +000074 RecordDecl *SuperStructDecl;
75
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +000076 // Needed for header files being rewritten
77 bool IsHeader;
78
Fariborz Jahanian640a01f2007-10-18 19:23:00 +000079 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnerb429ae42007-10-11 00:43:27 +000080 public:
Ted Kremenek17861c52007-12-19 22:51:13 +000081 void Initialize(ASTContext &context) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +000082 Context = &context;
Ted Kremenekb3ee1932007-12-11 21:27:55 +000083 SM = &Context->getSourceManager();
Steve Naroffe9780582007-10-23 23:50:29 +000084 MsgSendFunctionDecl = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000085 MsgSendSuperFunctionDecl = 0;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +000086 MsgSendStretFunctionDecl = 0;
87 MsgSendSuperStretFunctionDecl = 0;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +000088 MsgSendFpretFunctionDecl = 0;
Steve Naroff95b28c12007-10-24 01:09:48 +000089 GetClassFunctionDecl = 0;
Steve Naroff3b1caac2007-12-07 03:50:46 +000090 GetMetaClassFunctionDecl = 0;
Steve Naroff71226032007-10-24 22:48:43 +000091 SelGetUidFunctionDecl = 0;
Steve Naroffabb96362007-11-08 14:30:50 +000092 CFStringFunctionDecl = 0;
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +000093 GetProtocolFunctionDecl = 0;
Steve Naroff0add5d22007-11-03 11:27:19 +000094 ConstantStringClassReference = 0;
95 NSStringRecord = 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +000096 CurMethodDecl = 0;
97 SuperStructDecl = 0;
Fariborz Jahanian13dad332008-01-15 23:58:23 +000098 BcLabelCount = 0;
Steve Naroff53b6f4c2008-01-30 19:17:43 +000099
Chris Lattnerae43eb72007-12-02 01:13:47 +0000100 // Get the ID and start/end of the main file.
Ted Kremenek17861c52007-12-19 22:51:13 +0000101 MainFileID = SM->getMainFileID();
Chris Lattnerae43eb72007-12-02 01:13:47 +0000102 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
103 MainFileStart = MainBuf->getBufferStart();
104 MainFileEnd = MainBuf->getBufferEnd();
105
106
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000107 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Narofffcab7932007-11-05 14:55:35 +0000108 // declaring objc_selector outside the parameter list removes a silly
109 // scope related warning...
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000110 const char *s = "#pragma once\n"
111 "struct objc_selector; struct objc_class;\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000112 "#ifndef OBJC_SUPER\n"
113 "struct objc_super { struct objc_object *o; "
114 "struct objc_object *superClass; };\n"
115 "#define OBJC_SUPER\n"
116 "#endif\n"
117 "#ifndef _REWRITER_typedef_Protocol\n"
118 "typedef struct objc_object Protocol;\n"
119 "#define _REWRITER_typedef_Protocol\n"
120 "#endif\n"
Steve Narofffcab7932007-11-05 14:55:35 +0000121 "extern struct objc_object *objc_msgSend"
Steve Naroff0744c472007-11-04 22:37:50 +0000122 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff764c1ae2007-11-15 10:28:18 +0000123 "extern struct objc_object *objc_msgSendSuper"
124 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000125 "extern struct objc_object *objc_msgSend_stret"
126 "(struct objc_object *, struct objc_selector *, ...);\n"
127 "extern struct objc_object *objc_msgSendSuper_stret"
128 "(struct objc_super *, struct objc_selector *, ...);\n"
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000129 "extern struct objc_object *objc_msgSend_fpret"
130 "(struct objc_object *, struct objc_selector *, ...);\n"
Steve Naroff0744c472007-11-04 22:37:50 +0000131 "extern struct objc_object *objc_getClass"
Steve Naroffd3287d82007-11-07 18:43:40 +0000132 "(const char *);\n"
Steve Naroff3b1caac2007-12-07 03:50:46 +0000133 "extern struct objc_object *objc_getMetaClass"
134 "(const char *);\n"
Steve Naroffd3287d82007-11-07 18:43:40 +0000135 "extern void objc_exception_throw(struct objc_object *);\n"
136 "extern void objc_exception_try_enter(void *);\n"
137 "extern void objc_exception_try_exit(void *);\n"
138 "extern struct objc_object *objc_exception_extract(void *);\n"
139 "extern int objc_exception_match"
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +0000140 "(struct objc_class *, struct objc_object *, ...);\n"
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000141 "extern Protocol *objc_getProtocol(const char *);\n"
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000142 "#include <objc/objc.h>\n"
Fariborz Jahaniand8d36532008-01-10 23:04:06 +0000143 "#ifndef __FASTENUMERATIONSTATE\n"
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000144 "struct __objcFastEnumerationState {\n\t"
145 "unsigned long state;\n\t"
146 "id *itemsPtr;\n\t"
147 "unsigned long *mutationsPtr;\n\t"
Fariborz Jahaniand8d36532008-01-10 23:04:06 +0000148 "unsigned long extra[5];\n};\n"
149 "#define __FASTENUMERATIONSTATE\n"
150 "#endif\n";
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000151 if (IsHeader) {
152 // insert the whole string when rewriting a header file
153 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
154 s, strlen(s));
155 }
156 else {
157 // Not rewriting header, exclude the #pragma once pragma
158 const char *p = s + strlen("#pragma once\n");
159 Rewrite.InsertText(SourceLocation::getFileLoc(MainFileID, 0),
160 p, strlen(p));
161 }
Chris Lattnerb429ae42007-10-11 00:43:27 +0000162 }
Chris Lattner569faa62007-10-11 18:38:32 +0000163
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000164 // Top Level Driver code.
165 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner74db1682007-10-16 21:07:07 +0000166 void HandleDeclInMainFile(Decl *D);
Steve Naroff1c46cf12008-01-28 21:34:52 +0000167 RewriteTest(bool isHeader, Diagnostic &D) : Diags(D) {
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000168 IsHeader = isHeader;
Steve Naroff1c46cf12008-01-28 21:34:52 +0000169 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
170 "rewriting sub-expression within a macro (may not be correct)");
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000171 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000172 ~RewriteTest();
173
174 // Syntactic Rewriting.
Steve Naroff0744c472007-11-04 22:37:50 +0000175 void RewritePrologue(SourceLocation Loc);
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000176 void RewriteInclude();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000177 void RewriteTabs();
Ted Kremenek42730c52008-01-07 19:49:32 +0000178 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
179 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000180 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremenek42730c52008-01-07 19:49:32 +0000181 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
182 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
183 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
184 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
185 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
186 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff02a82aa2007-10-30 23:14:51 +0000187 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000188 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffc8a92d12007-11-01 13:24:47 +0000189 bool needToScanForQualifiers(QualType T);
Ted Kremenek42730c52008-01-07 19:49:32 +0000190 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff764c1ae2007-11-15 10:28:18 +0000191 QualType getSuperStructType();
Chris Lattner6fe8b272007-10-16 22:36:42 +0000192
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000193 // Expression Rewriting.
Steve Naroff334fbc22007-11-09 15:20:18 +0000194 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner0021f452007-10-24 16:57:36 +0000195 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000196 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroff296b74f2007-11-05 14:50:49 +0000197 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner0021f452007-10-24 16:57:36 +0000198 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroff0add5d22007-11-03 11:27:19 +0000199 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000200 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremenek42730c52008-01-07 19:49:32 +0000201 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000202 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek42730c52008-01-07 19:49:32 +0000203 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
204 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
205 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner2c022162008-01-31 05:10:40 +0000206 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
207 SourceLocation OrigEnd);
Steve Naroff71226032007-10-24 22:48:43 +0000208 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
209 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000210 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000211 Stmt *RewriteBreakStmt(BreakStmt *S);
212 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000213 void SynthCountByEnumWithState(std::string &buf);
214
Steve Naroff02a82aa2007-10-30 23:14:51 +0000215 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000216 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000217 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000218 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000219 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000220 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000221 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000222 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000223 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000224 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000225
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000226 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000227 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000228 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000229
Ted Kremenek42730c52008-01-07 19:49:32 +0000230 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000231 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000232
Ted Kremenek42730c52008-01-07 19:49:32 +0000233 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
234 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000235 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000236 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000237 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000238 const char *ClassName,
239 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000240
Ted Kremenek42730c52008-01-07 19:49:32 +0000241 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000242 int NumProtocols,
243 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000244 const char *ClassName,
245 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000246 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000247 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000248 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
249 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000250 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000251 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000252 };
253}
254
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000255static bool IsHeaderFile(const std::string &Filename) {
256 std::string::size_type DotPos = Filename.rfind('.');
257
258 if (DotPos == std::string::npos) {
259 // no file extension
260 return false;
261 }
262
263 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
264 // C header: .h
265 // C++ header: .hh or .H;
266 return Ext == "h" || Ext == "hh" || Ext == "H";
267}
268
269ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
270 Diagnostic &Diags) {
271 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattner258f26c2007-11-30 22:25:36 +0000272}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000273
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000274//===----------------------------------------------------------------------===//
275// Top Level Driver Code
276//===----------------------------------------------------------------------===//
277
Chris Lattner569faa62007-10-11 18:38:32 +0000278void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000279 // Two cases: either the decl could be in the main file, or it could be in a
280 // #included file. If the former, rewrite it now. If the later, check to see
281 // if we rewrote the #include/#import.
282 SourceLocation Loc = D->getLocation();
283 Loc = SM->getLogicalLoc(Loc);
284
285 // If this is for a builtin, ignore it.
286 if (Loc.isInvalid()) return;
287
Steve Naroffe9780582007-10-23 23:50:29 +0000288 // Look for built-in declarations that we need to refer during the rewrite.
289 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000290 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000291 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
292 // declared in <Foundation/NSString.h>
293 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
294 ConstantStringClassReference = FVD;
295 return;
296 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000297 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000298 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000299 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000300 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000301 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000302 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000303 } else if (ObjCForwardProtocolDecl *FP =
304 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000305 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000306 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000307 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000308 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
309 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000310}
311
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000312/// HandleDeclInMainFile - This is called for each top-level decl defined in the
313/// main file of the input.
314void RewriteTest::HandleDeclInMainFile(Decl *D) {
315 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
316 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000317 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000318
Ted Kremenek42730c52008-01-07 19:49:32 +0000319 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000320 if (Stmt *Body = MD->getBody()) {
321 //Body->dump();
322 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000323 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000324 CurMethodDecl = 0;
325 }
Steve Naroff18c83382007-11-13 23:01:27 +0000326 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000327 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000328 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000329 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000330 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000331 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000332 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000333 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000334 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000335 if (VD->getInit())
336 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
337 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000338 // Nothing yet.
339}
340
341RewriteTest::~RewriteTest() {
342 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000343
344 // Rewrite tabs if we care.
345 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000346
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000347 RewriteInclude();
348
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000349 // Rewrite Objective-c meta data*
350 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000351 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000352
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000353 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
354 // we are done.
355 if (const RewriteBuffer *RewriteBuf =
356 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000357 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000358 std::string S(RewriteBuf->begin(), RewriteBuf->end());
359 printf("%s\n", S.c_str());
360 } else {
361 printf("No changes\n");
362 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000363 // Emit metadata.
364 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000365}
366
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000367//===----------------------------------------------------------------------===//
368// Syntactic (non-AST) Rewriting Code
369//===----------------------------------------------------------------------===//
370
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000371void RewriteTest::RewriteInclude() {
372 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
373 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
374 const char *MainBufStart = MainBuf.first;
375 const char *MainBufEnd = MainBuf.second;
376 size_t ImportLen = strlen("import");
377 size_t IncludeLen = strlen("include");
378
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000379 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000380 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
381 if (*BufPtr == '#') {
382 if (++BufPtr == MainBufEnd)
383 return;
384 while (*BufPtr == ' ' || *BufPtr == '\t')
385 if (++BufPtr == MainBufEnd)
386 return;
387 if (!strncmp(BufPtr, "import", ImportLen)) {
388 // replace import with include
389 SourceLocation ImportLoc =
390 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
391 Rewrite.ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
392 BufPtr += ImportLen;
393 }
394 }
395 }
Chris Lattner74db1682007-10-16 21:07:07 +0000396}
397
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000398void RewriteTest::RewriteTabs() {
399 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
400 const char *MainBufStart = MainBuf.first;
401 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000402
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000403 // Loop over the whole file, looking for tabs.
404 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
405 if (*BufPtr != '\t')
406 continue;
407
408 // Okay, we found a tab. This tab will turn into at least one character,
409 // but it depends on which 'virtual column' it is in. Compute that now.
410 unsigned VCol = 0;
411 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
412 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
413 ++VCol;
414
415 // Okay, now that we know the virtual column, we know how many spaces to
416 // insert. We assume 8-character tab-stops.
417 unsigned Spaces = 8-(VCol & 7);
418
419 // Get the location of the tab.
420 SourceLocation TabLoc =
421 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
422
423 // Rewrite the single tab character into a sequence of spaces.
424 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
425 }
Chris Lattner569faa62007-10-11 18:38:32 +0000426}
427
428
Ted Kremenek42730c52008-01-07 19:49:32 +0000429void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000430 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000431 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000432
433 // Get the start location and compute the semi location.
434 SourceLocation startLoc = ClassDecl->getLocation();
435 const char *startBuf = SM->getCharacterData(startLoc);
436 const char *semiPtr = strchr(startBuf, ';');
437
438 // Translate to typedef's that forward reference structs with the same name
439 // as the class. As a convenience, we include the original declaration
440 // as a comment.
441 std::string typedefString;
442 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000443 typedefString.append(startBuf, semiPtr-startBuf+1);
444 typedefString += "\n";
445 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000446 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000447 typedefString += "#ifndef _REWRITER_typedef_";
448 typedefString += ForwardDecl->getName();
449 typedefString += "\n";
450 typedefString += "#define _REWRITER_typedef_";
451 typedefString += ForwardDecl->getName();
452 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000453 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000454 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000455 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000456 }
457
458 // Replace the @class with typedefs corresponding to the classes.
459 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
460 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000461}
462
Ted Kremenek42730c52008-01-07 19:49:32 +0000463void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000464 SourceLocation LocStart = Method->getLocStart();
465 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000466
Steve Naroff2ce399a2007-12-14 23:37:57 +0000467 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000468 Rewrite.InsertText(LocStart, "/* ", 3);
469 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000470 } else {
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000471 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000472 }
473}
474
Ted Kremenek42730c52008-01-07 19:49:32 +0000475void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000476{
477 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000478 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000479 SourceLocation Loc = Property->getLocation();
480
481 Rewrite.ReplaceText(Loc, 0, "// ", 3);
482
483 // FIXME: handle properties that are declared across multiple lines.
484 }
485}
486
Ted Kremenek42730c52008-01-07 19:49:32 +0000487void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000488 SourceLocation LocStart = CatDecl->getLocStart();
489
490 // FIXME: handle category headers that are declared across multiple lines.
491 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
492
Ted Kremenek42730c52008-01-07 19:49:32 +0000493 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000494 E = CatDecl->instmeth_end(); I != E; ++I)
495 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000496 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000497 E = CatDecl->classmeth_end(); I != E; ++I)
498 RewriteMethodDeclaration(*I);
499
Steve Naroff667f1682007-10-30 13:30:57 +0000500 // Lastly, comment out the @end.
501 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
502}
503
Ted Kremenek42730c52008-01-07 19:49:32 +0000504void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000505 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000506
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000507 SourceLocation LocStart = PDecl->getLocStart();
508
509 // FIXME: handle protocol headers that are declared across multiple lines.
510 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
511
Ted Kremenek42730c52008-01-07 19:49:32 +0000512 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000513 E = PDecl->instmeth_end(); I != E; ++I)
514 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000515 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000516 E = PDecl->classmeth_end(); I != E; ++I)
517 RewriteMethodDeclaration(*I);
518
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000519 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000520 SourceLocation LocEnd = PDecl->getAtEndLoc();
521 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000522
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000523 // Must comment out @optional/@required
524 const char *startBuf = SM->getCharacterData(LocStart);
525 const char *endBuf = SM->getCharacterData(LocEnd);
526 for (const char *p = startBuf; p < endBuf; p++) {
527 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
528 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000529 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000530 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
531 CommentedOptional.c_str(), CommentedOptional.size());
532
533 }
534 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
535 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000536 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000537 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
538 CommentedRequired.c_str(), CommentedRequired.size());
539
540 }
541 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000542}
543
Ted Kremenek42730c52008-01-07 19:49:32 +0000544void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000545 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000546 if (LocStart.isInvalid())
547 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000548 // FIXME: handle forward protocol that are declared across multiple lines.
549 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
550}
551
Ted Kremenek42730c52008-01-07 19:49:32 +0000552void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000553 std::string &ResultStr) {
554 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000555 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000556 ResultStr += "id";
557 else
558 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000559 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000560
561 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000562 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000563
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000564 if (OMD->isInstance())
565 NameStr += "_I_";
566 else
567 NameStr += "_C_";
568
569 NameStr += OMD->getClassInterface()->getName();
570 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000571
572 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000573 if (ObjCCategoryImplDecl *CID =
574 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000575 NameStr += CID->getName();
576 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000577 }
578 // Append selector names, replacing ':' with '_'
579 const char *selName = OMD->getSelector().getName().c_str();
580 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000581 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000582 else {
583 std::string selString = OMD->getSelector().getName();
584 int len = selString.size();
585 for (int i = 0; i < len; i++)
586 if (selString[i] == ':')
587 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000588 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000589 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000590 // Remember this name for metadata emission
591 MethodInternalNames[OMD] = NameStr;
592 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000593
594 // Rewrite arguments
595 ResultStr += "(";
596
597 // invisible arguments
598 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000599 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000600 selfTy = Context->getPointerType(selfTy);
Ted Kremenek42730c52008-01-07 19:49:32 +0000601 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000602 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000603 ResultStr += selfTy.getAsString();
604 }
605 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000606 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000607
608 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000609 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000610 ResultStr += " _cmd";
611
612 // Method arguments.
613 for (int i = 0; i < OMD->getNumParams(); i++) {
614 ParmVarDecl *PDecl = OMD->getParamDecl(i);
615 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000616 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000617 ResultStr += "id";
618 else
619 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000620 ResultStr += " ";
621 ResultStr += PDecl->getName();
622 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000623 if (OMD->isVariadic())
624 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000625 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000626
627}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000628void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000629 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
630 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000631
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000632 if (IMD)
633 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
634 else
635 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000636
Ted Kremenek42730c52008-01-07 19:49:32 +0000637 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000638 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
639 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000640 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000641 ObjCMethodDecl *OMD = *I;
642 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000643 SourceLocation LocStart = OMD->getLocStart();
644 SourceLocation LocEnd = OMD->getBody()->getLocStart();
645
646 const char *startBuf = SM->getCharacterData(LocStart);
647 const char *endBuf = SM->getCharacterData(LocEnd);
648 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
649 ResultStr.c_str(), ResultStr.size());
650 }
651
Ted Kremenek42730c52008-01-07 19:49:32 +0000652 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000653 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
654 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000655 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000656 ObjCMethodDecl *OMD = *I;
657 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000658 SourceLocation LocStart = OMD->getLocStart();
659 SourceLocation LocEnd = OMD->getBody()->getLocStart();
660
661 const char *startBuf = SM->getCharacterData(LocStart);
662 const char *endBuf = SM->getCharacterData(LocEnd);
663 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
664 ResultStr.c_str(), ResultStr.size());
665 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000666 if (IMD)
667 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
668 else
669 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000670}
671
Ted Kremenek42730c52008-01-07 19:49:32 +0000672void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000673 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000674 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000675 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000676 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000677 ResultStr += ClassDecl->getName();
678 ResultStr += "\n";
679 ResultStr += "#define _REWRITER_typedef_";
680 ResultStr += ClassDecl->getName();
681 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000682 ResultStr += "typedef struct ";
683 ResultStr += ClassDecl->getName();
684 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000685 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000686 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000687
688 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000689 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000690 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000691 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000692
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000693 RewriteProperties(ClassDecl->getNumPropertyDecl(),
694 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000695 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000696 E = ClassDecl->instmeth_end(); I != E; ++I)
697 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000698 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000699 E = ClassDecl->classmeth_end(); I != E; ++I)
700 RewriteMethodDeclaration(*I);
701
Steve Naroff1ccf4632007-10-30 03:43:13 +0000702 // Lastly, comment out the @end.
703 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000704}
705
Steve Naroff6b759ce2007-11-15 02:58:25 +0000706Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000707 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff6b759ce2007-11-15 02:58:25 +0000708 if (IV->isFreeIvar()) {
709 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
710 IV->getLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000711 if (Rewrite.ReplaceStmt(IV, Replacement)) {
712 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +0000713 SourceRange Range = IV->getSourceRange();
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000714 if (!SilenceRewriteMacroWarning)
Steve Naroff1c46cf12008-01-28 21:34:52 +0000715 Diags.Report(Context->getFullLoc(IV->getLocation()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000716 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000717 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000718 delete IV;
719 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000720 } else {
Fariborz Jahanianc8849882008-01-23 20:34:40 +0000721#if 0
722 /// This code is not right. It seems unnecessary. It breaks use of
723 /// ivar reference used as 'receiver' of an expression; as in:
724 /// [newInv->_container addObject:0];
Steve Naroff292b7b92007-11-15 11:33:00 +0000725 if (CurMethodDecl) {
726 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000727 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff292b7b92007-11-15 11:33:00 +0000728 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
729 IdentifierInfo *II = intT->getDecl()->getIdentifier();
730 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
731 II, 0);
732 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
733
734 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
735 // Don't forget the parens to enforce the proper binding.
736 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000737 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
738 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +0000739 SourceRange Range = IV->getBase()->getSourceRange();
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000740 if (!SilenceRewriteMacroWarning)
Steve Naroff1c46cf12008-01-28 21:34:52 +0000741 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()),
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000742 RewriteFailedDiag, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000743 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000744 delete IV->getBase();
745 return PE;
746 }
747 }
748 }
Fariborz Jahanianc8849882008-01-23 20:34:40 +0000749#endif
Steve Naroff6b759ce2007-11-15 02:58:25 +0000750 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000751 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000752}
753
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000754//===----------------------------------------------------------------------===//
755// Function Body / Expression rewriting
756//===----------------------------------------------------------------------===//
757
Steve Naroff334fbc22007-11-09 15:20:18 +0000758Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000759 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
760 isa<DoStmt>(S) || isa<ForStmt>(S))
761 Stmts.push_back(S);
762 else if (isa<ObjCForCollectionStmt>(S)) {
763 Stmts.push_back(S);
764 ObjCBcLabelNo.push_back(++BcLabelCount);
765 }
766
Chris Lattner2c022162008-01-31 05:10:40 +0000767 SourceLocation OrigStmtEnd = S->getLocEnd();
768
769 // Start by rewriting all children.
Chris Lattner6fe8b272007-10-16 22:36:42 +0000770 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
771 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000772 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000773 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000774 if (newStmt)
775 *CI = newStmt;
776 }
Steve Naroffe9780582007-10-23 23:50:29 +0000777
778 // Handle specific things.
779 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
780 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000781
782 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
783 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000784
785 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
786 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000787
Steve Naroff0add5d22007-11-03 11:27:19 +0000788 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
789 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000790
Steve Naroff71226032007-10-24 22:48:43 +0000791 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
792 // Before we rewrite it, put the original message expression in a comment.
793 SourceLocation startLoc = MessExpr->getLocStart();
794 SourceLocation endLoc = MessExpr->getLocEnd();
795
796 const char *startBuf = SM->getCharacterData(startLoc);
797 const char *endBuf = SM->getCharacterData(endLoc);
798
799 std::string messString;
800 messString += "// ";
801 messString.append(startBuf, endBuf-startBuf+1);
802 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000803
Steve Naroff71226032007-10-24 22:48:43 +0000804 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
805 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
806 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000807 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000808 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000809 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000810
Ted Kremenek42730c52008-01-07 19:49:32 +0000811 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
812 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000813
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000814 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
815 return RewriteObjCSynchronizedStmt(StmtTry);
816
Ted Kremenek42730c52008-01-07 19:49:32 +0000817 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
818 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000819
820 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
821 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000822
823 if (ObjCForCollectionStmt *StmtForCollection =
824 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner2c022162008-01-31 05:10:40 +0000825 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000826 if (BreakStmt *StmtBreakStmt =
827 dyn_cast<BreakStmt>(S))
828 return RewriteBreakStmt(StmtBreakStmt);
829 if (ContinueStmt *StmtContinueStmt =
830 dyn_cast<ContinueStmt>(S))
831 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000832
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000833 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
834 isa<DoStmt>(S) || isa<ForStmt>(S)) {
835 assert(!Stmts.empty() && "Statement stack is empty");
836 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
837 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
838 && "Statement stack mismatch");
839 Stmts.pop_back();
840 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000841#if 0
842 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
843 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
844 // Get the new text.
845 std::ostringstream Buf;
846 Replacement->printPretty(Buf);
847 const std::string &Str = Buf.str();
848
849 printf("CAST = %s\n", &Str[0]);
850 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
851 delete S;
852 return Replacement;
853 }
854#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000855 // Return this stmt unmodified.
856 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000857}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000858
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000859/// SynthCountByEnumWithState - To print:
860/// ((unsigned int (*)
861/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
862/// (void *)objc_msgSend)((id)l_collection,
863/// sel_registerName(
864/// "countByEnumeratingWithState:objects:count:"),
865/// &enumState,
866/// (id *)items, (unsigned int)16)
867///
868void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
869 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
870 "id *, unsigned int))(void *)objc_msgSend)";
871 buf += "\n\t\t";
872 buf += "((id)l_collection,\n\t\t";
873 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
874 buf += "\n\t\t";
875 buf += "&enumState, "
876 "(id *)items, (unsigned int)16)";
877}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000878
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000879/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
880/// statement to exit to its outer synthesized loop.
881///
882Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
883 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
884 return S;
885 // replace break with goto __break_label
886 std::string buf;
887
888 SourceLocation startLoc = S->getLocStart();
889 buf = "goto __break_label_";
890 buf += utostr(ObjCBcLabelNo.back());
891 Rewrite.ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
892
893 return 0;
894}
895
896/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
897/// statement to continue with its inner synthesized loop.
898///
899Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
900 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
901 return S;
902 // replace continue with goto __continue_label
903 std::string buf;
904
905 SourceLocation startLoc = S->getLocStart();
906 buf = "goto __continue_label_";
907 buf += utostr(ObjCBcLabelNo.back());
908 Rewrite.ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
909
910 return 0;
911}
912
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000913/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000914/// It rewrites:
915/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000916
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000917/// Into:
918/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000919/// type elem;
920/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000921/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000922/// id l_collection = (id)collection;
923/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
924/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000925/// if (limit) {
926/// unsigned long startMutations = *enumState.mutationsPtr;
927/// do {
928/// unsigned long counter = 0;
929/// do {
930/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000931/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000932/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000933/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000934/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000935/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000936/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
937/// objects:items count:16]);
938/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000939/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000940/// }
941/// else
942/// elem = nil;
943/// }
944///
Chris Lattner2c022162008-01-31 05:10:40 +0000945Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
946 SourceLocation OrigEnd) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000947 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
948 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
949 "ObjCForCollectionStmt Statement stack mismatch");
950 assert(!ObjCBcLabelNo.empty() &&
951 "ObjCForCollectionStmt - Label No stack empty");
952
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000953 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000954 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000955 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000956 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000957 std::string buf;
958 buf = "\n{\n\t";
959 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
960 // type elem;
961 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000962 elementTypeAsString = ElementType.getAsString();
963 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000964 buf += " ";
965 elementName = DS->getDecl()->getName();
966 buf += elementName;
967 buf += ";\n\t";
968 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000969 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000970 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000971 elementTypeAsString = DR->getDecl()->getType().getAsString();
972 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000973 else
974 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
975
976 // struct __objcFastEnumerationState enumState = { 0 };
977 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
978 // id items[16];
979 buf += "id items[16];\n\t";
980 // id l_collection = (id)
981 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +0000982 // Find start location of 'collection' the hard way!
983 const char *startCollectionBuf = startBuf;
984 startCollectionBuf += 3; // skip 'for'
985 startCollectionBuf = strchr(startCollectionBuf, '(');
986 startCollectionBuf++; // skip '('
987 // find 'in' and skip it.
988 while (*startCollectionBuf != ' ' ||
989 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
990 (*(startCollectionBuf+3) != ' ' &&
991 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
992 startCollectionBuf++;
993 startCollectionBuf += 3;
994
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000995 // Replace: "for (type element in" with string constructed thus far.
996 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
997 buf.c_str(), buf.size());
998 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +0000999 SourceLocation rightParenLoc = S->getRParenLoc();
1000 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1001 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001002 buf = ";\n\t";
1003
1004 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1005 // objects:items count:16];
1006 // which is synthesized into:
1007 // unsigned int limit =
1008 // ((unsigned int (*)
1009 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1010 // (void *)objc_msgSend)((id)l_collection,
1011 // sel_registerName(
1012 // "countByEnumeratingWithState:objects:count:"),
1013 // (struct __objcFastEnumerationState *)&state,
1014 // (id *)items, (unsigned int)16);
1015 buf += "unsigned long limit =\n\t\t";
1016 SynthCountByEnumWithState(buf);
1017 buf += ";\n\t";
1018 /// if (limit) {
1019 /// unsigned long startMutations = *enumState.mutationsPtr;
1020 /// do {
1021 /// unsigned long counter = 0;
1022 /// do {
1023 /// if (startMutations != *enumState.mutationsPtr)
1024 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001025 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001026 buf += "if (limit) {\n\t";
1027 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1028 buf += "do {\n\t\t";
1029 buf += "unsigned long counter = 0;\n\t\t";
1030 buf += "do {\n\t\t\t";
1031 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1032 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1033 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001034 buf += " = (";
1035 buf += elementTypeAsString;
1036 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001037 // Replace ')' in for '(' type elem in collection ')' with all of these.
1038 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
1039
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001040 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001041 /// } while (counter < limit);
1042 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1043 /// objects:items count:16]);
1044 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001045 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001046 /// }
1047 /// else
1048 /// elem = nil;
1049 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001050 ///
1051 buf = ";\n\t";
1052 buf += "__continue_label_";
1053 buf += utostr(ObjCBcLabelNo.back());
1054 buf += ": ;";
1055 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001056 buf += "} while (counter < limit);\n\t";
1057 buf += "} while (limit = ";
1058 SynthCountByEnumWithState(buf);
1059 buf += ");\n\t";
1060 buf += elementName;
1061 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001062 buf += "__break_label_";
1063 buf += utostr(ObjCBcLabelNo.back());
1064 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001065 buf += "}\n\t";
1066 buf += "else\n\t\t";
1067 buf += elementName;
1068 buf += " = nil;\n";
1069 buf += "}\n";
1070 // Insert all these *after* the statement body.
Chris Lattner2c022162008-01-31 05:10:40 +00001071 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001072 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001073 Stmts.pop_back();
1074 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001075 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001076}
1077
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001078/// RewriteObjCSynchronizedStmt -
1079/// This routine rewrites @synchronized(expr) stmt;
1080/// into:
1081/// objc_sync_enter(expr);
1082/// @try stmt @finally { objc_sync_exit(expr); }
1083///
1084Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1085 // Get the start location and compute the semi location.
1086 SourceLocation startLoc = S->getLocStart();
1087 const char *startBuf = SM->getCharacterData(startLoc);
1088
1089 assert((*startBuf == '@') && "bogus @synchronized location");
1090
1091 std::string buf;
1092 buf = "objc_sync_enter";
1093 Rewrite.ReplaceText(startLoc, 13, buf.c_str(), buf.size());
1094 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1095 const char *endBuf = SM->getCharacterData(endLoc);
1096 endBuf++;
1097 const char *rparenBuf = strchr(endBuf, ')');
1098 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1099 buf = ");\n";
1100 // declare a new scope with two variables, _stack and _rethrow.
1101 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1102 buf += "int buf[18/*32-bit i386*/];\n";
1103 buf += "char *pointers[4];} _stack;\n";
1104 buf += "id volatile _rethrow = 0;\n";
1105 buf += "objc_exception_try_enter(&_stack);\n";
1106 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1107 Rewrite.ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
1108 startLoc = S->getSynchBody()->getLocEnd();
1109 startBuf = SM->getCharacterData(startLoc);
1110
1111 assert((*startBuf == '}') && "bogus @try block");
1112 SourceLocation lastCurlyLoc = startLoc;
1113 buf = "}\nelse {\n";
1114 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1115 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1116 // FIXME: This must be objc_sync_exit(syncExpr);
1117 buf += " objc_sync_exit();\n";
1118 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1119 buf += "}\n";
1120 buf += "}";
1121
1122 Rewrite.ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
1123 return 0;
1124}
1125
Ted Kremenek42730c52008-01-07 19:49:32 +00001126Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001127 // Get the start location and compute the semi location.
1128 SourceLocation startLoc = S->getLocStart();
1129 const char *startBuf = SM->getCharacterData(startLoc);
1130
1131 assert((*startBuf == '@') && "bogus @try location");
1132
1133 std::string buf;
1134 // declare a new scope with two variables, _stack and _rethrow.
1135 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1136 buf += "int buf[18/*32-bit i386*/];\n";
1137 buf += "char *pointers[4];} _stack;\n";
1138 buf += "id volatile _rethrow = 0;\n";
1139 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001140 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001141
1142 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
1143
1144 startLoc = S->getTryBody()->getLocEnd();
1145 startBuf = SM->getCharacterData(startLoc);
1146
1147 assert((*startBuf == '}') && "bogus @try block");
1148
1149 SourceLocation lastCurlyLoc = startLoc;
1150
1151 startLoc = startLoc.getFileLocWithOffset(1);
1152 buf = " /* @catch begin */ else {\n";
1153 buf += " id _caught = objc_exception_extract(&_stack);\n";
1154 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001155 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001156 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1157 buf += " else { /* @catch continue */";
1158
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001159 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001160
1161 bool sawIdTypedCatch = false;
1162 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001163 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001164 while (catchList) {
1165 Stmt *catchStmt = catchList->getCatchParamStmt();
1166
1167 if (catchList == S->getCatchStmts())
1168 buf = "if ("; // we are generating code for the first catch clause
1169 else
1170 buf = "else if (";
1171 startLoc = catchList->getLocStart();
1172 startBuf = SM->getCharacterData(startLoc);
1173
1174 assert((*startBuf == '@') && "bogus @catch location");
1175
1176 const char *lParenLoc = strchr(startBuf, '(');
1177
1178 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
1179 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001180 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001181 buf += "1) { ";
1182 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1183 buf.c_str(), buf.size());
1184 sawIdTypedCatch = true;
1185 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001186 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001187
Ted Kremenek42730c52008-01-07 19:49:32 +00001188 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001189 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001190 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001191 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001192 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +00001193 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1194 buf.c_str(), buf.size());
1195 }
1196 }
1197 // Now rewrite the body...
1198 lastCatchBody = catchList->getCatchBody();
1199 SourceLocation rParenLoc = catchList->getRParenLoc();
1200 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1201 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1202 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1203 assert((*rParenBuf == ')') && "bogus @catch paren location");
1204 assert((*bodyBuf == '{') && "bogus @catch body location");
1205
1206 buf = " = _caught;";
1207 // Here we replace ") {" with "= _caught;" (which initializes and
1208 // declares the @catch parameter).
1209 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1210 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001211 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001212 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001213 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001214 catchList = catchList->getNextCatchStmt();
1215 }
1216 // Complete the catch list...
1217 if (lastCatchBody) {
1218 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1219 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1220 assert((*bodyBuf == '}') && "bogus @catch body location");
1221 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1222 buf = " } } /* @catch end */\n";
1223
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001224 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001225
1226 // Set lastCurlyLoc
1227 lastCurlyLoc = lastCatchBody->getLocEnd();
1228 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001229 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001230 startLoc = finalStmt->getLocStart();
1231 startBuf = SM->getCharacterData(startLoc);
1232 assert((*startBuf == '@') && "bogus @finally start");
1233
1234 buf = "/* @finally */";
1235 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1236
1237 Stmt *body = finalStmt->getFinallyBody();
1238 SourceLocation startLoc = body->getLocStart();
1239 SourceLocation endLoc = body->getLocEnd();
1240 const char *startBuf = SM->getCharacterData(startLoc);
1241 const char *endBuf = SM->getCharacterData(endLoc);
1242 assert((*startBuf == '{') && "bogus @finally body location");
1243 assert((*endBuf == '}') && "bogus @finally body location");
1244
1245 startLoc = startLoc.getFileLocWithOffset(1);
1246 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001247 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001248 endLoc = endLoc.getFileLocWithOffset(-1);
1249 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001250 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001251
1252 // Set lastCurlyLoc
1253 lastCurlyLoc = body->getLocEnd();
1254 }
1255 // Now emit the final closing curly brace...
1256 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1257 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001258 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001259 return 0;
1260}
1261
Ted Kremenek42730c52008-01-07 19:49:32 +00001262Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001263 return 0;
1264}
1265
Ted Kremenek42730c52008-01-07 19:49:32 +00001266Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001267 return 0;
1268}
1269
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001270// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1271// the throw expression is typically a message expression that's already
1272// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001273Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001274 // Get the start location and compute the semi location.
1275 SourceLocation startLoc = S->getLocStart();
1276 const char *startBuf = SM->getCharacterData(startLoc);
1277
1278 assert((*startBuf == '@') && "bogus @throw location");
1279
1280 std::string buf;
1281 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001282 if (S->getThrowExpr())
1283 buf = "objc_exception_throw(";
1284 else // add an implicit argument
1285 buf = "objc_exception_throw(_caught";
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001286 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1287 const char *semiBuf = strchr(startBuf, ';');
1288 assert((*semiBuf == ';') && "@throw: can't find ';'");
1289 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1290 buf = ");";
1291 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1292 return 0;
1293}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001294
Chris Lattner0021f452007-10-24 16:57:36 +00001295Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001296 // Create a new string expression.
1297 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001298 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001299 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1300 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001301 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1302 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001303 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +00001304 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1305 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +00001306 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001307 if (!SilenceRewriteMacroWarning)
1308 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001309 0, 0, &Range, 1);
Chris Lattner258f26c2007-11-30 22:25:36 +00001310 }
1311
Chris Lattner4478db92007-11-30 22:53:43 +00001312 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001313 delete Exp;
1314 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001315}
1316
Steve Naroff296b74f2007-11-05 14:50:49 +00001317Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1318 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1319 // Create a call to sel_registerName("selName").
1320 llvm::SmallVector<Expr*, 8> SelExprs;
1321 QualType argType = Context->getPointerType(Context->CharTy);
1322 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1323 Exp->getSelector().getName().size(),
1324 false, argType, SourceLocation(),
1325 SourceLocation()));
1326 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1327 &SelExprs[0], SelExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001328 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1329 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001330 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001331 if (!SilenceRewriteMacroWarning)
1332 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001333 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001334 }
Steve Naroff296b74f2007-11-05 14:50:49 +00001335 delete Exp;
1336 return SelExp;
1337}
1338
Steve Naroff71226032007-10-24 22:48:43 +00001339CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1340 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001341 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001342 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001343
1344 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001345 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001346
1347 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001348 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001349 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1350
1351 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001352
Steve Naroff71226032007-10-24 22:48:43 +00001353 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1354}
1355
Steve Naroffc8a92d12007-11-01 13:24:47 +00001356static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1357 const char *&startRef, const char *&endRef) {
1358 while (startBuf < endBuf) {
1359 if (*startBuf == '<')
1360 startRef = startBuf; // mark the start.
1361 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001362 if (startRef && *startRef == '<') {
1363 endRef = startBuf; // mark the end.
1364 return true;
1365 }
1366 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001367 }
1368 startBuf++;
1369 }
1370 return false;
1371}
1372
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001373static void scanToNextArgument(const char *&argRef) {
1374 int angle = 0;
1375 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1376 if (*argRef == '<')
1377 angle++;
1378 else if (*argRef == '>')
1379 angle--;
1380 argRef++;
1381 }
1382 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1383}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001384
Steve Naroffc8a92d12007-11-01 13:24:47 +00001385bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001386
Ted Kremenek42730c52008-01-07 19:49:32 +00001387 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001388 return true;
1389
Ted Kremenek42730c52008-01-07 19:49:32 +00001390 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001391 return true;
1392
Steve Naroffc8a92d12007-11-01 13:24:47 +00001393 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001394 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001395 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001396 return true; // we have "Class <Protocol> *".
1397 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001398 return false;
1399}
1400
Ted Kremenek42730c52008-01-07 19:49:32 +00001401void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001402 SourceLocation Loc;
1403 QualType Type;
1404 const FunctionTypeProto *proto = 0;
1405 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1406 Loc = VD->getLocation();
1407 Type = VD->getType();
1408 }
1409 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1410 Loc = FD->getLocation();
1411 // Check for ObjC 'id' and class types that have been adorned with protocol
1412 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1413 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1414 assert(funcType && "missing function type");
1415 proto = dyn_cast<FunctionTypeProto>(funcType);
1416 if (!proto)
1417 return;
1418 Type = proto->getResultType();
1419 }
1420 else
1421 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001422
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001423 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001424 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001425
1426 const char *endBuf = SM->getCharacterData(Loc);
1427 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001428 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001429 startBuf--; // scan backward (from the decl location) for return type.
1430 const char *startRef = 0, *endRef = 0;
1431 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1432 // Get the locations of the startRef, endRef.
1433 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1434 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1435 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001436 Rewrite.InsertText(LessLoc, "/*", 2);
1437 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001438 }
1439 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001440 if (!proto)
1441 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001442 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001443 const char *startBuf = SM->getCharacterData(Loc);
1444 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001445 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1446 if (needToScanForQualifiers(proto->getArgType(i))) {
1447 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001448
Steve Naroffc8a92d12007-11-01 13:24:47 +00001449 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001450 // scan forward (from the decl location) for argument types.
1451 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001452 const char *startRef = 0, *endRef = 0;
1453 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1454 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001455 SourceLocation LessLoc =
1456 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1457 SourceLocation GreaterLoc =
1458 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001459 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001460 Rewrite.InsertText(LessLoc, "/*", 2);
1461 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001462 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001463 startBuf = ++endBuf;
1464 }
1465 else {
1466 while (*startBuf != ')' && *startBuf != ',')
1467 startBuf++; // scan forward (from the decl location) for argument types.
1468 startBuf++;
1469 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001470 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001471}
1472
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001473// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1474void RewriteTest::SynthSelGetUidFunctionDecl() {
1475 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1476 llvm::SmallVector<QualType, 16> ArgTys;
1477 ArgTys.push_back(Context->getPointerType(
1478 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001479 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001480 &ArgTys[0], ArgTys.size(),
1481 false /*isVariadic*/);
1482 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1483 SelGetUidIdent, getFuncType,
1484 FunctionDecl::Extern, false, 0);
1485}
1486
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001487// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1488void RewriteTest::SynthGetProtocolFunctionDecl() {
1489 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1490 llvm::SmallVector<QualType, 16> ArgTys;
1491 ArgTys.push_back(Context->getPointerType(
1492 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001493 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001494 &ArgTys[0], ArgTys.size(),
1495 false /*isVariadic*/);
1496 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1497 SelGetProtoIdent, getFuncType,
1498 FunctionDecl::Extern, false, 0);
1499}
1500
Steve Naroff02a82aa2007-10-30 23:14:51 +00001501void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1502 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001503 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001504 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001505 return;
1506 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001507 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001508}
1509
1510// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1511void RewriteTest::SynthMsgSendFunctionDecl() {
1512 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1513 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001514 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001515 assert(!argT.isNull() && "Can't find 'id' type");
1516 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001517 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001518 assert(!argT.isNull() && "Can't find 'SEL' type");
1519 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001520 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001521 &ArgTys[0], ArgTys.size(),
1522 true /*isVariadic*/);
1523 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1524 msgSendIdent, msgSendType,
1525 FunctionDecl::Extern, false, 0);
1526}
1527
Steve Naroff764c1ae2007-11-15 10:28:18 +00001528// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1529void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1530 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1531 llvm::SmallVector<QualType, 16> ArgTys;
1532 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1533 &Context->Idents.get("objc_super"), 0);
1534 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1535 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1536 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001537 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001538 assert(!argT.isNull() && "Can't find 'SEL' type");
1539 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001540 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001541 &ArgTys[0], ArgTys.size(),
1542 true /*isVariadic*/);
1543 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1544 msgSendIdent, msgSendType,
1545 FunctionDecl::Extern, false, 0);
1546}
1547
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001548// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1549void RewriteTest::SynthMsgSendStretFunctionDecl() {
1550 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1551 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001552 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001553 assert(!argT.isNull() && "Can't find 'id' type");
1554 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001555 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001556 assert(!argT.isNull() && "Can't find 'SEL' type");
1557 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001558 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001559 &ArgTys[0], ArgTys.size(),
1560 true /*isVariadic*/);
1561 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1562 msgSendIdent, msgSendType,
1563 FunctionDecl::Extern, false, 0);
1564}
1565
1566// SynthMsgSendSuperStretFunctionDecl -
1567// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1568void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1569 IdentifierInfo *msgSendIdent =
1570 &Context->Idents.get("objc_msgSendSuper_stret");
1571 llvm::SmallVector<QualType, 16> ArgTys;
1572 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1573 &Context->Idents.get("objc_super"), 0);
1574 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1575 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1576 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001577 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001578 assert(!argT.isNull() && "Can't find 'SEL' type");
1579 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001580 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001581 &ArgTys[0], ArgTys.size(),
1582 true /*isVariadic*/);
1583 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1584 msgSendIdent, msgSendType,
1585 FunctionDecl::Extern, false, 0);
1586}
1587
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001588// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1589void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1590 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1591 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001592 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001593 assert(!argT.isNull() && "Can't find 'id' type");
1594 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001595 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001596 assert(!argT.isNull() && "Can't find 'SEL' type");
1597 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001598 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001599 &ArgTys[0], ArgTys.size(),
1600 true /*isVariadic*/);
1601 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1602 msgSendIdent, msgSendType,
1603 FunctionDecl::Extern, false, 0);
1604}
1605
Steve Naroff02a82aa2007-10-30 23:14:51 +00001606// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1607void RewriteTest::SynthGetClassFunctionDecl() {
1608 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1609 llvm::SmallVector<QualType, 16> ArgTys;
1610 ArgTys.push_back(Context->getPointerType(
1611 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001612 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001613 &ArgTys[0], ArgTys.size(),
1614 false /*isVariadic*/);
1615 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1616 getClassIdent, getClassType,
1617 FunctionDecl::Extern, false, 0);
1618}
1619
Steve Naroff3b1caac2007-12-07 03:50:46 +00001620// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1621void RewriteTest::SynthGetMetaClassFunctionDecl() {
1622 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1623 llvm::SmallVector<QualType, 16> ArgTys;
1624 ArgTys.push_back(Context->getPointerType(
1625 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001626 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001627 &ArgTys[0], ArgTys.size(),
1628 false /*isVariadic*/);
1629 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1630 getClassIdent, getClassType,
1631 FunctionDecl::Extern, false, 0);
1632}
1633
Steve Naroffabb96362007-11-08 14:30:50 +00001634// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1635void RewriteTest::SynthCFStringFunctionDecl() {
1636 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1637 llvm::SmallVector<QualType, 16> ArgTys;
1638 ArgTys.push_back(Context->getPointerType(
1639 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001640 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffabb96362007-11-08 14:30:50 +00001641 &ArgTys[0], ArgTys.size(),
1642 false /*isVariadic*/);
1643 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1644 getClassIdent, getClassType,
1645 FunctionDecl::Extern, false, 0);
1646}
1647
Steve Naroff0add5d22007-11-03 11:27:19 +00001648Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001649#if 1
1650 // This rewrite is specific to GCC, which has builtin support for CFString.
1651 if (!CFStringFunctionDecl)
1652 SynthCFStringFunctionDecl();
1653 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1654 llvm::SmallVector<Expr*, 8> StrExpr;
1655 StrExpr.push_back(Exp->getString());
1656 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1657 &StrExpr[0], StrExpr.size());
1658 // cast to NSConstantString *
1659 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001660 if (Rewrite.ReplaceStmt(Exp, cast)) {
1661 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001662 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001663 if (!SilenceRewriteMacroWarning)
1664 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001665 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001666 }
Steve Naroffabb96362007-11-08 14:30:50 +00001667 delete Exp;
1668 return cast;
1669#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001670 assert(ConstantStringClassReference && "Can't find constant string reference");
1671 llvm::SmallVector<Expr*, 4> InitExprs;
1672
1673 // Synthesize "(Class)&_NSConstantStringClassReference"
1674 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1675 ConstantStringClassReference->getType(),
1676 SourceLocation());
1677 QualType expType = Context->getPointerType(ClsRef->getType());
1678 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1679 expType, SourceLocation());
Ted Kremenek42730c52008-01-07 19:49:32 +00001680 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroff0add5d22007-11-03 11:27:19 +00001681 SourceLocation());
1682 InitExprs.push_back(cast); // set the 'isa'.
1683 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1684 unsigned IntSize = static_cast<unsigned>(
1685 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1686 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1687 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1688 Exp->getLocStart());
1689 InitExprs.push_back(len); // set "int numBytes".
1690
1691 // struct NSConstantString
1692 QualType CFConstantStrType = Context->getCFConstantStringType();
1693 // (struct NSConstantString) { <exprs from above> }
1694 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1695 &InitExprs[0], InitExprs.size(),
1696 SourceLocation());
Steve Naroffbe37fc02008-01-14 18:19:28 +00001697 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroff0add5d22007-11-03 11:27:19 +00001698 // struct NSConstantString *
1699 expType = Context->getPointerType(StrRep->getType());
1700 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1701 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001702 // cast to NSConstantString *
1703 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001704 Rewrite.ReplaceStmt(Exp, cast);
1705 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001706 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001707#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001708}
1709
Ted Kremenek42730c52008-01-07 19:49:32 +00001710ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001711 // check if we are sending a message to 'super'
1712 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001713 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1714 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1715 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1716 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001717 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001718 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001719 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001720 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001721 if (ObjCInterfaceType *IT =
1722 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001723 if (IT->getDecl() ==
1724 CurMethodDecl->getClassInterface()->getSuperClass())
1725 return IT->getDecl();
1726 }
1727 }
1728 }
1729 }
1730 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001731 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001732 }
1733 return 0;
1734}
1735
1736// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1737QualType RewriteTest::getSuperStructType() {
1738 if (!SuperStructDecl) {
1739 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1740 &Context->Idents.get("objc_super"), 0);
1741 QualType FieldTypes[2];
1742
1743 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001744 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001745 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001746 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001747 // Create fields
1748 FieldDecl *FieldDecls[2];
1749
1750 for (unsigned i = 0; i < 2; ++i)
1751 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1752
1753 SuperStructDecl->defineBody(FieldDecls, 4);
1754 }
1755 return Context->getTagDeclType(SuperStructDecl);
1756}
1757
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001758Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001759 if (!SelGetUidFunctionDecl)
1760 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001761 if (!MsgSendFunctionDecl)
1762 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001763 if (!MsgSendSuperFunctionDecl)
1764 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001765 if (!MsgSendStretFunctionDecl)
1766 SynthMsgSendStretFunctionDecl();
1767 if (!MsgSendSuperStretFunctionDecl)
1768 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001769 if (!MsgSendFpretFunctionDecl)
1770 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001771 if (!GetClassFunctionDecl)
1772 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001773 if (!GetMetaClassFunctionDecl)
1774 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001775
Steve Naroff764c1ae2007-11-15 10:28:18 +00001776 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001777 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1778 // May need to use objc_msgSend_stret() as well.
1779 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001780 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001781 QualType resultType = mDecl->getResultType();
1782 if (resultType.getCanonicalType()->isStructureType()
1783 || resultType.getCanonicalType()->isUnionType())
1784 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001785 else if (resultType.getCanonicalType()->isRealFloatingType())
1786 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001787 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001788
Steve Naroff71226032007-10-24 22:48:43 +00001789 // Synthesize a call to objc_msgSend().
1790 llvm::SmallVector<Expr*, 8> MsgExprs;
1791 IdentifierInfo *clsName = Exp->getClassName();
1792
1793 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1794 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001795 if (!strcmp(clsName->getName(), "super")) {
1796 MsgSendFlavor = MsgSendSuperFunctionDecl;
1797 if (MsgSendStretFlavor)
1798 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1799 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1800
Ted Kremenek42730c52008-01-07 19:49:32 +00001801 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001802 CurMethodDecl->getClassInterface()->getSuperClass();
1803
1804 llvm::SmallVector<Expr*, 4> InitExprs;
1805
1806 // set the receiver to self, the first argument to all methods.
1807 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001808 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001809 SourceLocation()));
1810 llvm::SmallVector<Expr*, 8> ClsExprs;
1811 QualType argType = Context->getPointerType(Context->CharTy);
1812 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1813 SuperDecl->getIdentifier()->getLength(),
1814 false, argType, SourceLocation(),
1815 SourceLocation()));
1816 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1817 &ClsExprs[0],
1818 ClsExprs.size());
1819 // To turn off a warning, type-cast to 'id'
1820 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001821 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001822 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1823 // struct objc_super
1824 QualType superType = getSuperStructType();
1825 // (struct objc_super) { <exprs from above> }
1826 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1827 &InitExprs[0], InitExprs.size(),
1828 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001829 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001830 superType, ILE, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001831 // struct objc_super *
1832 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1833 Context->getPointerType(SuperRep->getType()),
1834 SourceLocation());
1835 MsgExprs.push_back(Unop);
1836 } else {
1837 llvm::SmallVector<Expr*, 8> ClsExprs;
1838 QualType argType = Context->getPointerType(Context->CharTy);
1839 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1840 clsName->getLength(),
1841 false, argType, SourceLocation(),
1842 SourceLocation()));
1843 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1844 &ClsExprs[0],
1845 ClsExprs.size());
1846 MsgExprs.push_back(Cls);
1847 }
Steve Naroff885e2122007-11-14 23:54:14 +00001848 } else { // instance message.
1849 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001850
Ted Kremenek42730c52008-01-07 19:49:32 +00001851 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001852 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001853 if (MsgSendStretFlavor)
1854 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001855 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1856
1857 llvm::SmallVector<Expr*, 4> InitExprs;
1858
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001859 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001860 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001861 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001862
1863 llvm::SmallVector<Expr*, 8> ClsExprs;
1864 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001865 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1866 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001867 false, argType, SourceLocation(),
1868 SourceLocation()));
1869 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001870 &ClsExprs[0],
1871 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001872 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001873 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001874 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001875 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001876 // struct objc_super
1877 QualType superType = getSuperStructType();
1878 // (struct objc_super) { <exprs from above> }
1879 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1880 &InitExprs[0], InitExprs.size(),
1881 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001882 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001883 superType, ILE, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001884 // struct objc_super *
1885 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1886 Context->getPointerType(SuperRep->getType()),
1887 SourceLocation());
1888 MsgExprs.push_back(Unop);
1889 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001890 // Remove all type-casts because it may contain objc-style types; e.g.
1891 // Foo<Proto> *.
1892 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1893 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001894 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001895 MsgExprs.push_back(recExpr);
1896 }
Steve Naroff885e2122007-11-14 23:54:14 +00001897 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001898 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001899 llvm::SmallVector<Expr*, 8> SelExprs;
1900 QualType argType = Context->getPointerType(Context->CharTy);
1901 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1902 Exp->getSelector().getName().size(),
1903 false, argType, SourceLocation(),
1904 SourceLocation()));
1905 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1906 &SelExprs[0], SelExprs.size());
1907 MsgExprs.push_back(SelExp);
1908
1909 // Now push any user supplied arguments.
1910 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001911 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001912 // Make all implicit casts explicit...ICE comes in handy:-)
1913 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1914 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00001915 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1916 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001917 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001918 }
1919 // Make id<P...> cast into an 'id' cast.
1920 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001921 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001922 while ((CE = dyn_cast<CastExpr>(userExpr)))
1923 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001924 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001925 userExpr, SourceLocation());
1926 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001927 }
Steve Naroff885e2122007-11-14 23:54:14 +00001928 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001929 // We've transferred the ownership to MsgExprs. Null out the argument in
1930 // the original expression, since we will delete it below.
1931 Exp->setArg(i, 0);
1932 }
Steve Naroff0744c472007-11-04 22:37:50 +00001933 // Generate the funky cast.
1934 CastExpr *cast;
1935 llvm::SmallVector<QualType, 8> ArgTypes;
1936 QualType returnType;
1937
1938 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001939 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1940 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1941 else
Ted Kremenek42730c52008-01-07 19:49:32 +00001942 ArgTypes.push_back(Context->getObjCIdType());
1943 ArgTypes.push_back(Context->getObjCSelType());
1944 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00001945 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001946 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001947 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1948 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001949 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001950 ArgTypes.push_back(t);
1951 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001952 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1953 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00001954 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00001955 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00001956 }
1957 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001958 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001959
1960 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001961 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1962 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001963
1964 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1965 // If we don't do this cast, we get the following bizarre warning/note:
1966 // xx.m:13: warning: function called through a non-compatible type
1967 // xx.m:13: note: if this code is reached, the program will abort
1968 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1969 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001970
Steve Naroff0744c472007-11-04 22:37:50 +00001971 // Now do the "normal" pointer to function cast.
1972 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001973 &ArgTypes[0], ArgTypes.size(),
1974 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001975 castType = Context->getPointerType(castType);
1976 cast = new CastExpr(castType, cast, SourceLocation());
1977
1978 // Don't forget the parens to enforce the proper binding.
1979 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1980
1981 const FunctionType *FT = msgSendType->getAsFunctionType();
1982 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1983 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001984 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001985 if (MsgSendStretFlavor) {
1986 // We have the method which returns a struct/union. Must also generate
1987 // call to objc_msgSend_stret and hang both varieties on a conditional
1988 // expression which dictate which one to envoke depending on size of
1989 // method's return type.
1990
1991 // Create a reference to the objc_msgSend_stret() declaration.
1992 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1993 SourceLocation());
1994 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1995 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1996 SourceLocation());
1997 // Now do the "normal" pointer to function cast.
1998 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001999 &ArgTypes[0], ArgTypes.size(),
2000 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002001 castType = Context->getPointerType(castType);
2002 cast = new CastExpr(castType, cast, SourceLocation());
2003
2004 // Don't forget the parens to enforce the proper binding.
2005 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2006
2007 FT = msgSendType->getAsFunctionType();
2008 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2009 FT->getResultType(), SourceLocation());
2010
2011 // Build sizeof(returnType)
2012 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2013 returnType, Context->getSizeType(),
2014 SourceLocation(), SourceLocation());
2015 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2016 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2017 // For X86 it is more complicated and some kind of target specific routine
2018 // is needed to decide what to do.
2019 unsigned IntSize = static_cast<unsigned>(
2020 Context->getTypeSize(Context->IntTy, SourceLocation()));
2021
2022 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2023 Context->IntTy,
2024 SourceLocation());
2025 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2026 BinaryOperator::LE,
2027 Context->IntTy,
2028 SourceLocation());
2029 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2030 ConditionalOperator *CondExpr =
2031 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002032 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002033 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002034 return ReplacingStmt;
2035}
2036
2037Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2038 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002039 // Now do the actual rewrite.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002040 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroffe4e5e262007-12-19 14:32:56 +00002041 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00002042 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00002043 if (!SilenceRewriteMacroWarning)
2044 Diags.Report(Context->getFullLoc(Exp->getLocStart()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002045 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00002046 }
Steve Naroff71226032007-10-24 22:48:43 +00002047
Chris Lattner0021f452007-10-24 16:57:36 +00002048 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002049 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002050}
2051
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002052/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2053/// call to objc_getProtocol("proto-name").
2054Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2055 if (!GetProtocolFunctionDecl)
2056 SynthGetProtocolFunctionDecl();
2057 // Create a call to objc_getProtocol("ProtocolName").
2058 llvm::SmallVector<Expr*, 8> ProtoExprs;
2059 QualType argType = Context->getPointerType(Context->CharTy);
2060 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2061 strlen(Exp->getProtocol()->getName()),
2062 false, argType, SourceLocation(),
2063 SourceLocation()));
2064 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2065 &ProtoExprs[0],
2066 ProtoExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00002067 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
2068 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00002069 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00002070 if (!SilenceRewriteMacroWarning)
2071 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002072 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00002073 }
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002074 delete Exp;
2075 return ProtoExp;
2076
2077}
2078
Ted Kremenek42730c52008-01-07 19:49:32 +00002079/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002080/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002081void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002082 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002083 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2084 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002085 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002086 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002087 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002088 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002089 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002090 SourceLocation LocStart = CDecl->getLocStart();
2091 SourceLocation LocEnd = CDecl->getLocEnd();
2092
2093 const char *startBuf = SM->getCharacterData(LocStart);
2094 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002095 // If no ivars and no root or if its root, directly or indirectly,
2096 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00002097 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002098 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2099 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2100 Result.c_str(), Result.size());
2101 return;
2102 }
2103
2104 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002105 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002106 Result += "\nstruct ";
2107 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002108
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002109 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002110 const char *cursor = strchr(startBuf, '{');
2111 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002112 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002113
2114 // rewrite the original header *without* disturbing the '{'
2115 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
2116 Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002117 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002118 Result = "\n struct ";
2119 Result += RCDecl->getName();
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002120 // Note: We don't name the field decl. This simplifies the "codegen" for
2121 // accessing a superclasses instance variables (and is similar to what gcc
2122 // does internally). The unnamed struct field feature is enabled with
2123 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2124 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002125 Result += ";\n";
2126
2127 // insert the super class structure definition.
2128 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
2129 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
2130 }
2131 cursor++; // past '{'
2132
2133 // Now comment out any visibility specifiers.
2134 while (cursor < endBuf) {
2135 if (*cursor == '@') {
2136 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002137 // Skip whitespace.
2138 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2139 /*scan*/;
2140
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002141 // FIXME: presence of @public, etc. inside comment results in
2142 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002143 if (!strncmp(cursor, "public", strlen("public")) ||
2144 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002145 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00002146 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002147 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002148 // FIXME: If there are cases where '<' is used in ivar declaration part
2149 // of user code, then scan the ivar list and use needToScanForQualifiers
2150 // for type checking.
2151 else if (*cursor == '<') {
2152 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2153 Rewrite.InsertText(atLoc, "/* ", 3);
2154 cursor = strchr(cursor, '>');
2155 cursor++;
2156 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2157 Rewrite.InsertText(atLoc, " */", 3);
2158 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002159 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002160 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002161 // Don't forget to add a ';'!!
2162 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
2163 } else { // we don't have any instance variables - insert super struct.
2164 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2165 Result += " {\n struct ";
2166 Result += RCDecl->getName();
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002167 // Note: We don't name the field decl. This simplifies the "codegen" for
2168 // accessing a superclasses instance variables (and is similar to what gcc
2169 // does internally). The unnamed struct field feature is enabled with
2170 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2171 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002172 Result += ";\n};\n";
2173 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2174 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002175 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002176 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002177 if (!ObjCSynthesizedStructs.insert(CDecl))
2178 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002179}
2180
Ted Kremenek42730c52008-01-07 19:49:32 +00002181// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002182/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002183void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002184 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002185 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002186 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002187 const char *ClassName,
2188 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002189 if (MethodBegin == MethodEnd) return;
2190
Fariborz Jahanian04455192007-10-22 21:41:37 +00002191 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002192 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002193 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002194 SEL _cmd;
2195 char *method_types;
2196 void *_imp;
2197 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002198 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002199 Result += "\nstruct _objc_method {\n";
2200 Result += "\tSEL _cmd;\n";
2201 Result += "\tchar *method_types;\n";
2202 Result += "\tvoid *_imp;\n";
2203 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002204
2205 /* struct _objc_method_list {
2206 struct _objc_method_list *next_method;
2207 int method_count;
2208 struct _objc_method method_list[];
2209 }
2210 */
2211 Result += "\nstruct _objc_method_list {\n";
2212 Result += "\tstruct _objc_method_list *next_method;\n";
2213 Result += "\tint method_count;\n";
2214 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002215 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002216 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002217
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002218 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002219 Result += "\nstatic struct _objc_method_list _OBJC_";
2220 Result += prefix;
2221 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2222 Result += "_METHODS_";
2223 Result += ClassName;
2224 Result += " __attribute__ ((section (\"__OBJC, __";
2225 Result += IsInstanceMethod ? "inst" : "cls";
2226 Result += "_meth\")))= ";
2227 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002228
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002229 Result += "\t,{{(SEL)\"";
2230 Result += (*MethodBegin)->getSelector().getName().c_str();
2231 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002232 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002233 Result += "\", \"";
2234 Result += MethodTypeString;
2235 Result += "\", ";
2236 Result += MethodInternalNames[*MethodBegin];
2237 Result += "}\n";
2238 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2239 Result += "\t ,{(SEL)\"";
2240 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002241 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002242 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002243 Result += "\", \"";
2244 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002245 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002246 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002247 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002248 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002249 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002250}
2251
Ted Kremenek42730c52008-01-07 19:49:32 +00002252/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2253void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002254 int NumProtocols,
2255 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002256 const char *ClassName,
2257 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002258 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002259 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002260 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002261 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002262 // Output struct protocol_methods holder of method selector and type.
2263 if (!objc_protocol_methods &&
2264 (PDecl->getNumInstanceMethods() > 0
2265 || PDecl->getNumClassMethods() > 0)) {
2266 /* struct protocol_methods {
2267 SEL _cmd;
2268 char *method_types;
2269 }
2270 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002271 Result += "\nstruct protocol_methods {\n";
2272 Result += "\tSEL _cmd;\n";
2273 Result += "\tchar *method_types;\n";
2274 Result += "};\n";
2275
2276 /* struct _objc_protocol_method_list {
2277 int protocol_method_count;
2278 struct protocol_methods protocols[];
2279 }
2280 */
2281 Result += "\nstruct _objc_protocol_method_list {\n";
2282 Result += "\tint protocol_method_count;\n";
2283 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002284 objc_protocol_methods = true;
2285 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002286
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002287 int NumMethods = PDecl->getNumInstanceMethods();
2288 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002289 Result += "\nstatic struct _objc_protocol_method_list "
2290 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2291 Result += PDecl->getName();
2292 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2293 "{\n\t" + utostr(NumMethods) + "\n";
2294
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002295 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002296 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002297 E = PDecl->instmeth_end(); I != E; ++I) {
2298 if (I == PDecl->instmeth_begin())
2299 Result += "\t ,{{(SEL)\"";
2300 else
2301 Result += "\t ,{(SEL)\"";
2302 Result += (*I)->getSelector().getName().c_str();
2303 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002304 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002305 Result += "\", \"";
2306 Result += MethodTypeString;
2307 Result += "\"}\n";
2308 }
2309 Result += "\t }\n};\n";
2310 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002311
2312 // Output class methods declared in this protocol.
2313 NumMethods = PDecl->getNumClassMethods();
2314 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002315 Result += "\nstatic struct _objc_protocol_method_list "
2316 "_OBJC_PROTOCOL_CLASS_METHODS_";
2317 Result += PDecl->getName();
2318 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2319 "{\n\t";
2320 Result += utostr(NumMethods);
2321 Result += "\n";
2322
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002323 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002324 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002325 E = PDecl->classmeth_end(); I != E; ++I) {
2326 if (I == PDecl->classmeth_begin())
2327 Result += "\t ,{{(SEL)\"";
2328 else
2329 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002330 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002331 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002332 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002333 Result += "\", \"";
2334 Result += MethodTypeString;
2335 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002336 }
2337 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002338 }
2339 // Output:
2340 /* struct _objc_protocol {
2341 // Objective-C 1.0 extensions
2342 struct _objc_protocol_extension *isa;
2343 char *protocol_name;
2344 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002345 struct _objc_protocol_method_list *instance_methods;
2346 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002347 };
2348 */
2349 static bool objc_protocol = false;
2350 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002351 Result += "\nstruct _objc_protocol {\n";
2352 Result += "\tstruct _objc_protocol_extension *isa;\n";
2353 Result += "\tchar *protocol_name;\n";
2354 Result += "\tstruct _objc_protocol **protocol_list;\n";
2355 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2356 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2357 Result += "};\n";
2358
2359 /* struct _objc_protocol_list {
2360 struct _objc_protocol_list *next;
2361 int protocol_count;
2362 struct _objc_protocol *class_protocols[];
2363 }
2364 */
2365 Result += "\nstruct _objc_protocol_list {\n";
2366 Result += "\tstruct _objc_protocol_list *next;\n";
2367 Result += "\tint protocol_count;\n";
2368 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2369 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002370 objc_protocol = true;
2371 }
2372
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002373 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2374 Result += PDecl->getName();
2375 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2376 "{\n\t0, \"";
2377 Result += PDecl->getName();
2378 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002379 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002380 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2381 Result += PDecl->getName();
2382 Result += ", ";
2383 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002384 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002385 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002386 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002387 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2388 Result += PDecl->getName();
2389 Result += "\n";
2390 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002391 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002392 Result += "0\n";
2393 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002394 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002395 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002396 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2397 Result += prefix;
2398 Result += "_PROTOCOLS_";
2399 Result += ClassName;
2400 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2401 "{\n\t0, ";
2402 Result += utostr(NumProtocols);
2403 Result += "\n";
2404
2405 Result += "\t,{&_OBJC_PROTOCOL_";
2406 Result += Protocols[0]->getName();
2407 Result += " \n";
2408
2409 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002410 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002411 Result += "\t ,&_OBJC_PROTOCOL_";
2412 Result += PDecl->getName();
2413 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002414 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002415 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002416 }
2417}
2418
Ted Kremenek42730c52008-01-07 19:49:32 +00002419/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002420/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002421void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002422 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002423 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002424 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002425 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002426 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2427 CDecl = CDecl->getNextClassCategory())
2428 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2429 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002430
Chris Lattnera661a4d2007-12-23 01:40:15 +00002431 std::string FullCategoryName = ClassDecl->getName();
2432 FullCategoryName += '_';
2433 FullCategoryName += IDecl->getName();
2434
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002435 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002436 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002437 true, "CATEGORY_", FullCategoryName.c_str(),
2438 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002439
2440 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002441 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002442 false, "CATEGORY_", FullCategoryName.c_str(),
2443 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002444
2445 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002446 // Null CDecl is case of a category implementation with no category interface
2447 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002448 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002449 CDecl->getNumReferencedProtocols(),
2450 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002451 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002452
2453 /* struct _objc_category {
2454 char *category_name;
2455 char *class_name;
2456 struct _objc_method_list *instance_methods;
2457 struct _objc_method_list *class_methods;
2458 struct _objc_protocol_list *protocols;
2459 // Objective-C 1.0 extensions
2460 uint32_t size; // sizeof (struct _objc_category)
2461 struct _objc_property_list *instance_properties; // category's own
2462 // @property decl.
2463 };
2464 */
2465
2466 static bool objc_category = false;
2467 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002468 Result += "\nstruct _objc_category {\n";
2469 Result += "\tchar *category_name;\n";
2470 Result += "\tchar *class_name;\n";
2471 Result += "\tstruct _objc_method_list *instance_methods;\n";
2472 Result += "\tstruct _objc_method_list *class_methods;\n";
2473 Result += "\tstruct _objc_protocol_list *protocols;\n";
2474 Result += "\tunsigned int size;\n";
2475 Result += "\tstruct _objc_property_list *instance_properties;\n";
2476 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002477 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002478 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002479 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2480 Result += FullCategoryName;
2481 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2482 Result += IDecl->getName();
2483 Result += "\"\n\t, \"";
2484 Result += ClassDecl->getName();
2485 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002486
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002487 if (IDecl->getNumInstanceMethods() > 0) {
2488 Result += "\t, (struct _objc_method_list *)"
2489 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2490 Result += FullCategoryName;
2491 Result += "\n";
2492 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002493 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002494 Result += "\t, 0\n";
2495 if (IDecl->getNumClassMethods() > 0) {
2496 Result += "\t, (struct _objc_method_list *)"
2497 "&_OBJC_CATEGORY_CLASS_METHODS_";
2498 Result += FullCategoryName;
2499 Result += "\n";
2500 }
2501 else
2502 Result += "\t, 0\n";
2503
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002504 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002505 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2506 Result += FullCategoryName;
2507 Result += "\n";
2508 }
2509 else
2510 Result += "\t, 0\n";
2511 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002512}
2513
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002514/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2515/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002516void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2517 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002518 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002519 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002520 Result += IDecl->getName();
2521 Result += ", ";
2522 Result += ivar->getName();
2523 Result += ")";
2524}
2525
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002526//===----------------------------------------------------------------------===//
2527// Meta Data Emission
2528//===----------------------------------------------------------------------===//
2529
Ted Kremenek42730c52008-01-07 19:49:32 +00002530void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002531 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002532 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002533
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002534 // Explictly declared @interface's are already synthesized.
2535 if (CDecl->ImplicitInterfaceDecl()) {
2536 // FIXME: Implementation of a class with no @interface (legacy) doese not
2537 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002538 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002539 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002540
Chris Lattnerc7b06752007-12-12 07:56:42 +00002541 // Build _objc_ivar_list metadata for classes ivars if needed
2542 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2543 ? IDecl->getImplDeclNumIvars()
2544 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002545 if (NumIvars > 0) {
2546 static bool objc_ivar = false;
2547 if (!objc_ivar) {
2548 /* struct _objc_ivar {
2549 char *ivar_name;
2550 char *ivar_type;
2551 int ivar_offset;
2552 };
2553 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002554 Result += "\nstruct _objc_ivar {\n";
2555 Result += "\tchar *ivar_name;\n";
2556 Result += "\tchar *ivar_type;\n";
2557 Result += "\tint ivar_offset;\n";
2558 Result += "};\n";
2559
2560 /* struct _objc_ivar_list {
2561 int ivar_count;
2562 struct _objc_ivar ivar_list[];
2563 };
2564 */
2565 Result += "\nstruct _objc_ivar_list {\n";
2566 Result += "\tint ivar_count;\n";
2567 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002568 objc_ivar = true;
2569 }
2570
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002571 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2572 Result += IDecl->getName();
2573 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2574 "{\n\t";
2575 Result += utostr(NumIvars);
2576 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002577
Ted Kremenek42730c52008-01-07 19:49:32 +00002578 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002579 if (IDecl->getImplDeclNumIvars() > 0) {
2580 IVI = IDecl->ivar_begin();
2581 IVE = IDecl->ivar_end();
2582 } else {
2583 IVI = CDecl->ivar_begin();
2584 IVE = CDecl->ivar_end();
2585 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002586 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002587 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002588 Result += "\", \"";
2589 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002590 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2591 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002592 Result += StrEncoding;
2593 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002594 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002595 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002596 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002597 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002598 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002599 Result += "\", \"";
2600 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002601 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2602 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002603 Result += StrEncoding;
2604 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002605 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002606 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002607 }
2608
2609 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002610 }
2611
2612 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002613 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002614 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002615
2616 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002617 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002618 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002619
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002620 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002621 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002622 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002623 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002624
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002625
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002626 // Declaration of class/meta-class metadata
2627 /* struct _objc_class {
2628 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002629 const char *super_class_name;
2630 char *name;
2631 long version;
2632 long info;
2633 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002634 struct _objc_ivar_list *ivars;
2635 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002636 struct objc_cache *cache;
2637 struct objc_protocol_list *protocols;
2638 const char *ivar_layout;
2639 struct _objc_class_ext *ext;
2640 };
2641 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002642 static bool objc_class = false;
2643 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002644 Result += "\nstruct _objc_class {\n";
2645 Result += "\tstruct _objc_class *isa;\n";
2646 Result += "\tconst char *super_class_name;\n";
2647 Result += "\tchar *name;\n";
2648 Result += "\tlong version;\n";
2649 Result += "\tlong info;\n";
2650 Result += "\tlong instance_size;\n";
2651 Result += "\tstruct _objc_ivar_list *ivars;\n";
2652 Result += "\tstruct _objc_method_list *methods;\n";
2653 Result += "\tstruct objc_cache *cache;\n";
2654 Result += "\tstruct _objc_protocol_list *protocols;\n";
2655 Result += "\tconst char *ivar_layout;\n";
2656 Result += "\tstruct _objc_class_ext *ext;\n";
2657 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002658 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002659 }
2660
2661 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002662 ObjCInterfaceDecl *RootClass = 0;
2663 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002664 while (SuperClass) {
2665 RootClass = SuperClass;
2666 SuperClass = SuperClass->getSuperClass();
2667 }
2668 SuperClass = CDecl->getSuperClass();
2669
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002670 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2671 Result += CDecl->getName();
2672 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2673 "{\n\t(struct _objc_class *)\"";
2674 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2675 Result += "\"";
2676
2677 if (SuperClass) {
2678 Result += ", \"";
2679 Result += SuperClass->getName();
2680 Result += "\", \"";
2681 Result += CDecl->getName();
2682 Result += "\"";
2683 }
2684 else {
2685 Result += ", 0, \"";
2686 Result += CDecl->getName();
2687 Result += "\"";
2688 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002689 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002690 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002691 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002692 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002693 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002694 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002695 Result += "\n";
2696 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002697 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002698 Result += ", 0\n";
2699 if (CDecl->getNumIntfRefProtocols() > 0) {
2700 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2701 Result += CDecl->getName();
2702 Result += ",0,0\n";
2703 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002704 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002705 Result += "\t,0,0,0,0\n";
2706 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002707
2708 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002709 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2710 Result += CDecl->getName();
2711 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2712 "{\n\t&_OBJC_METACLASS_";
2713 Result += CDecl->getName();
2714 if (SuperClass) {
2715 Result += ", \"";
2716 Result += SuperClass->getName();
2717 Result += "\", \"";
2718 Result += CDecl->getName();
2719 Result += "\"";
2720 }
2721 else {
2722 Result += ", 0, \"";
2723 Result += CDecl->getName();
2724 Result += "\"";
2725 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002726 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002727 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002728 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002729 Result += ",0";
2730 else {
2731 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002732 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002733 Result += CDecl->getName();
2734 Result += ")";
2735 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002736 if (NumIvars > 0) {
2737 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2738 Result += CDecl->getName();
2739 Result += "\n\t";
2740 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002741 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002742 Result += ",0";
2743 if (IDecl->getNumInstanceMethods() > 0) {
2744 Result += ", &_OBJC_INSTANCE_METHODS_";
2745 Result += CDecl->getName();
2746 Result += ", 0\n\t";
2747 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002748 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002749 Result += ",0,0";
2750 if (CDecl->getNumIntfRefProtocols() > 0) {
2751 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2752 Result += CDecl->getName();
2753 Result += ", 0,0\n";
2754 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002755 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002756 Result += ",0,0,0\n";
2757 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002758}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002759
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002760/// RewriteImplementations - This routine rewrites all method implementations
2761/// and emits meta-data.
2762
2763void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002764 int ClsDefCount = ClassImplementation.size();
2765 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002766
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002767 if (ClsDefCount == 0 && CatDefCount == 0)
2768 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002769 // Rewrite implemented methods
2770 for (int i = 0; i < ClsDefCount; i++)
2771 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002772
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002773 for (int i = 0; i < CatDefCount; i++)
2774 RewriteImplementationDecl(CategoryImplementation[i]);
2775
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002776 // This is needed for use of offsetof
2777 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002778
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002779 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002780 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002781 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002782
2783 // For each implemented category, write out all its meta data.
2784 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002785 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002786
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002787 // Write objc_symtab metadata
2788 /*
2789 struct _objc_symtab
2790 {
2791 long sel_ref_cnt;
2792 SEL *refs;
2793 short cls_def_cnt;
2794 short cat_def_cnt;
2795 void *defs[cls_def_cnt + cat_def_cnt];
2796 };
2797 */
2798
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002799 Result += "\nstruct _objc_symtab {\n";
2800 Result += "\tlong sel_ref_cnt;\n";
2801 Result += "\tSEL *refs;\n";
2802 Result += "\tshort cls_def_cnt;\n";
2803 Result += "\tshort cat_def_cnt;\n";
2804 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2805 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002806
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002807 Result += "static struct _objc_symtab "
2808 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2809 Result += "\t0, 0, " + utostr(ClsDefCount)
2810 + ", " + utostr(CatDefCount) + "\n";
2811 for (int i = 0; i < ClsDefCount; i++) {
2812 Result += "\t,&_OBJC_CLASS_";
2813 Result += ClassImplementation[i]->getName();
2814 Result += "\n";
2815 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002816
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002817 for (int i = 0; i < CatDefCount; i++) {
2818 Result += "\t,&_OBJC_CATEGORY_";
2819 Result += CategoryImplementation[i]->getClassInterface()->getName();
2820 Result += "_";
2821 Result += CategoryImplementation[i]->getName();
2822 Result += "\n";
2823 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002824
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002825 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002826
2827 // Write objc_module metadata
2828
2829 /*
2830 struct _objc_module {
2831 long version;
2832 long size;
2833 const char *name;
2834 struct _objc_symtab *symtab;
2835 }
2836 */
2837
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002838 Result += "\nstruct _objc_module {\n";
2839 Result += "\tlong version;\n";
2840 Result += "\tlong size;\n";
2841 Result += "\tconst char *name;\n";
2842 Result += "\tstruct _objc_symtab *symtab;\n";
2843 Result += "};\n\n";
2844 Result += "static struct _objc_module "
2845 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002846 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2847 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002848 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002849
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002850}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002851