blob: 4c84b8adcb53c330399d87d9435ce3492a19d6bc [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);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000206 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S);
Steve Naroff71226032007-10-24 22:48:43 +0000207 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
208 Expr **args, unsigned nargs);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000209 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000210 Stmt *RewriteBreakStmt(BreakStmt *S);
211 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000212 void SynthCountByEnumWithState(std::string &buf);
213
Steve Naroff02a82aa2007-10-30 23:14:51 +0000214 void SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +0000215 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000216 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +0000217 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +0000218 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +0000219 void SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +0000220 void SynthGetMetaClassFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000221 void SynthCFStringFunctionDecl();
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +0000222 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000223 void SynthGetProtocolFunctionDecl();
Steve Naroffabb96362007-11-08 14:30:50 +0000224
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000225 // Metadata emission.
Ted Kremenek42730c52008-01-07 19:49:32 +0000226 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000227 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000228
Ted Kremenek42730c52008-01-07 19:49:32 +0000229 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000230 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000231
Ted Kremenek42730c52008-01-07 19:49:32 +0000232 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
233 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000234 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +0000235 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000236 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +0000237 const char *ClassName,
238 std::string &Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000239
Ted Kremenek42730c52008-01-07 19:49:32 +0000240 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +0000241 int NumProtocols,
242 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +0000243 const char *ClassName,
244 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000245 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000246 std::string &Result);
Ted Kremenek42730c52008-01-07 19:49:32 +0000247 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
248 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000249 std::string &Result);
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000250 void RewriteImplementations(std::string &Result);
Chris Lattnerb429ae42007-10-11 00:43:27 +0000251 };
252}
253
Fariborz Jahanian8d2080c2008-01-18 01:15:54 +0000254static bool IsHeaderFile(const std::string &Filename) {
255 std::string::size_type DotPos = Filename.rfind('.');
256
257 if (DotPos == std::string::npos) {
258 // no file extension
259 return false;
260 }
261
262 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
263 // C header: .h
264 // C++ header: .hh or .H;
265 return Ext == "h" || Ext == "hh" || Ext == "H";
266}
267
268ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
269 Diagnostic &Diags) {
270 return new RewriteTest(IsHeaderFile(InFile), Diags);
Chris Lattner258f26c2007-11-30 22:25:36 +0000271}
Chris Lattnerb429ae42007-10-11 00:43:27 +0000272
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000273//===----------------------------------------------------------------------===//
274// Top Level Driver Code
275//===----------------------------------------------------------------------===//
276
Chris Lattner569faa62007-10-11 18:38:32 +0000277void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner74db1682007-10-16 21:07:07 +0000278 // Two cases: either the decl could be in the main file, or it could be in a
279 // #included file. If the former, rewrite it now. If the later, check to see
280 // if we rewrote the #include/#import.
281 SourceLocation Loc = D->getLocation();
282 Loc = SM->getLogicalLoc(Loc);
283
284 // If this is for a builtin, ignore it.
285 if (Loc.isInvalid()) return;
286
Steve Naroffe9780582007-10-23 23:50:29 +0000287 // Look for built-in declarations that we need to refer during the rewrite.
288 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff02a82aa2007-10-30 23:14:51 +0000289 RewriteFunctionDecl(FD);
Steve Naroff0add5d22007-11-03 11:27:19 +0000290 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
291 // declared in <Foundation/NSString.h>
292 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
293 ConstantStringClassReference = FVD;
294 return;
295 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000296 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff3774dd92007-10-26 20:53:56 +0000297 RewriteInterfaceDecl(MD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000298 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff667f1682007-10-30 13:30:57 +0000299 RewriteCategoryDecl(CD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000300 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000301 RewriteProtocolDecl(PD);
Ted Kremenek42730c52008-01-07 19:49:32 +0000302 } else if (ObjCForwardProtocolDecl *FP =
303 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000304 RewriteForwardProtocolDecl(FP);
Steve Naroffe9780582007-10-23 23:50:29 +0000305 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000306 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner74db1682007-10-16 21:07:07 +0000307 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
308 return HandleDeclInMainFile(D);
Chris Lattner74db1682007-10-16 21:07:07 +0000309}
310
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000311/// HandleDeclInMainFile - This is called for each top-level decl defined in the
312/// main file of the input.
313void RewriteTest::HandleDeclInMainFile(Decl *D) {
314 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
315 if (Stmt *Body = FD->getBody())
Steve Naroff334fbc22007-11-09 15:20:18 +0000316 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000317
Ted Kremenek42730c52008-01-07 19:49:32 +0000318 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +0000319 if (Stmt *Body = MD->getBody()) {
320 //Body->dump();
321 CurMethodDecl = MD;
Steve Naroff18c83382007-11-13 23:01:27 +0000322 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff764c1ae2007-11-15 10:28:18 +0000323 CurMethodDecl = 0;
324 }
Steve Naroff18c83382007-11-13 23:01:27 +0000325 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000326 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000327 ClassImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000328 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000329 CategoryImplementation.push_back(CI);
Ted Kremenek42730c52008-01-07 19:49:32 +0000330 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000331 RewriteForwardClassDecl(CD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000332 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000333 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff334fbc22007-11-09 15:20:18 +0000334 if (VD->getInit())
335 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
336 }
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000337 // Nothing yet.
338}
339
340RewriteTest::~RewriteTest() {
341 // Get the top-level buffer that this corresponds to.
Chris Lattner257236c2007-11-08 04:27:23 +0000342
343 // Rewrite tabs if we care.
344 //RewriteTabs();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000345
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000346 RewriteInclude();
347
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000348 // Rewrite Objective-c meta data*
349 std::string ResultStr;
Fariborz Jahanian8c664912007-11-13 19:21:13 +0000350 RewriteImplementations(ResultStr);
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000351
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000352 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
353 // we are done.
354 if (const RewriteBuffer *RewriteBuf =
355 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroff0add5d22007-11-03 11:27:19 +0000356 //printf("Changed:\n");
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000357 std::string S(RewriteBuf->begin(), RewriteBuf->end());
358 printf("%s\n", S.c_str());
359 } else {
360 printf("No changes\n");
361 }
Fariborz Jahanian70ef5462007-11-07 18:40:28 +0000362 // Emit metadata.
363 printf("%s", ResultStr.c_str());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +0000364}
365
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000366//===----------------------------------------------------------------------===//
367// Syntactic (non-AST) Rewriting Code
368//===----------------------------------------------------------------------===//
369
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000370void RewriteTest::RewriteInclude() {
371 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
372 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
373 const char *MainBufStart = MainBuf.first;
374 const char *MainBufEnd = MainBuf.second;
375 size_t ImportLen = strlen("import");
376 size_t IncludeLen = strlen("include");
377
Fariborz Jahanianc81ed742008-01-19 01:03:17 +0000378 // Loop over the whole file, looking for includes.
Fariborz Jahaniana42227a2008-01-19 00:30:35 +0000379 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
380 if (*BufPtr == '#') {
381 if (++BufPtr == MainBufEnd)
382 return;
383 while (*BufPtr == ' ' || *BufPtr == '\t')
384 if (++BufPtr == MainBufEnd)
385 return;
386 if (!strncmp(BufPtr, "import", ImportLen)) {
387 // replace import with include
388 SourceLocation ImportLoc =
389 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
390 Rewrite.ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
391 BufPtr += ImportLen;
392 }
393 }
394 }
Chris Lattner74db1682007-10-16 21:07:07 +0000395}
396
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000397void RewriteTest::RewriteTabs() {
398 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
399 const char *MainBufStart = MainBuf.first;
400 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian640a01f2007-10-18 19:23:00 +0000401
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000402 // Loop over the whole file, looking for tabs.
403 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
404 if (*BufPtr != '\t')
405 continue;
406
407 // Okay, we found a tab. This tab will turn into at least one character,
408 // but it depends on which 'virtual column' it is in. Compute that now.
409 unsigned VCol = 0;
410 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
411 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
412 ++VCol;
413
414 // Okay, now that we know the virtual column, we know how many spaces to
415 // insert. We assume 8-character tab-stops.
416 unsigned Spaces = 8-(VCol & 7);
417
418 // Get the location of the tab.
419 SourceLocation TabLoc =
420 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
421
422 // Rewrite the single tab character into a sequence of spaces.
423 Rewrite.ReplaceText(TabLoc, 1, " ", Spaces);
424 }
Chris Lattner569faa62007-10-11 18:38:32 +0000425}
426
427
Ted Kremenek42730c52008-01-07 19:49:32 +0000428void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000429 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremenek42730c52008-01-07 19:49:32 +0000430 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000431
432 // Get the start location and compute the semi location.
433 SourceLocation startLoc = ClassDecl->getLocation();
434 const char *startBuf = SM->getCharacterData(startLoc);
435 const char *semiPtr = strchr(startBuf, ';');
436
437 // Translate to typedef's that forward reference structs with the same name
438 // as the class. As a convenience, we include the original declaration
439 // as a comment.
440 std::string typedefString;
441 typedefString += "// ";
Steve Naroff71226032007-10-24 22:48:43 +0000442 typedefString.append(startBuf, semiPtr-startBuf+1);
443 typedefString += "\n";
444 for (int i = 0; i < numDecls; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000445 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff2aeae312007-11-09 12:50:28 +0000446 typedefString += "#ifndef _REWRITER_typedef_";
447 typedefString += ForwardDecl->getName();
448 typedefString += "\n";
449 typedefString += "#define _REWRITER_typedef_";
450 typedefString += ForwardDecl->getName();
451 typedefString += "\n";
Steve Naroff4242b972007-11-05 14:36:37 +0000452 typedefString += "typedef struct objc_object ";
Steve Naroff71226032007-10-24 22:48:43 +0000453 typedefString += ForwardDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000454 typedefString += ";\n#endif\n";
Steve Naroff71226032007-10-24 22:48:43 +0000455 }
456
457 // Replace the @class with typedefs corresponding to the classes.
458 Rewrite.ReplaceText(startLoc, semiPtr-startBuf+1,
459 typedefString.c_str(), typedefString.size());
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000460}
461
Ted Kremenek42730c52008-01-07 19:49:32 +0000462void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff2ce399a2007-12-14 23:37:57 +0000463 SourceLocation LocStart = Method->getLocStart();
464 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff667f1682007-10-30 13:30:57 +0000465
Steve Naroff2ce399a2007-12-14 23:37:57 +0000466 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000467 Rewrite.InsertText(LocStart, "/* ", 3);
468 Rewrite.ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff2ce399a2007-12-14 23:37:57 +0000469 } else {
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000470 Rewrite.InsertText(LocStart, "// ", 3);
Steve Naroff667f1682007-10-30 13:30:57 +0000471 }
472}
473
Ted Kremenek42730c52008-01-07 19:49:32 +0000474void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000475{
476 for (int i = 0; i < nProperties; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000477 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000478 SourceLocation Loc = Property->getLocation();
479
480 Rewrite.ReplaceText(Loc, 0, "// ", 3);
481
482 // FIXME: handle properties that are declared across multiple lines.
483 }
484}
485
Ted Kremenek42730c52008-01-07 19:49:32 +0000486void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff667f1682007-10-30 13:30:57 +0000487 SourceLocation LocStart = CatDecl->getLocStart();
488
489 // FIXME: handle category headers that are declared across multiple lines.
490 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
491
Ted Kremenek42730c52008-01-07 19:49:32 +0000492 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000493 E = CatDecl->instmeth_end(); I != E; ++I)
494 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000495 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000496 E = CatDecl->classmeth_end(); I != E; ++I)
497 RewriteMethodDeclaration(*I);
498
Steve Naroff667f1682007-10-30 13:30:57 +0000499 // Lastly, comment out the @end.
500 Rewrite.ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
501}
502
Ted Kremenek42730c52008-01-07 19:49:32 +0000503void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000504 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000505
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000506 SourceLocation LocStart = PDecl->getLocStart();
507
508 // FIXME: handle protocol headers that are declared across multiple lines.
509 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
510
Ted Kremenek42730c52008-01-07 19:49:32 +0000511 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000512 E = PDecl->instmeth_end(); I != E; ++I)
513 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000514 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000515 E = PDecl->classmeth_end(); I != E; ++I)
516 RewriteMethodDeclaration(*I);
517
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000518 // Lastly, comment out the @end.
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000519 SourceLocation LocEnd = PDecl->getAtEndLoc();
520 Rewrite.ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff268fa592007-11-14 15:03:57 +0000521
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000522 // Must comment out @optional/@required
523 const char *startBuf = SM->getCharacterData(LocStart);
524 const char *endBuf = SM->getCharacterData(LocEnd);
525 for (const char *p = startBuf; p < endBuf; p++) {
526 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
527 std::string CommentedOptional = "/* @optional */";
Steve Naroff268fa592007-11-14 15:03:57 +0000528 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000529 Rewrite.ReplaceText(OptionalLoc, strlen("@optional"),
530 CommentedOptional.c_str(), CommentedOptional.size());
531
532 }
533 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
534 std::string CommentedRequired = "/* @required */";
Steve Naroff268fa592007-11-14 15:03:57 +0000535 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Fariborz Jahanian3960e9c2007-11-14 01:37:46 +0000536 Rewrite.ReplaceText(OptionalLoc, strlen("@required"),
537 CommentedRequired.c_str(), CommentedRequired.size());
538
539 }
540 }
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000541}
542
Ted Kremenek42730c52008-01-07 19:49:32 +0000543void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000544 SourceLocation LocStart = PDecl->getLocation();
Steve Naroff0540f3f2007-11-14 03:37:28 +0000545 if (LocStart.isInvalid())
546 assert(false && "Invalid SourceLocation");
Fariborz Jahanian016a1882007-11-14 00:42:16 +0000547 // FIXME: handle forward protocol that are declared across multiple lines.
548 Rewrite.ReplaceText(LocStart, 0, "// ", 3);
549}
550
Ted Kremenek42730c52008-01-07 19:49:32 +0000551void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000552 std::string &ResultStr) {
553 ResultStr += "\nstatic ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000554 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000555 ResultStr += "id";
556 else
557 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000558 ResultStr += " ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000559
560 // Unique method name
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000561 std::string NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000562
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000563 if (OMD->isInstance())
564 NameStr += "_I_";
565 else
566 NameStr += "_C_";
567
568 NameStr += OMD->getClassInterface()->getName();
569 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000570
571 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremenek42730c52008-01-07 19:49:32 +0000572 if (ObjCCategoryImplDecl *CID =
573 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000574 NameStr += CID->getName();
575 NameStr += "_";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000576 }
577 // Append selector names, replacing ':' with '_'
578 const char *selName = OMD->getSelector().getName().c_str();
579 if (!strchr(selName, ':'))
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000580 NameStr += OMD->getSelector().getName();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000581 else {
582 std::string selString = OMD->getSelector().getName();
583 int len = selString.size();
584 for (int i = 0; i < len; i++)
585 if (selString[i] == ':')
586 selString[i] = '_';
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000587 NameStr += selString;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000588 }
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +0000589 // Remember this name for metadata emission
590 MethodInternalNames[OMD] = NameStr;
591 ResultStr += NameStr;
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000592
593 // Rewrite arguments
594 ResultStr += "(";
595
596 // invisible arguments
597 if (OMD->isInstance()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000598 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000599 selfTy = Context->getPointerType(selfTy);
Ted Kremenek42730c52008-01-07 19:49:32 +0000600 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000601 ResultStr += "struct ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000602 ResultStr += selfTy.getAsString();
603 }
604 else
Ted Kremenek42730c52008-01-07 19:49:32 +0000605 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000606
607 ResultStr += " self, ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000608 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000609 ResultStr += " _cmd";
610
611 // Method arguments.
612 for (int i = 0; i < OMD->getNumParams(); i++) {
613 ParmVarDecl *PDecl = OMD->getParamDecl(i);
614 ResultStr += ", ";
Ted Kremenek42730c52008-01-07 19:49:32 +0000615 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +0000616 ResultStr += "id";
617 else
618 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000619 ResultStr += " ";
620 ResultStr += PDecl->getName();
621 }
Fariborz Jahanian2fab94e2008-01-21 20:14:23 +0000622 if (OMD->isVariadic())
623 ResultStr += ", ...";
Fariborz Jahanian7202d982008-01-10 01:39:52 +0000624 ResultStr += ") ";
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000625
626}
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000627void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000628 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
629 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000630
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000631 if (IMD)
632 Rewrite.InsertText(IMD->getLocStart(), "// ", 3);
633 else
634 Rewrite.InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000635
Ted Kremenek42730c52008-01-07 19:49:32 +0000636 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000637 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
638 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000639 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000640 ObjCMethodDecl *OMD = *I;
641 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000642 SourceLocation LocStart = OMD->getLocStart();
643 SourceLocation LocEnd = OMD->getBody()->getLocStart();
644
645 const char *startBuf = SM->getCharacterData(LocStart);
646 const char *endBuf = SM->getCharacterData(LocEnd);
647 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
648 ResultStr.c_str(), ResultStr.size());
649 }
650
Ted Kremenek42730c52008-01-07 19:49:32 +0000651 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerdea5bec2007-12-12 07:46:12 +0000652 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
653 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000654 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000655 ObjCMethodDecl *OMD = *I;
656 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000657 SourceLocation LocStart = OMD->getLocStart();
658 SourceLocation LocEnd = OMD->getBody()->getLocStart();
659
660 const char *startBuf = SM->getCharacterData(LocStart);
661 const char *endBuf = SM->getCharacterData(LocEnd);
662 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
663 ResultStr.c_str(), ResultStr.size());
664 }
Fariborz Jahanian0136e372007-11-13 20:04:28 +0000665 if (IMD)
666 Rewrite.InsertText(IMD->getLocEnd(), "// ", 3);
667 else
668 Rewrite.InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian5ea3a762007-11-13 18:44:14 +0000669}
670
Ted Kremenek42730c52008-01-07 19:49:32 +0000671void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffef20ed32007-10-30 02:23:23 +0000672 std::string ResultStr;
Ted Kremenek42730c52008-01-07 19:49:32 +0000673 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff77d081b2007-11-01 03:35:41 +0000674 // we haven't seen a forward decl - generate a typedef.
Steve Naroff2adead72007-11-14 23:02:56 +0000675 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff2aeae312007-11-09 12:50:28 +0000676 ResultStr += ClassDecl->getName();
677 ResultStr += "\n";
678 ResultStr += "#define _REWRITER_typedef_";
679 ResultStr += ClassDecl->getName();
680 ResultStr += "\n";
Fariborz Jahaniana845eec2007-12-03 22:25:42 +0000681 ResultStr += "typedef struct ";
682 ResultStr += ClassDecl->getName();
683 ResultStr += " ";
Steve Naroff77d081b2007-11-01 03:35:41 +0000684 ResultStr += ClassDecl->getName();
Steve Naroff2aeae312007-11-09 12:50:28 +0000685 ResultStr += ";\n#endif\n";
Steve Naroff77d081b2007-11-01 03:35:41 +0000686
687 // Mark this typedef as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +0000688 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff77d081b2007-11-01 03:35:41 +0000689 }
Ted Kremenek42730c52008-01-07 19:49:32 +0000690 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Naroffef20ed32007-10-30 02:23:23 +0000691
Fariborz Jahanianeca7fad2007-11-07 00:09:37 +0000692 RewriteProperties(ClassDecl->getNumPropertyDecl(),
693 ClassDecl->getPropertyDecl());
Ted Kremenek42730c52008-01-07 19:49:32 +0000694 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000695 E = ClassDecl->instmeth_end(); I != E; ++I)
696 RewriteMethodDeclaration(*I);
Ted Kremenek42730c52008-01-07 19:49:32 +0000697 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff2ce399a2007-12-14 23:37:57 +0000698 E = ClassDecl->classmeth_end(); I != E; ++I)
699 RewriteMethodDeclaration(*I);
700
Steve Naroff1ccf4632007-10-30 03:43:13 +0000701 // Lastly, comment out the @end.
702 Rewrite.ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff3774dd92007-10-26 20:53:56 +0000703}
704
Steve Naroff6b759ce2007-11-15 02:58:25 +0000705Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000706 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff6b759ce2007-11-15 02:58:25 +0000707 if (IV->isFreeIvar()) {
708 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
709 IV->getLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +0000710 if (Rewrite.ReplaceStmt(IV, Replacement)) {
711 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +0000712 SourceRange Range = IV->getSourceRange();
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000713 if (!SilenceRewriteMacroWarning)
Steve Naroff1c46cf12008-01-28 21:34:52 +0000714 Diags.Report(Context->getFullLoc(IV->getLocation()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000715 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000716 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000717 delete IV;
718 return Replacement;
Steve Naroff292b7b92007-11-15 11:33:00 +0000719 } else {
Fariborz Jahanianc8849882008-01-23 20:34:40 +0000720#if 0
721 /// This code is not right. It seems unnecessary. It breaks use of
722 /// ivar reference used as 'receiver' of an expression; as in:
723 /// [newInv->_container addObject:0];
Steve Naroff292b7b92007-11-15 11:33:00 +0000724 if (CurMethodDecl) {
725 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +0000726 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff292b7b92007-11-15 11:33:00 +0000727 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
728 IdentifierInfo *II = intT->getDecl()->getIdentifier();
729 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
730 II, 0);
731 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
732
733 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
734 // Don't forget the parens to enforce the proper binding.
735 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000736 if (Rewrite.ReplaceStmt(IV->getBase(), PE)) {
737 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +0000738 SourceRange Range = IV->getBase()->getSourceRange();
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000739 if (!SilenceRewriteMacroWarning)
Steve Naroff1c46cf12008-01-28 21:34:52 +0000740 Diags.Report(Context->getFullLoc(IV->getBase()->getLocStart()),
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000741 RewriteFailedDiag, 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +0000742 }
Steve Naroff292b7b92007-11-15 11:33:00 +0000743 delete IV->getBase();
744 return PE;
745 }
746 }
747 }
Fariborz Jahanianc8849882008-01-23 20:34:40 +0000748#endif
Steve Naroff6b759ce2007-11-15 02:58:25 +0000749 return IV;
Steve Naroff292b7b92007-11-15 11:33:00 +0000750 }
Steve Naroff6b759ce2007-11-15 02:58:25 +0000751}
752
Chris Lattnerfce2c5a2007-10-24 17:06:59 +0000753//===----------------------------------------------------------------------===//
754// Function Body / Expression rewriting
755//===----------------------------------------------------------------------===//
756
Steve Naroff334fbc22007-11-09 15:20:18 +0000757Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000758 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
759 isa<DoStmt>(S) || isa<ForStmt>(S))
760 Stmts.push_back(S);
761 else if (isa<ObjCForCollectionStmt>(S)) {
762 Stmts.push_back(S);
763 ObjCBcLabelNo.push_back(++BcLabelCount);
764 }
765
Chris Lattner6fe8b272007-10-16 22:36:42 +0000766 // Otherwise, just rewrite all children.
767 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
768 CI != E; ++CI)
Steve Naroffe9f69842007-11-07 04:08:17 +0000769 if (*CI) {
Steve Naroff334fbc22007-11-09 15:20:18 +0000770 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroffe9f69842007-11-07 04:08:17 +0000771 if (newStmt)
772 *CI = newStmt;
773 }
Steve Naroffe9780582007-10-23 23:50:29 +0000774
775 // Handle specific things.
776 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
777 return RewriteAtEncode(AtEncode);
Steve Naroff6b759ce2007-11-15 02:58:25 +0000778
779 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
780 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroff296b74f2007-11-05 14:50:49 +0000781
782 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
783 return RewriteAtSelector(AtSelector);
Steve Naroff53b6f4c2008-01-30 19:17:43 +0000784
Steve Naroff0add5d22007-11-03 11:27:19 +0000785 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
786 return RewriteObjCStringLiteral(AtString);
Steve Naroffe9780582007-10-23 23:50:29 +0000787
Steve Naroff71226032007-10-24 22:48:43 +0000788 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
789 // Before we rewrite it, put the original message expression in a comment.
790 SourceLocation startLoc = MessExpr->getLocStart();
791 SourceLocation endLoc = MessExpr->getLocEnd();
792
793 const char *startBuf = SM->getCharacterData(startLoc);
794 const char *endBuf = SM->getCharacterData(endLoc);
795
796 std::string messString;
797 messString += "// ";
798 messString.append(startBuf, endBuf-startBuf+1);
799 messString += "\n";
Steve Naroff3774dd92007-10-26 20:53:56 +0000800
Steve Naroff71226032007-10-24 22:48:43 +0000801 // FIXME: Missing definition of Rewrite.InsertText(clang::SourceLocation, char const*, unsigned int).
802 // Rewrite.InsertText(startLoc, messString.c_str(), messString.size());
803 // Tried this, but it didn't work either...
Steve Narofff4b7d6a2007-10-30 16:42:30 +0000804 // Rewrite.ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffe9780582007-10-23 23:50:29 +0000805 return RewriteMessageExpr(MessExpr);
Steve Naroff71226032007-10-24 22:48:43 +0000806 }
Fariborz Jahanian9447e462007-11-05 17:47:33 +0000807
Ted Kremenek42730c52008-01-07 19:49:32 +0000808 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
809 return RewriteObjCTryStmt(StmtTry);
Steve Naroff8b1fb8c2007-11-07 15:32:26 +0000810
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000811 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
812 return RewriteObjCSynchronizedStmt(StmtTry);
813
Ted Kremenek42730c52008-01-07 19:49:32 +0000814 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
815 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +0000816
817 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
818 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000819
820 if (ObjCForCollectionStmt *StmtForCollection =
821 dyn_cast<ObjCForCollectionStmt>(S))
822 return RewriteObjCForCollectionStmt(StmtForCollection);
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000823 if (BreakStmt *StmtBreakStmt =
824 dyn_cast<BreakStmt>(S))
825 return RewriteBreakStmt(StmtBreakStmt);
826 if (ContinueStmt *StmtContinueStmt =
827 dyn_cast<ContinueStmt>(S))
828 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000829
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000830 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
831 isa<DoStmt>(S) || isa<ForStmt>(S)) {
832 assert(!Stmts.empty() && "Statement stack is empty");
833 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
834 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
835 && "Statement stack mismatch");
836 Stmts.pop_back();
837 }
Steve Naroff764c1ae2007-11-15 10:28:18 +0000838#if 0
839 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
840 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
841 // Get the new text.
842 std::ostringstream Buf;
843 Replacement->printPretty(Buf);
844 const std::string &Str = Buf.str();
845
846 printf("CAST = %s\n", &Str[0]);
847 Rewrite.InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
848 delete S;
849 return Replacement;
850 }
851#endif
Chris Lattner0021f452007-10-24 16:57:36 +0000852 // Return this stmt unmodified.
853 return S;
Chris Lattner6fe8b272007-10-16 22:36:42 +0000854}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000855
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000856/// SynthCountByEnumWithState - To print:
857/// ((unsigned int (*)
858/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
859/// (void *)objc_msgSend)((id)l_collection,
860/// sel_registerName(
861/// "countByEnumeratingWithState:objects:count:"),
862/// &enumState,
863/// (id *)items, (unsigned int)16)
864///
865void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
866 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
867 "id *, unsigned int))(void *)objc_msgSend)";
868 buf += "\n\t\t";
869 buf += "((id)l_collection,\n\t\t";
870 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
871 buf += "\n\t\t";
872 buf += "&enumState, "
873 "(id *)items, (unsigned int)16)";
874}
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000875
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000876/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
877/// statement to exit to its outer synthesized loop.
878///
879Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
880 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
881 return S;
882 // replace break with goto __break_label
883 std::string buf;
884
885 SourceLocation startLoc = S->getLocStart();
886 buf = "goto __break_label_";
887 buf += utostr(ObjCBcLabelNo.back());
888 Rewrite.ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
889
890 return 0;
891}
892
893/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
894/// statement to continue with its inner synthesized loop.
895///
896Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
897 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
898 return S;
899 // replace continue with goto __continue_label
900 std::string buf;
901
902 SourceLocation startLoc = S->getLocStart();
903 buf = "goto __continue_label_";
904 buf += utostr(ObjCBcLabelNo.back());
905 Rewrite.ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
906
907 return 0;
908}
909
Fariborz Jahanian499bf412008-01-29 22:59:37 +0000910/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000911/// It rewrites:
912/// for ( type elem in collection) { stmts; }
Fariborz Jahanian45d52f72007-10-18 22:09:03 +0000913
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000914/// Into:
915/// {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000916/// type elem;
917/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000918/// id items[16];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000919/// id l_collection = (id)collection;
920/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
921/// objects:items count:16];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000922/// if (limit) {
923/// unsigned long startMutations = *enumState.mutationsPtr;
924/// do {
925/// unsigned long counter = 0;
926/// do {
927/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000928/// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000929/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000930/// stmts;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000931/// __continue_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000932/// } while (counter < limit);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000933/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
934/// objects:items count:16]);
935/// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000936/// __break_label: ;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +0000937/// }
938/// else
939/// elem = nil;
940/// }
941///
942Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S) {
Fariborz Jahanian13dad332008-01-15 23:58:23 +0000943 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
944 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
945 "ObjCForCollectionStmt Statement stack mismatch");
946 assert(!ObjCBcLabelNo.empty() &&
947 "ObjCForCollectionStmt - Label No stack empty");
948
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000949 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000950 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000951 const char *elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000952 std::string elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000953 std::string buf;
954 buf = "\n{\n\t";
955 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
956 // type elem;
957 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000958 elementTypeAsString = ElementType.getAsString();
959 buf += elementTypeAsString;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000960 buf += " ";
961 elementName = DS->getDecl()->getName();
962 buf += elementName;
963 buf += ";\n\t";
964 }
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000965 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000966 elementName = DR->getDecl()->getName();
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +0000967 elementTypeAsString = DR->getDecl()->getType().getAsString();
968 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000969 else
970 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
971
972 // struct __objcFastEnumerationState enumState = { 0 };
973 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
974 // id items[16];
975 buf += "id items[16];\n\t";
976 // id l_collection = (id)
977 buf += "id l_collection = (id)";
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +0000978 // Find start location of 'collection' the hard way!
979 const char *startCollectionBuf = startBuf;
980 startCollectionBuf += 3; // skip 'for'
981 startCollectionBuf = strchr(startCollectionBuf, '(');
982 startCollectionBuf++; // skip '('
983 // find 'in' and skip it.
984 while (*startCollectionBuf != ' ' ||
985 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
986 (*(startCollectionBuf+3) != ' ' &&
987 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
988 startCollectionBuf++;
989 startCollectionBuf += 3;
990
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000991 // Replace: "for (type element in" with string constructed thus far.
992 Rewrite.ReplaceText(startLoc, startCollectionBuf - startBuf,
993 buf.c_str(), buf.size());
994 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahaniandf2b0952008-01-10 00:24:29 +0000995 SourceLocation rightParenLoc = S->getRParenLoc();
996 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
997 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +0000998 buf = ";\n\t";
999
1000 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1001 // objects:items count:16];
1002 // which is synthesized into:
1003 // unsigned int limit =
1004 // ((unsigned int (*)
1005 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1006 // (void *)objc_msgSend)((id)l_collection,
1007 // sel_registerName(
1008 // "countByEnumeratingWithState:objects:count:"),
1009 // (struct __objcFastEnumerationState *)&state,
1010 // (id *)items, (unsigned int)16);
1011 buf += "unsigned long limit =\n\t\t";
1012 SynthCountByEnumWithState(buf);
1013 buf += ";\n\t";
1014 /// if (limit) {
1015 /// unsigned long startMutations = *enumState.mutationsPtr;
1016 /// do {
1017 /// unsigned long counter = 0;
1018 /// do {
1019 /// if (startMutations != *enumState.mutationsPtr)
1020 /// objc_enumerationMutation(l_collection);
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001021 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001022 buf += "if (limit) {\n\t";
1023 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1024 buf += "do {\n\t\t";
1025 buf += "unsigned long counter = 0;\n\t\t";
1026 buf += "do {\n\t\t\t";
1027 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1028 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1029 buf += elementName;
Fariborz Jahanianfb09aa02008-01-09 18:15:42 +00001030 buf += " = (";
1031 buf += elementTypeAsString;
1032 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001033 // Replace ')' in for '(' type elem in collection ')' with all of these.
1034 Rewrite.ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
1035
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001036 /// __continue_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001037 /// } while (counter < limit);
1038 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1039 /// objects:items count:16]);
1040 /// elem = nil;
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001041 /// __break_label: ;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001042 /// }
1043 /// else
1044 /// elem = nil;
1045 /// }
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001046 ///
1047 buf = ";\n\t";
1048 buf += "__continue_label_";
1049 buf += utostr(ObjCBcLabelNo.back());
1050 buf += ": ;";
1051 buf += "\n\t\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001052 buf += "} while (counter < limit);\n\t";
1053 buf += "} while (limit = ";
1054 SynthCountByEnumWithState(buf);
1055 buf += ");\n\t";
1056 buf += elementName;
1057 buf += " = nil;\n\t";
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001058 buf += "__break_label_";
1059 buf += utostr(ObjCBcLabelNo.back());
1060 buf += ": ;\n\t";
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001061 buf += "}\n\t";
1062 buf += "else\n\t\t";
1063 buf += elementName;
1064 buf += " = nil;\n";
1065 buf += "}\n";
1066 // Insert all these *after* the statement body.
1067 SourceLocation endBodyLoc = S->getBody()->getLocEnd();
1068 const char *endBodyBuf = SM->getCharacterData(endBodyLoc)+1;
1069 endBodyLoc = startLoc.getFileLocWithOffset(endBodyBuf-startBuf);
1070 Rewrite.InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahanian13dad332008-01-15 23:58:23 +00001071 Stmts.pop_back();
1072 ObjCBcLabelNo.pop_back();
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001073
1074 return 0;
Fariborz Jahanian955fcb82008-01-07 21:40:22 +00001075}
1076
Fariborz Jahanian499bf412008-01-29 22:59:37 +00001077/// RewriteObjCSynchronizedStmt -
1078/// This routine rewrites @synchronized(expr) stmt;
1079/// into:
1080/// objc_sync_enter(expr);
1081/// @try stmt @finally { objc_sync_exit(expr); }
1082///
1083Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1084 // Get the start location and compute the semi location.
1085 SourceLocation startLoc = S->getLocStart();
1086 const char *startBuf = SM->getCharacterData(startLoc);
1087
1088 assert((*startBuf == '@') && "bogus @synchronized location");
1089
1090 std::string buf;
1091 buf = "objc_sync_enter";
1092 Rewrite.ReplaceText(startLoc, 13, buf.c_str(), buf.size());
1093 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1094 const char *endBuf = SM->getCharacterData(endLoc);
1095 endBuf++;
1096 const char *rparenBuf = strchr(endBuf, ')');
1097 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1098 buf = ");\n";
1099 // declare a new scope with two variables, _stack and _rethrow.
1100 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1101 buf += "int buf[18/*32-bit i386*/];\n";
1102 buf += "char *pointers[4];} _stack;\n";
1103 buf += "id volatile _rethrow = 0;\n";
1104 buf += "objc_exception_try_enter(&_stack);\n";
1105 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1106 Rewrite.ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
1107 startLoc = S->getSynchBody()->getLocEnd();
1108 startBuf = SM->getCharacterData(startLoc);
1109
1110 assert((*startBuf == '}') && "bogus @try block");
1111 SourceLocation lastCurlyLoc = startLoc;
1112 buf = "}\nelse {\n";
1113 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1114 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1115 // FIXME: This must be objc_sync_exit(syncExpr);
1116 buf += " objc_sync_exit();\n";
1117 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1118 buf += "}\n";
1119 buf += "}";
1120
1121 Rewrite.ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
1122 return 0;
1123}
1124
Ted Kremenek42730c52008-01-07 19:49:32 +00001125Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001126 // Get the start location and compute the semi location.
1127 SourceLocation startLoc = S->getLocStart();
1128 const char *startBuf = SM->getCharacterData(startLoc);
1129
1130 assert((*startBuf == '@') && "bogus @try location");
1131
1132 std::string buf;
1133 // declare a new scope with two variables, _stack and _rethrow.
1134 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1135 buf += "int buf[18/*32-bit i386*/];\n";
1136 buf += "char *pointers[4];} _stack;\n";
1137 buf += "id volatile _rethrow = 0;\n";
1138 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001139 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001140
1141 Rewrite.ReplaceText(startLoc, 4, buf.c_str(), buf.size());
1142
1143 startLoc = S->getTryBody()->getLocEnd();
1144 startBuf = SM->getCharacterData(startLoc);
1145
1146 assert((*startBuf == '}') && "bogus @try block");
1147
1148 SourceLocation lastCurlyLoc = startLoc;
1149
1150 startLoc = startLoc.getFileLocWithOffset(1);
1151 buf = " /* @catch begin */ else {\n";
1152 buf += " id _caught = objc_exception_extract(&_stack);\n";
1153 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroffd3287d82007-11-07 18:43:40 +00001154 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroffe9f69842007-11-07 04:08:17 +00001155 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1156 buf += " else { /* @catch continue */";
1157
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001158 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001159
1160 bool sawIdTypedCatch = false;
1161 Stmt *lastCatchBody = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001162 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroffe9f69842007-11-07 04:08:17 +00001163 while (catchList) {
1164 Stmt *catchStmt = catchList->getCatchParamStmt();
1165
1166 if (catchList == S->getCatchStmts())
1167 buf = "if ("; // we are generating code for the first catch clause
1168 else
1169 buf = "else if (";
1170 startLoc = catchList->getLocStart();
1171 startBuf = SM->getCharacterData(startLoc);
1172
1173 assert((*startBuf == '@') && "bogus @catch location");
1174
1175 const char *lParenLoc = strchr(startBuf, '(');
1176
1177 if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
1178 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremenek42730c52008-01-07 19:49:32 +00001179 if (t == Context->getObjCIdType()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001180 buf += "1) { ";
1181 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1182 buf.c_str(), buf.size());
1183 sawIdTypedCatch = true;
1184 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001185 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroffe9f69842007-11-07 04:08:17 +00001186
Ted Kremenek42730c52008-01-07 19:49:32 +00001187 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffe9f69842007-11-07 04:08:17 +00001188 if (cls) {
Steve Naroffd3287d82007-11-07 18:43:40 +00001189 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroffe9f69842007-11-07 04:08:17 +00001190 buf += cls->getDecl()->getName();
Steve Naroffd3287d82007-11-07 18:43:40 +00001191 buf += "\"), (struct objc_object *)_caught)) { ";
Steve Naroffe9f69842007-11-07 04:08:17 +00001192 Rewrite.ReplaceText(startLoc, lParenLoc-startBuf+1,
1193 buf.c_str(), buf.size());
1194 }
1195 }
1196 // Now rewrite the body...
1197 lastCatchBody = catchList->getCatchBody();
1198 SourceLocation rParenLoc = catchList->getRParenLoc();
1199 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1200 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1201 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1202 assert((*rParenBuf == ')') && "bogus @catch paren location");
1203 assert((*bodyBuf == '{') && "bogus @catch body location");
1204
1205 buf = " = _caught;";
1206 // Here we replace ") {" with "= _caught;" (which initializes and
1207 // declares the @catch parameter).
1208 Rewrite.ReplaceText(rParenLoc, bodyBuf-rParenBuf+1,
1209 buf.c_str(), buf.size());
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001210 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001211 assert(false && "@catch rewrite bug");
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001212 }
Steve Naroffe9f69842007-11-07 04:08:17 +00001213 catchList = catchList->getNextCatchStmt();
1214 }
1215 // Complete the catch list...
1216 if (lastCatchBody) {
1217 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1218 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1219 assert((*bodyBuf == '}') && "bogus @catch body location");
1220 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1221 buf = " } } /* @catch end */\n";
1222
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001223 Rewrite.InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001224
1225 // Set lastCurlyLoc
1226 lastCurlyLoc = lastCatchBody->getLocEnd();
1227 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001228 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffe9f69842007-11-07 04:08:17 +00001229 startLoc = finalStmt->getLocStart();
1230 startBuf = SM->getCharacterData(startLoc);
1231 assert((*startBuf == '@') && "bogus @finally start");
1232
1233 buf = "/* @finally */";
1234 Rewrite.ReplaceText(startLoc, 8, buf.c_str(), buf.size());
1235
1236 Stmt *body = finalStmt->getFinallyBody();
1237 SourceLocation startLoc = body->getLocStart();
1238 SourceLocation endLoc = body->getLocEnd();
1239 const char *startBuf = SM->getCharacterData(startLoc);
1240 const char *endBuf = SM->getCharacterData(endLoc);
1241 assert((*startBuf == '{') && "bogus @finally body location");
1242 assert((*endBuf == '}') && "bogus @finally body location");
1243
1244 startLoc = startLoc.getFileLocWithOffset(1);
1245 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001246 Rewrite.InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001247 endLoc = endLoc.getFileLocWithOffset(-1);
1248 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001249 Rewrite.InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroffe9f69842007-11-07 04:08:17 +00001250
1251 // Set lastCurlyLoc
1252 lastCurlyLoc = body->getLocEnd();
1253 }
1254 // Now emit the final closing curly brace...
1255 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1256 buf = " } /* @try scope end */\n";
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001257 Rewrite.InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001258 return 0;
1259}
1260
Ted Kremenek42730c52008-01-07 19:49:32 +00001261Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001262 return 0;
1263}
1264
Ted Kremenek42730c52008-01-07 19:49:32 +00001265Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001266 return 0;
1267}
1268
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001269// This can't be done with Rewrite.ReplaceStmt(S, ThrowExpr), since
1270// the throw expression is typically a message expression that's already
1271// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremenek42730c52008-01-07 19:49:32 +00001272Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001273 // Get the start location and compute the semi location.
1274 SourceLocation startLoc = S->getLocStart();
1275 const char *startBuf = SM->getCharacterData(startLoc);
1276
1277 assert((*startBuf == '@') && "bogus @throw location");
1278
1279 std::string buf;
1280 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffbe72efa2008-01-19 00:42:38 +00001281 if (S->getThrowExpr())
1282 buf = "objc_exception_throw(";
1283 else // add an implicit argument
1284 buf = "objc_exception_throw(_caught";
Steve Naroff8b1fb8c2007-11-07 15:32:26 +00001285 Rewrite.ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1286 const char *semiBuf = strchr(startBuf, ';');
1287 assert((*semiBuf == ';') && "@throw: can't find ';'");
1288 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1289 buf = ");";
1290 Rewrite.ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
1291 return 0;
1292}
Fariborz Jahanian9447e462007-11-05 17:47:33 +00001293
Chris Lattner0021f452007-10-24 16:57:36 +00001294Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001295 // Create a new string expression.
1296 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001297 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00001298 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1299 EncodingRecordTypes);
Anders Carlsson36f07d82007-10-29 05:01:08 +00001300 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1301 StrEncoding.length(), false, StrType,
Chris Lattnerbf0bfa62007-10-17 22:35:30 +00001302 SourceLocation(), SourceLocation());
Chris Lattner258f26c2007-11-30 22:25:36 +00001303 if (Rewrite.ReplaceStmt(Exp, Replacement)) {
1304 // replacement failed.
Chris Lattner217df512007-12-02 01:09:57 +00001305 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001306 if (!SilenceRewriteMacroWarning)
1307 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001308 0, 0, &Range, 1);
Chris Lattner258f26c2007-11-30 22:25:36 +00001309 }
1310
Chris Lattner4478db92007-11-30 22:53:43 +00001311 // Replace this subexpr in the parent.
Chris Lattner0021f452007-10-24 16:57:36 +00001312 delete Exp;
1313 return Replacement;
Chris Lattner6fe8b272007-10-16 22:36:42 +00001314}
1315
Steve Naroff296b74f2007-11-05 14:50:49 +00001316Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1317 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1318 // Create a call to sel_registerName("selName").
1319 llvm::SmallVector<Expr*, 8> SelExprs;
1320 QualType argType = Context->getPointerType(Context->CharTy);
1321 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1322 Exp->getSelector().getName().size(),
1323 false, argType, SourceLocation(),
1324 SourceLocation()));
1325 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1326 &SelExprs[0], SelExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001327 if (Rewrite.ReplaceStmt(Exp, SelExp)) {
1328 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001329 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001330 if (!SilenceRewriteMacroWarning)
1331 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001332 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001333 }
Steve Naroff296b74f2007-11-05 14:50:49 +00001334 delete Exp;
1335 return SelExp;
1336}
1337
Steve Naroff71226032007-10-24 22:48:43 +00001338CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1339 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffe9780582007-10-23 23:50:29 +00001340 // Get the type, we will need to reference it in a couple spots.
Steve Naroff71226032007-10-24 22:48:43 +00001341 QualType msgSendType = FD->getType();
Steve Naroffe9780582007-10-23 23:50:29 +00001342
1343 // Create a reference to the objc_msgSend() declaration.
Steve Naroff71226032007-10-24 22:48:43 +00001344 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffe9780582007-10-23 23:50:29 +00001345
1346 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerfce2c5a2007-10-24 17:06:59 +00001347 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffe9780582007-10-23 23:50:29 +00001348 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1349
1350 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattner0021f452007-10-24 16:57:36 +00001351
Steve Naroff71226032007-10-24 22:48:43 +00001352 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1353}
1354
Steve Naroffc8a92d12007-11-01 13:24:47 +00001355static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1356 const char *&startRef, const char *&endRef) {
1357 while (startBuf < endBuf) {
1358 if (*startBuf == '<')
1359 startRef = startBuf; // mark the start.
1360 if (*startBuf == '>') {
Steve Naroff2aeae312007-11-09 12:50:28 +00001361 if (startRef && *startRef == '<') {
1362 endRef = startBuf; // mark the end.
1363 return true;
1364 }
1365 return false;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001366 }
1367 startBuf++;
1368 }
1369 return false;
1370}
1371
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001372static void scanToNextArgument(const char *&argRef) {
1373 int angle = 0;
1374 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1375 if (*argRef == '<')
1376 angle++;
1377 else if (*argRef == '>')
1378 angle--;
1379 argRef++;
1380 }
1381 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1382}
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001383
Steve Naroffc8a92d12007-11-01 13:24:47 +00001384bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001385
Ted Kremenek42730c52008-01-07 19:49:32 +00001386 if (T == Context->getObjCIdType())
Steve Naroffc8a92d12007-11-01 13:24:47 +00001387 return true;
1388
Ted Kremenek42730c52008-01-07 19:49:32 +00001389 if (T->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001390 return true;
1391
Steve Naroffc8a92d12007-11-01 13:24:47 +00001392 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff05d6ff52007-10-31 04:38:33 +00001393 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001394 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff05d6ff52007-10-31 04:38:33 +00001395 return true; // we have "Class <Protocol> *".
1396 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001397 return false;
1398}
1399
Ted Kremenek42730c52008-01-07 19:49:32 +00001400void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001401 SourceLocation Loc;
1402 QualType Type;
1403 const FunctionTypeProto *proto = 0;
1404 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1405 Loc = VD->getLocation();
1406 Type = VD->getType();
1407 }
1408 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1409 Loc = FD->getLocation();
1410 // Check for ObjC 'id' and class types that have been adorned with protocol
1411 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1412 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1413 assert(funcType && "missing function type");
1414 proto = dyn_cast<FunctionTypeProto>(funcType);
1415 if (!proto)
1416 return;
1417 Type = proto->getResultType();
1418 }
1419 else
1420 return;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001421
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001422 if (needToScanForQualifiers(Type)) {
Steve Naroffc8a92d12007-11-01 13:24:47 +00001423 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001424
1425 const char *endBuf = SM->getCharacterData(Loc);
1426 const char *startBuf = endBuf;
Chris Lattnerae43eb72007-12-02 01:13:47 +00001427 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffc8a92d12007-11-01 13:24:47 +00001428 startBuf--; // scan backward (from the decl location) for return type.
1429 const char *startRef = 0, *endRef = 0;
1430 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1431 // Get the locations of the startRef, endRef.
1432 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1433 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1434 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001435 Rewrite.InsertText(LessLoc, "/*", 2);
1436 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroff05d6ff52007-10-31 04:38:33 +00001437 }
1438 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001439 if (!proto)
1440 return; // most likely, was a variable
Steve Naroffc8a92d12007-11-01 13:24:47 +00001441 // Now check arguments.
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001442 const char *startBuf = SM->getCharacterData(Loc);
1443 const char *startFuncBuf = startBuf;
Steve Naroffc8a92d12007-11-01 13:24:47 +00001444 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1445 if (needToScanForQualifiers(proto->getArgType(i))) {
1446 // Since types are unique, we need to scan the buffer.
Steve Naroffc8a92d12007-11-01 13:24:47 +00001447
Steve Naroffc8a92d12007-11-01 13:24:47 +00001448 const char *endBuf = startBuf;
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001449 // scan forward (from the decl location) for argument types.
1450 scanToNextArgument(endBuf);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001451 const char *startRef = 0, *endRef = 0;
1452 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1453 // Get the locations of the startRef, endRef.
Fariborz Jahaniandb2904f2007-12-11 23:04:08 +00001454 SourceLocation LessLoc =
1455 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1456 SourceLocation GreaterLoc =
1457 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001458 // Comment out the protocol references.
Chris Lattner3c82a7e2007-11-08 04:41:51 +00001459 Rewrite.InsertText(LessLoc, "/*", 2);
1460 Rewrite.InsertText(GreaterLoc, "*/", 2);
Steve Naroffc8a92d12007-11-01 13:24:47 +00001461 }
Fariborz Jahanian150c6ea2007-12-11 22:50:14 +00001462 startBuf = ++endBuf;
1463 }
1464 else {
1465 while (*startBuf != ')' && *startBuf != ',')
1466 startBuf++; // scan forward (from the decl location) for argument types.
1467 startBuf++;
1468 }
Steve Naroffc8a92d12007-11-01 13:24:47 +00001469 }
Steve Naroff05d6ff52007-10-31 04:38:33 +00001470}
1471
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001472// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1473void RewriteTest::SynthSelGetUidFunctionDecl() {
1474 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1475 llvm::SmallVector<QualType, 16> ArgTys;
1476 ArgTys.push_back(Context->getPointerType(
1477 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001478 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001479 &ArgTys[0], ArgTys.size(),
1480 false /*isVariadic*/);
1481 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1482 SelGetUidIdent, getFuncType,
1483 FunctionDecl::Extern, false, 0);
1484}
1485
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001486// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1487void RewriteTest::SynthGetProtocolFunctionDecl() {
1488 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1489 llvm::SmallVector<QualType, 16> ArgTys;
1490 ArgTys.push_back(Context->getPointerType(
1491 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001492 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00001493 &ArgTys[0], ArgTys.size(),
1494 false /*isVariadic*/);
1495 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1496 SelGetProtoIdent, getFuncType,
1497 FunctionDecl::Extern, false, 0);
1498}
1499
Steve Naroff02a82aa2007-10-30 23:14:51 +00001500void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1501 // declared in <objc/objc.h>
Steve Naroff0add5d22007-11-03 11:27:19 +00001502 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff02a82aa2007-10-30 23:14:51 +00001503 SelGetUidFunctionDecl = FD;
Steve Naroff05d6ff52007-10-31 04:38:33 +00001504 return;
1505 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001506 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff02a82aa2007-10-30 23:14:51 +00001507}
1508
1509// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1510void RewriteTest::SynthMsgSendFunctionDecl() {
1511 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1512 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001513 QualType argT = Context->getObjCIdType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001514 assert(!argT.isNull() && "Can't find 'id' type");
1515 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001516 argT = Context->getObjCSelType();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001517 assert(!argT.isNull() && "Can't find 'SEL' type");
1518 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001519 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001520 &ArgTys[0], ArgTys.size(),
1521 true /*isVariadic*/);
1522 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1523 msgSendIdent, msgSendType,
1524 FunctionDecl::Extern, false, 0);
1525}
1526
Steve Naroff764c1ae2007-11-15 10:28:18 +00001527// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1528void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1529 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1530 llvm::SmallVector<QualType, 16> ArgTys;
1531 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1532 &Context->Idents.get("objc_super"), 0);
1533 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1534 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1535 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001536 argT = Context->getObjCSelType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001537 assert(!argT.isNull() && "Can't find 'SEL' type");
1538 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001539 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001540 &ArgTys[0], ArgTys.size(),
1541 true /*isVariadic*/);
1542 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1543 msgSendIdent, msgSendType,
1544 FunctionDecl::Extern, false, 0);
1545}
1546
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001547// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1548void RewriteTest::SynthMsgSendStretFunctionDecl() {
1549 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1550 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001551 QualType argT = Context->getObjCIdType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001552 assert(!argT.isNull() && "Can't find 'id' type");
1553 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001554 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001555 assert(!argT.isNull() && "Can't find 'SEL' type");
1556 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001557 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001558 &ArgTys[0], ArgTys.size(),
1559 true /*isVariadic*/);
1560 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1561 msgSendIdent, msgSendType,
1562 FunctionDecl::Extern, false, 0);
1563}
1564
1565// SynthMsgSendSuperStretFunctionDecl -
1566// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1567void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1568 IdentifierInfo *msgSendIdent =
1569 &Context->Idents.get("objc_msgSendSuper_stret");
1570 llvm::SmallVector<QualType, 16> ArgTys;
1571 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1572 &Context->Idents.get("objc_super"), 0);
1573 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1574 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1575 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001576 argT = Context->getObjCSelType();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001577 assert(!argT.isNull() && "Can't find 'SEL' type");
1578 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001579 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001580 &ArgTys[0], ArgTys.size(),
1581 true /*isVariadic*/);
1582 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1583 msgSendIdent, msgSendType,
1584 FunctionDecl::Extern, false, 0);
1585}
1586
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001587// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1588void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1589 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1590 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek42730c52008-01-07 19:49:32 +00001591 QualType argT = Context->getObjCIdType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001592 assert(!argT.isNull() && "Can't find 'id' type");
1593 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001594 argT = Context->getObjCSelType();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001595 assert(!argT.isNull() && "Can't find 'SEL' type");
1596 ArgTys.push_back(argT);
Ted Kremenek42730c52008-01-07 19:49:32 +00001597 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001598 &ArgTys[0], ArgTys.size(),
1599 true /*isVariadic*/);
1600 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1601 msgSendIdent, msgSendType,
1602 FunctionDecl::Extern, false, 0);
1603}
1604
Steve Naroff02a82aa2007-10-30 23:14:51 +00001605// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1606void RewriteTest::SynthGetClassFunctionDecl() {
1607 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1608 llvm::SmallVector<QualType, 16> ArgTys;
1609 ArgTys.push_back(Context->getPointerType(
1610 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001611 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff02a82aa2007-10-30 23:14:51 +00001612 &ArgTys[0], ArgTys.size(),
1613 false /*isVariadic*/);
1614 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1615 getClassIdent, getClassType,
1616 FunctionDecl::Extern, false, 0);
1617}
1618
Steve Naroff3b1caac2007-12-07 03:50:46 +00001619// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1620void RewriteTest::SynthGetMetaClassFunctionDecl() {
1621 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1622 llvm::SmallVector<QualType, 16> ArgTys;
1623 ArgTys.push_back(Context->getPointerType(
1624 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001625 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001626 &ArgTys[0], ArgTys.size(),
1627 false /*isVariadic*/);
1628 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1629 getClassIdent, getClassType,
1630 FunctionDecl::Extern, false, 0);
1631}
1632
Steve Naroffabb96362007-11-08 14:30:50 +00001633// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1634void RewriteTest::SynthCFStringFunctionDecl() {
1635 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1636 llvm::SmallVector<QualType, 16> ArgTys;
1637 ArgTys.push_back(Context->getPointerType(
1638 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremenek42730c52008-01-07 19:49:32 +00001639 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffabb96362007-11-08 14:30:50 +00001640 &ArgTys[0], ArgTys.size(),
1641 false /*isVariadic*/);
1642 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1643 getClassIdent, getClassType,
1644 FunctionDecl::Extern, false, 0);
1645}
1646
Steve Naroff0add5d22007-11-03 11:27:19 +00001647Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffabb96362007-11-08 14:30:50 +00001648#if 1
1649 // This rewrite is specific to GCC, which has builtin support for CFString.
1650 if (!CFStringFunctionDecl)
1651 SynthCFStringFunctionDecl();
1652 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1653 llvm::SmallVector<Expr*, 8> StrExpr;
1654 StrExpr.push_back(Exp->getString());
1655 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1656 &StrExpr[0], StrExpr.size());
1657 // cast to NSConstantString *
1658 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Steve Naroffe4e5e262007-12-19 14:32:56 +00001659 if (Rewrite.ReplaceStmt(Exp, cast)) {
1660 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00001661 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00001662 if (!SilenceRewriteMacroWarning)
1663 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00001664 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00001665 }
Steve Naroffabb96362007-11-08 14:30:50 +00001666 delete Exp;
1667 return cast;
1668#else
Steve Naroff0add5d22007-11-03 11:27:19 +00001669 assert(ConstantStringClassReference && "Can't find constant string reference");
1670 llvm::SmallVector<Expr*, 4> InitExprs;
1671
1672 // Synthesize "(Class)&_NSConstantStringClassReference"
1673 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1674 ConstantStringClassReference->getType(),
1675 SourceLocation());
1676 QualType expType = Context->getPointerType(ClsRef->getType());
1677 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1678 expType, SourceLocation());
Ted Kremenek42730c52008-01-07 19:49:32 +00001679 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroff0add5d22007-11-03 11:27:19 +00001680 SourceLocation());
1681 InitExprs.push_back(cast); // set the 'isa'.
1682 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1683 unsigned IntSize = static_cast<unsigned>(
1684 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1685 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1686 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1687 Exp->getLocStart());
1688 InitExprs.push_back(len); // set "int numBytes".
1689
1690 // struct NSConstantString
1691 QualType CFConstantStrType = Context->getCFConstantStringType();
1692 // (struct NSConstantString) { <exprs from above> }
1693 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1694 &InitExprs[0], InitExprs.size(),
1695 SourceLocation());
Steve Naroffbe37fc02008-01-14 18:19:28 +00001696 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroff0add5d22007-11-03 11:27:19 +00001697 // struct NSConstantString *
1698 expType = Context->getPointerType(StrRep->getType());
1699 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1700 SourceLocation());
Steve Naroff4242b972007-11-05 14:36:37 +00001701 // cast to NSConstantString *
1702 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Steve Naroff0add5d22007-11-03 11:27:19 +00001703 Rewrite.ReplaceStmt(Exp, cast);
1704 delete Exp;
Steve Naroff4242b972007-11-05 14:36:37 +00001705 return cast;
Steve Naroffabb96362007-11-08 14:30:50 +00001706#endif
Steve Naroff0add5d22007-11-03 11:27:19 +00001707}
1708
Ted Kremenek42730c52008-01-07 19:49:32 +00001709ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff3b1caac2007-12-07 03:50:46 +00001710 // check if we are sending a message to 'super'
1711 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001712 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1713 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1714 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1715 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001716 // is this id<P1..> type?
Ted Kremenek42730c52008-01-07 19:49:32 +00001717 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001718 return 0;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001719 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001720 if (ObjCInterfaceType *IT =
1721 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001722 if (IT->getDecl() ==
1723 CurMethodDecl->getClassInterface()->getSuperClass())
1724 return IT->getDecl();
1725 }
1726 }
1727 }
1728 }
1729 }
Steve Naroff3b1caac2007-12-07 03:50:46 +00001730 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001731 }
1732 return 0;
1733}
1734
1735// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1736QualType RewriteTest::getSuperStructType() {
1737 if (!SuperStructDecl) {
1738 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1739 &Context->Idents.get("objc_super"), 0);
1740 QualType FieldTypes[2];
1741
1742 // struct objc_object *receiver;
Ted Kremenek42730c52008-01-07 19:49:32 +00001743 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001744 // struct objc_class *super;
Ted Kremenek42730c52008-01-07 19:49:32 +00001745 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001746 // Create fields
1747 FieldDecl *FieldDecls[2];
1748
1749 for (unsigned i = 0; i < 2; ++i)
1750 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1751
1752 SuperStructDecl->defineBody(FieldDecls, 4);
1753 }
1754 return Context->getTagDeclType(SuperStructDecl);
1755}
1756
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001757Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianfb8e9912007-12-04 21:47:40 +00001758 if (!SelGetUidFunctionDecl)
1759 SynthSelGetUidFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001760 if (!MsgSendFunctionDecl)
1761 SynthMsgSendFunctionDecl();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001762 if (!MsgSendSuperFunctionDecl)
1763 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001764 if (!MsgSendStretFunctionDecl)
1765 SynthMsgSendStretFunctionDecl();
1766 if (!MsgSendSuperStretFunctionDecl)
1767 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001768 if (!MsgSendFpretFunctionDecl)
1769 SynthMsgSendFpretFunctionDecl();
Steve Naroff02a82aa2007-10-30 23:14:51 +00001770 if (!GetClassFunctionDecl)
1771 SynthGetClassFunctionDecl();
Steve Naroff3b1caac2007-12-07 03:50:46 +00001772 if (!GetMetaClassFunctionDecl)
1773 SynthGetMetaClassFunctionDecl();
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001774
Steve Naroff764c1ae2007-11-15 10:28:18 +00001775 // default to objc_msgSend().
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001776 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1777 // May need to use objc_msgSend_stret() as well.
1778 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremenek42730c52008-01-07 19:49:32 +00001779 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001780 QualType resultType = mDecl->getResultType();
1781 if (resultType.getCanonicalType()->isStructureType()
1782 || resultType.getCanonicalType()->isUnionType())
1783 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanian1d29b5d2007-12-03 21:26:48 +00001784 else if (resultType.getCanonicalType()->isRealFloatingType())
1785 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001786 }
Steve Naroff764c1ae2007-11-15 10:28:18 +00001787
Steve Naroff71226032007-10-24 22:48:43 +00001788 // Synthesize a call to objc_msgSend().
1789 llvm::SmallVector<Expr*, 8> MsgExprs;
1790 IdentifierInfo *clsName = Exp->getClassName();
1791
1792 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1793 if (clsName) { // class message.
Steve Naroff3b1caac2007-12-07 03:50:46 +00001794 if (!strcmp(clsName->getName(), "super")) {
1795 MsgSendFlavor = MsgSendSuperFunctionDecl;
1796 if (MsgSendStretFlavor)
1797 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1798 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1799
Ted Kremenek42730c52008-01-07 19:49:32 +00001800 ObjCInterfaceDecl *SuperDecl =
Steve Naroff3b1caac2007-12-07 03:50:46 +00001801 CurMethodDecl->getClassInterface()->getSuperClass();
1802
1803 llvm::SmallVector<Expr*, 4> InitExprs;
1804
1805 // set the receiver to self, the first argument to all methods.
1806 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremenek42730c52008-01-07 19:49:32 +00001807 Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001808 SourceLocation()));
1809 llvm::SmallVector<Expr*, 8> ClsExprs;
1810 QualType argType = Context->getPointerType(Context->CharTy);
1811 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1812 SuperDecl->getIdentifier()->getLength(),
1813 false, argType, SourceLocation(),
1814 SourceLocation()));
1815 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1816 &ClsExprs[0],
1817 ClsExprs.size());
1818 // To turn off a warning, type-cast to 'id'
1819 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001820 new CastExpr(Context->getObjCIdType(),
Steve Naroff3b1caac2007-12-07 03:50:46 +00001821 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1822 // struct objc_super
1823 QualType superType = getSuperStructType();
1824 // (struct objc_super) { <exprs from above> }
1825 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1826 &InitExprs[0], InitExprs.size(),
1827 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001828 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001829 superType, ILE, false);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001830 // struct objc_super *
1831 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1832 Context->getPointerType(SuperRep->getType()),
1833 SourceLocation());
1834 MsgExprs.push_back(Unop);
1835 } else {
1836 llvm::SmallVector<Expr*, 8> ClsExprs;
1837 QualType argType = Context->getPointerType(Context->CharTy);
1838 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1839 clsName->getLength(),
1840 false, argType, SourceLocation(),
1841 SourceLocation()));
1842 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1843 &ClsExprs[0],
1844 ClsExprs.size());
1845 MsgExprs.push_back(Cls);
1846 }
Steve Naroff885e2122007-11-14 23:54:14 +00001847 } else { // instance message.
1848 Expr *recExpr = Exp->getReceiver();
Steve Naroff764c1ae2007-11-15 10:28:18 +00001849
Ted Kremenek42730c52008-01-07 19:49:32 +00001850 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff764c1ae2007-11-15 10:28:18 +00001851 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001852 if (MsgSendStretFlavor)
1853 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff764c1ae2007-11-15 10:28:18 +00001854 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1855
1856 llvm::SmallVector<Expr*, 4> InitExprs;
1857
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001858 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001859 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001860 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001861
1862 llvm::SmallVector<Expr*, 8> ClsExprs;
1863 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff3b1caac2007-12-07 03:50:46 +00001864 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1865 SuperDecl->getIdentifier()->getLength(),
Steve Naroff764c1ae2007-11-15 10:28:18 +00001866 false, argType, SourceLocation(),
1867 SourceLocation()));
1868 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001869 &ClsExprs[0],
1870 ClsExprs.size());
Fariborz Jahanianfabf3bf2007-12-05 17:29:46 +00001871 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001872 InitExprs.push_back(
Ted Kremenek42730c52008-01-07 19:49:32 +00001873 new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandc25ba72007-12-04 22:32:58 +00001874 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff764c1ae2007-11-15 10:28:18 +00001875 // struct objc_super
1876 QualType superType = getSuperStructType();
1877 // (struct objc_super) { <exprs from above> }
1878 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1879 &InitExprs[0], InitExprs.size(),
1880 SourceLocation());
Chris Lattner386ab8a2008-01-02 21:46:24 +00001881 CompoundLiteralExpr *SuperRep = new CompoundLiteralExpr(SourceLocation(),
Steve Naroffbe37fc02008-01-14 18:19:28 +00001882 superType, ILE, false);
Steve Naroff764c1ae2007-11-15 10:28:18 +00001883 // struct objc_super *
1884 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1885 Context->getPointerType(SuperRep->getType()),
1886 SourceLocation());
1887 MsgExprs.push_back(Unop);
1888 } else {
Fariborz Jahanianbe4283c2007-12-07 21:21:21 +00001889 // Remove all type-casts because it may contain objc-style types; e.g.
1890 // Foo<Proto> *.
1891 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1892 recExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001893 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff764c1ae2007-11-15 10:28:18 +00001894 MsgExprs.push_back(recExpr);
1895 }
Steve Naroff885e2122007-11-14 23:54:14 +00001896 }
Steve Naroff0add5d22007-11-03 11:27:19 +00001897 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff71226032007-10-24 22:48:43 +00001898 llvm::SmallVector<Expr*, 8> SelExprs;
1899 QualType argType = Context->getPointerType(Context->CharTy);
1900 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1901 Exp->getSelector().getName().size(),
1902 false, argType, SourceLocation(),
1903 SourceLocation()));
1904 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1905 &SelExprs[0], SelExprs.size());
1906 MsgExprs.push_back(SelExp);
1907
1908 // Now push any user supplied arguments.
1909 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff885e2122007-11-14 23:54:14 +00001910 Expr *userExpr = Exp->getArg(i);
Steve Naroff6b759ce2007-11-15 02:58:25 +00001911 // Make all implicit casts explicit...ICE comes in handy:-)
1912 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1913 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremenek42730c52008-01-07 19:49:32 +00001914 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
1915 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001916 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001917 }
1918 // Make id<P...> cast into an 'id' cast.
1919 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001920 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001921 while ((CE = dyn_cast<CastExpr>(userExpr)))
1922 userExpr = CE->getSubExpr();
Ted Kremenek42730c52008-01-07 19:49:32 +00001923 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniandcb2b1e2007-12-18 21:33:44 +00001924 userExpr, SourceLocation());
1925 }
Steve Naroff6b759ce2007-11-15 02:58:25 +00001926 }
Steve Naroff885e2122007-11-14 23:54:14 +00001927 MsgExprs.push_back(userExpr);
Steve Naroff71226032007-10-24 22:48:43 +00001928 // We've transferred the ownership to MsgExprs. Null out the argument in
1929 // the original expression, since we will delete it below.
1930 Exp->setArg(i, 0);
1931 }
Steve Naroff0744c472007-11-04 22:37:50 +00001932 // Generate the funky cast.
1933 CastExpr *cast;
1934 llvm::SmallVector<QualType, 8> ArgTypes;
1935 QualType returnType;
1936
1937 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff0c04bb62007-11-15 10:43:57 +00001938 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
1939 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
1940 else
Ted Kremenek42730c52008-01-07 19:49:32 +00001941 ArgTypes.push_back(Context->getObjCIdType());
1942 ArgTypes.push_back(Context->getObjCSelType());
1943 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroff0744c472007-11-04 22:37:50 +00001944 // Push any user argument types.
Steve Naroff4242b972007-11-05 14:36:37 +00001945 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00001946 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
1947 ? Context->getObjCIdType()
Fariborz Jahaniane76e8412007-12-17 21:03:50 +00001948 : mDecl->getParamDecl(i)->getType();
Steve Naroff4242b972007-11-05 14:36:37 +00001949 ArgTypes.push_back(t);
1950 }
Ted Kremenek42730c52008-01-07 19:49:32 +00001951 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
1952 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroff0744c472007-11-04 22:37:50 +00001953 } else {
Ted Kremenek42730c52008-01-07 19:49:32 +00001954 returnType = Context->getObjCIdType();
Steve Naroff0744c472007-11-04 22:37:50 +00001955 }
1956 // Get the type, we will need to reference it in a couple spots.
Steve Naroff764c1ae2007-11-15 10:28:18 +00001957 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroff0744c472007-11-04 22:37:50 +00001958
1959 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001960 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
1961 SourceLocation());
Steve Naroff0744c472007-11-04 22:37:50 +00001962
1963 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
1964 // If we don't do this cast, we get the following bizarre warning/note:
1965 // xx.m:13: warning: function called through a non-compatible type
1966 // xx.m:13: note: if this code is reached, the program will abort
1967 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
1968 SourceLocation());
Steve Naroff29fe7462007-11-15 12:35:21 +00001969
Steve Naroff0744c472007-11-04 22:37:50 +00001970 // Now do the "normal" pointer to function cast.
1971 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001972 &ArgTypes[0], ArgTypes.size(),
1973 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroff0744c472007-11-04 22:37:50 +00001974 castType = Context->getPointerType(castType);
1975 cast = new CastExpr(castType, cast, SourceLocation());
1976
1977 // Don't forget the parens to enforce the proper binding.
1978 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
1979
1980 const FunctionType *FT = msgSendType->getAsFunctionType();
1981 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
1982 FT->getResultType(), SourceLocation());
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00001983 Stmt *ReplacingStmt = CE;
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00001984 if (MsgSendStretFlavor) {
1985 // We have the method which returns a struct/union. Must also generate
1986 // call to objc_msgSend_stret and hang both varieties on a conditional
1987 // expression which dictate which one to envoke depending on size of
1988 // method's return type.
1989
1990 // Create a reference to the objc_msgSend_stret() declaration.
1991 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
1992 SourceLocation());
1993 // Need to cast objc_msgSend_stret to "void *" (see above comment).
1994 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
1995 SourceLocation());
1996 // Now do the "normal" pointer to function cast.
1997 castType = Context->getFunctionType(returnType,
Fariborz Jahanianefba8c82007-12-06 19:49:56 +00001998 &ArgTypes[0], ArgTypes.size(),
1999 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002000 castType = Context->getPointerType(castType);
2001 cast = new CastExpr(castType, cast, SourceLocation());
2002
2003 // Don't forget the parens to enforce the proper binding.
2004 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2005
2006 FT = msgSendType->getAsFunctionType();
2007 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2008 FT->getResultType(), SourceLocation());
2009
2010 // Build sizeof(returnType)
2011 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2012 returnType, Context->getSizeType(),
2013 SourceLocation(), SourceLocation());
2014 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2015 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2016 // For X86 it is more complicated and some kind of target specific routine
2017 // is needed to decide what to do.
2018 unsigned IntSize = static_cast<unsigned>(
2019 Context->getTypeSize(Context->IntTy, SourceLocation()));
2020
2021 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2022 Context->IntTy,
2023 SourceLocation());
2024 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2025 BinaryOperator::LE,
2026 Context->IntTy,
2027 SourceLocation());
2028 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2029 ConditionalOperator *CondExpr =
2030 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002031 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanianc26b2502007-12-03 19:17:29 +00002032 }
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002033 return ReplacingStmt;
2034}
2035
2036Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2037 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff71226032007-10-24 22:48:43 +00002038 // Now do the actual rewrite.
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002039 if (Rewrite.ReplaceStmt(Exp, ReplacingStmt)) {
Steve Naroffe4e5e262007-12-19 14:32:56 +00002040 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00002041 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00002042 if (!SilenceRewriteMacroWarning)
2043 Diags.Report(Context->getFullLoc(Exp->getLocStart()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002044 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00002045 }
Steve Naroff71226032007-10-24 22:48:43 +00002046
Chris Lattner0021f452007-10-24 16:57:36 +00002047 delete Exp;
Fariborz Jahanian9ea6a2d2008-01-08 22:06:28 +00002048 return ReplacingStmt;
Steve Naroffe9780582007-10-23 23:50:29 +00002049}
2050
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002051/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2052/// call to objc_getProtocol("proto-name").
2053Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2054 if (!GetProtocolFunctionDecl)
2055 SynthGetProtocolFunctionDecl();
2056 // Create a call to objc_getProtocol("ProtocolName").
2057 llvm::SmallVector<Expr*, 8> ProtoExprs;
2058 QualType argType = Context->getPointerType(Context->CharTy);
2059 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2060 strlen(Exp->getProtocol()->getName()),
2061 false, argType, SourceLocation(),
2062 SourceLocation()));
2063 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2064 &ProtoExprs[0],
2065 ProtoExprs.size());
Steve Naroffe4e5e262007-12-19 14:32:56 +00002066 if (Rewrite.ReplaceStmt(Exp, ProtoExp)) {
2067 // replacement failed.
Steve Naroffe4e5e262007-12-19 14:32:56 +00002068 SourceRange Range = Exp->getSourceRange();
Steve Naroff1c46cf12008-01-28 21:34:52 +00002069 if (!SilenceRewriteMacroWarning)
2070 Diags.Report(Context->getFullLoc(Exp->getAtLoc()), RewriteFailedDiag,
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002071 0, 0, &Range, 1);
Steve Naroffe4e5e262007-12-19 14:32:56 +00002072 }
Fariborz Jahanian6ff57c62007-12-07 18:47:10 +00002073 delete Exp;
2074 return ProtoExp;
2075
2076}
2077
Ted Kremenek42730c52008-01-07 19:49:32 +00002078/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002079/// an objective-c class with ivars.
Ted Kremenek42730c52008-01-07 19:49:32 +00002080void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002081 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002082 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2083 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002084 // Do not synthesize more than once.
Ted Kremenek42730c52008-01-07 19:49:32 +00002085 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianfb4f6a32007-10-31 23:08:24 +00002086 return;
Ted Kremenek42730c52008-01-07 19:49:32 +00002087 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroffdd2e26c2007-11-12 13:56:41 +00002088 int NumIvars = CDecl->getNumInstanceVariables();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002089 SourceLocation LocStart = CDecl->getLocStart();
2090 SourceLocation LocEnd = CDecl->getLocEnd();
2091
2092 const char *startBuf = SM->getCharacterData(LocStart);
2093 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002094 // If no ivars and no root or if its root, directly or indirectly,
2095 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremenek42730c52008-01-07 19:49:32 +00002096 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002097 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2098 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2099 Result.c_str(), Result.size());
2100 return;
2101 }
2102
2103 // FIXME: This has potential of causing problem. If
Ted Kremenek42730c52008-01-07 19:49:32 +00002104 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian920cde32007-11-26 19:52:57 +00002105 Result += "\nstruct ";
2106 Result += CDecl->getName();
Steve Naroff2c7afc92007-11-14 19:25:57 +00002107
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002108 if (NumIvars > 0) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002109 const char *cursor = strchr(startBuf, '{');
2110 assert((cursor && endBuf)
Ted Kremenek42730c52008-01-07 19:49:32 +00002111 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroff2c7afc92007-11-14 19:25:57 +00002112
2113 // rewrite the original header *without* disturbing the '{'
2114 Rewrite.ReplaceText(LocStart, cursor-startBuf-1,
2115 Result.c_str(), Result.size());
Ted Kremenek42730c52008-01-07 19:49:32 +00002116 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroff2c7afc92007-11-14 19:25:57 +00002117 Result = "\n struct ";
2118 Result += RCDecl->getName();
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002119 // Note: We don't name the field decl. This simplifies the "codegen" for
2120 // accessing a superclasses instance variables (and is similar to what gcc
2121 // does internally). The unnamed struct field feature is enabled with
2122 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2123 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002124 Result += ";\n";
2125
2126 // insert the super class structure definition.
2127 SourceLocation OnePastCurly = LocStart.getFileLocWithOffset(cursor-startBuf+1);
2128 Rewrite.InsertText(OnePastCurly, Result.c_str(), Result.size());
2129 }
2130 cursor++; // past '{'
2131
2132 // Now comment out any visibility specifiers.
2133 while (cursor < endBuf) {
2134 if (*cursor == '@') {
2135 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf04ead52007-11-14 22:57:51 +00002136 // Skip whitespace.
2137 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2138 /*scan*/;
2139
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002140 // FIXME: presence of @public, etc. inside comment results in
2141 // this transformation as well, which is still correct c-code.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002142 if (!strncmp(cursor, "public", strlen("public")) ||
2143 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002144 !strncmp(cursor, "protected", strlen("protected")))
Steve Naroff2c7afc92007-11-14 19:25:57 +00002145 Rewrite.InsertText(atLoc, "// ", 3);
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002146 }
Fariborz Jahanian8d9c7352007-11-14 22:26:25 +00002147 // FIXME: If there are cases where '<' is used in ivar declaration part
2148 // of user code, then scan the ivar list and use needToScanForQualifiers
2149 // for type checking.
2150 else if (*cursor == '<') {
2151 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2152 Rewrite.InsertText(atLoc, "/* ", 3);
2153 cursor = strchr(cursor, '>');
2154 cursor++;
2155 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2156 Rewrite.InsertText(atLoc, " */", 3);
2157 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002158 cursor++;
Fariborz Jahanian6acfa2b2007-10-31 17:29:28 +00002159 }
Steve Naroff2c7afc92007-11-14 19:25:57 +00002160 // Don't forget to add a ';'!!
2161 Rewrite.InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
2162 } else { // we don't have any instance variables - insert super struct.
2163 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2164 Result += " {\n struct ";
2165 Result += RCDecl->getName();
Steve Naroff53b6f4c2008-01-30 19:17:43 +00002166 // Note: We don't name the field decl. This simplifies the "codegen" for
2167 // accessing a superclasses instance variables (and is similar to what gcc
2168 // does internally). The unnamed struct field feature is enabled with
2169 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2170 // need to use this switch. That said, I don't want to inline the def.
Steve Naroff2c7afc92007-11-14 19:25:57 +00002171 Result += ";\n};\n";
2172 Rewrite.ReplaceText(LocStart, endBuf-startBuf,
2173 Result.c_str(), Result.size());
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002174 }
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002175 // Mark this struct as having been generated.
Ted Kremenek42730c52008-01-07 19:49:32 +00002176 if (!ObjCSynthesizedStructs.insert(CDecl))
2177 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002178}
2179
Ted Kremenek42730c52008-01-07 19:49:32 +00002180// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002181/// class methods.
Ted Kremenek42730c52008-01-07 19:49:32 +00002182void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002183 instmeth_iterator MethodEnd,
Fariborz Jahaniana3986372007-10-25 00:14:44 +00002184 bool IsInstanceMethod,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002185 const char *prefix,
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002186 const char *ClassName,
2187 std::string &Result) {
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002188 if (MethodBegin == MethodEnd) return;
2189
Fariborz Jahanian04455192007-10-22 21:41:37 +00002190 static bool objc_impl_method = false;
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002191 if (!objc_impl_method) {
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002192 /* struct _objc_method {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002193 SEL _cmd;
2194 char *method_types;
2195 void *_imp;
2196 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002197 */
Chris Lattnerc3aa5c42007-10-25 17:07:24 +00002198 Result += "\nstruct _objc_method {\n";
2199 Result += "\tSEL _cmd;\n";
2200 Result += "\tchar *method_types;\n";
2201 Result += "\tvoid *_imp;\n";
2202 Result += "};\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002203
2204 /* struct _objc_method_list {
2205 struct _objc_method_list *next_method;
2206 int method_count;
2207 struct _objc_method method_list[];
2208 }
2209 */
2210 Result += "\nstruct _objc_method_list {\n";
2211 Result += "\tstruct _objc_method_list *next_method;\n";
2212 Result += "\tint method_count;\n";
2213 Result += "\tstruct _objc_method method_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002214 objc_impl_method = true;
Fariborz Jahanian96b55da2007-10-19 00:36:46 +00002215 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002216
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002217 // Build _objc_method_list for class's methods if needed
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002218 Result += "\nstatic struct _objc_method_list _OBJC_";
2219 Result += prefix;
2220 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2221 Result += "_METHODS_";
2222 Result += ClassName;
2223 Result += " __attribute__ ((section (\"__OBJC, __";
2224 Result += IsInstanceMethod ? "inst" : "cls";
2225 Result += "_meth\")))= ";
2226 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002227
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002228 Result += "\t,{{(SEL)\"";
2229 Result += (*MethodBegin)->getSelector().getName().c_str();
2230 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002231 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002232 Result += "\", \"";
2233 Result += MethodTypeString;
2234 Result += "\", ";
2235 Result += MethodInternalNames[*MethodBegin];
2236 Result += "}\n";
2237 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2238 Result += "\t ,{(SEL)\"";
2239 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002240 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002241 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002242 Result += "\", \"";
2243 Result += MethodTypeString;
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002244 Result += "\", ";
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002245 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianbd2fd922007-11-13 21:02:00 +00002246 Result += "}\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002247 }
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002248 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002249}
2250
Ted Kremenek42730c52008-01-07 19:49:32 +00002251/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2252void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002253 int NumProtocols,
2254 const char *prefix,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002255 const char *ClassName,
2256 std::string &Result) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002257 static bool objc_protocol_methods = false;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002258 if (NumProtocols > 0) {
Fariborz Jahanian04455192007-10-22 21:41:37 +00002259 for (int i = 0; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002260 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahanian04455192007-10-22 21:41:37 +00002261 // Output struct protocol_methods holder of method selector and type.
2262 if (!objc_protocol_methods &&
2263 (PDecl->getNumInstanceMethods() > 0
2264 || PDecl->getNumClassMethods() > 0)) {
2265 /* struct protocol_methods {
2266 SEL _cmd;
2267 char *method_types;
2268 }
2269 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002270 Result += "\nstruct protocol_methods {\n";
2271 Result += "\tSEL _cmd;\n";
2272 Result += "\tchar *method_types;\n";
2273 Result += "};\n";
2274
2275 /* struct _objc_protocol_method_list {
2276 int protocol_method_count;
2277 struct protocol_methods protocols[];
2278 }
2279 */
2280 Result += "\nstruct _objc_protocol_method_list {\n";
2281 Result += "\tint protocol_method_count;\n";
2282 Result += "\tstruct protocol_methods protocols[];\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002283 objc_protocol_methods = true;
2284 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002285
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002286 int NumMethods = PDecl->getNumInstanceMethods();
2287 if(NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002288 Result += "\nstatic struct _objc_protocol_method_list "
2289 "_OBJC_PROTOCOL_INSTANCE_METHODS_";
2290 Result += PDecl->getName();
2291 Result += " __attribute__ ((section (\"__OBJC, __cat_inst_meth\")))= "
2292 "{\n\t" + utostr(NumMethods) + "\n";
2293
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002294 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002295 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002296 E = PDecl->instmeth_end(); I != E; ++I) {
2297 if (I == PDecl->instmeth_begin())
2298 Result += "\t ,{{(SEL)\"";
2299 else
2300 Result += "\t ,{(SEL)\"";
2301 Result += (*I)->getSelector().getName().c_str();
2302 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002303 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianbe63dd52007-12-17 17:56:10 +00002304 Result += "\", \"";
2305 Result += MethodTypeString;
2306 Result += "\"}\n";
2307 }
2308 Result += "\t }\n};\n";
2309 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002310
2311 // Output class methods declared in this protocol.
2312 NumMethods = PDecl->getNumClassMethods();
2313 if (NumMethods > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002314 Result += "\nstatic struct _objc_protocol_method_list "
2315 "_OBJC_PROTOCOL_CLASS_METHODS_";
2316 Result += PDecl->getName();
2317 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2318 "{\n\t";
2319 Result += utostr(NumMethods);
2320 Result += "\n";
2321
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002322 // Output instance methods declared in this protocol.
Ted Kremenek42730c52008-01-07 19:49:32 +00002323 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanian65a3d852007-12-17 18:07:01 +00002324 E = PDecl->classmeth_end(); I != E; ++I) {
2325 if (I == PDecl->classmeth_begin())
2326 Result += "\t ,{{(SEL)\"";
2327 else
2328 Result += "\t ,{(SEL)\"";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002329 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002330 std::string MethodTypeString;
Ted Kremenek42730c52008-01-07 19:49:32 +00002331 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianc81f3162007-10-29 22:57:28 +00002332 Result += "\", \"";
2333 Result += MethodTypeString;
2334 Result += "\"}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002335 }
2336 Result += "\t }\n};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002337 }
2338 // Output:
2339 /* struct _objc_protocol {
2340 // Objective-C 1.0 extensions
2341 struct _objc_protocol_extension *isa;
2342 char *protocol_name;
2343 struct _objc_protocol **protocol_list;
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002344 struct _objc_protocol_method_list *instance_methods;
2345 struct _objc_protocol_method_list *class_methods;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002346 };
2347 */
2348 static bool objc_protocol = false;
2349 if (!objc_protocol) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002350 Result += "\nstruct _objc_protocol {\n";
2351 Result += "\tstruct _objc_protocol_extension *isa;\n";
2352 Result += "\tchar *protocol_name;\n";
2353 Result += "\tstruct _objc_protocol **protocol_list;\n";
2354 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2355 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2356 Result += "};\n";
2357
2358 /* struct _objc_protocol_list {
2359 struct _objc_protocol_list *next;
2360 int protocol_count;
2361 struct _objc_protocol *class_protocols[];
2362 }
2363 */
2364 Result += "\nstruct _objc_protocol_list {\n";
2365 Result += "\tstruct _objc_protocol_list *next;\n";
2366 Result += "\tint protocol_count;\n";
2367 Result += "\tstruct _objc_protocol *class_protocols[];\n";
2368 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002369 objc_protocol = true;
2370 }
2371
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002372 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2373 Result += PDecl->getName();
2374 Result += " __attribute__ ((section (\"__OBJC, __protocol\")))= "
2375 "{\n\t0, \"";
2376 Result += PDecl->getName();
2377 Result += "\", 0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002378 if (PDecl->getNumInstanceMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002379 Result += "&_OBJC_PROTOCOL_INSTANCE_METHODS_";
2380 Result += PDecl->getName();
2381 Result += ", ";
2382 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002383 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002384 Result += "0, ";
Steve Naroff2ce399a2007-12-14 23:37:57 +00002385 if (PDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002386 Result += "&_OBJC_PROTOCOL_CLASS_METHODS_";
2387 Result += PDecl->getName();
2388 Result += "\n";
2389 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002390 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002391 Result += "0\n";
2392 Result += "};\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002393 }
Fariborz Jahanian04455192007-10-22 21:41:37 +00002394 // Output the top lovel protocol meta-data for the class.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002395 Result += "\nstatic struct _objc_protocol_list _OBJC_";
2396 Result += prefix;
2397 Result += "_PROTOCOLS_";
2398 Result += ClassName;
2399 Result += " __attribute__ ((section (\"__OBJC, __cat_cls_meth\")))= "
2400 "{\n\t0, ";
2401 Result += utostr(NumProtocols);
2402 Result += "\n";
2403
2404 Result += "\t,{&_OBJC_PROTOCOL_";
2405 Result += Protocols[0]->getName();
2406 Result += " \n";
2407
2408 for (int i = 1; i < NumProtocols; i++) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002409 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002410 Result += "\t ,&_OBJC_PROTOCOL_";
2411 Result += PDecl->getName();
2412 Result += "\n";
Fariborz Jahanian04455192007-10-22 21:41:37 +00002413 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002414 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002415 }
2416}
2417
Ted Kremenek42730c52008-01-07 19:49:32 +00002418/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002419/// implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002420void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002421 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002422 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002423 // Find category declaration for this implementation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002424 ObjCCategoryDecl *CDecl;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002425 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2426 CDecl = CDecl->getNextClassCategory())
2427 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2428 break;
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002429
Chris Lattnera661a4d2007-12-23 01:40:15 +00002430 std::string FullCategoryName = ClassDecl->getName();
2431 FullCategoryName += '_';
2432 FullCategoryName += IDecl->getName();
2433
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002434 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002435 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002436 true, "CATEGORY_", FullCategoryName.c_str(),
2437 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002438
2439 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002440 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnera661a4d2007-12-23 01:40:15 +00002441 false, "CATEGORY_", FullCategoryName.c_str(),
2442 Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002443
2444 // Protocols referenced in class declaration?
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002445 // Null CDecl is case of a category implementation with no category interface
2446 if (CDecl)
Ted Kremenek42730c52008-01-07 19:49:32 +00002447 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002448 CDecl->getNumReferencedProtocols(),
2449 "CATEGORY",
Chris Lattnera661a4d2007-12-23 01:40:15 +00002450 FullCategoryName.c_str(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002451
2452 /* struct _objc_category {
2453 char *category_name;
2454 char *class_name;
2455 struct _objc_method_list *instance_methods;
2456 struct _objc_method_list *class_methods;
2457 struct _objc_protocol_list *protocols;
2458 // Objective-C 1.0 extensions
2459 uint32_t size; // sizeof (struct _objc_category)
2460 struct _objc_property_list *instance_properties; // category's own
2461 // @property decl.
2462 };
2463 */
2464
2465 static bool objc_category = false;
2466 if (!objc_category) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002467 Result += "\nstruct _objc_category {\n";
2468 Result += "\tchar *category_name;\n";
2469 Result += "\tchar *class_name;\n";
2470 Result += "\tstruct _objc_method_list *instance_methods;\n";
2471 Result += "\tstruct _objc_method_list *class_methods;\n";
2472 Result += "\tstruct _objc_protocol_list *protocols;\n";
2473 Result += "\tunsigned int size;\n";
2474 Result += "\tstruct _objc_property_list *instance_properties;\n";
2475 Result += "};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002476 objc_category = true;
Fariborz Jahanian04455192007-10-22 21:41:37 +00002477 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002478 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2479 Result += FullCategoryName;
2480 Result += " __attribute__ ((section (\"__OBJC, __category\")))= {\n\t\"";
2481 Result += IDecl->getName();
2482 Result += "\"\n\t, \"";
2483 Result += ClassDecl->getName();
2484 Result += "\"\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002485
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002486 if (IDecl->getNumInstanceMethods() > 0) {
2487 Result += "\t, (struct _objc_method_list *)"
2488 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2489 Result += FullCategoryName;
2490 Result += "\n";
2491 }
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002492 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002493 Result += "\t, 0\n";
2494 if (IDecl->getNumClassMethods() > 0) {
2495 Result += "\t, (struct _objc_method_list *)"
2496 "&_OBJC_CATEGORY_CLASS_METHODS_";
2497 Result += FullCategoryName;
2498 Result += "\n";
2499 }
2500 else
2501 Result += "\t, 0\n";
2502
Fariborz Jahaniand256e062007-11-13 22:09:49 +00002503 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002504 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2505 Result += FullCategoryName;
2506 Result += "\n";
2507 }
2508 else
2509 Result += "\t, 0\n";
2510 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002511}
2512
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002513/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2514/// ivar offset.
Ted Kremenek42730c52008-01-07 19:49:32 +00002515void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2516 ObjCIvarDecl *ivar,
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002517 std::string &Result) {
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002518 Result += "offsetof(struct ";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002519 Result += IDecl->getName();
2520 Result += ", ";
2521 Result += ivar->getName();
2522 Result += ")";
2523}
2524
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002525//===----------------------------------------------------------------------===//
2526// Meta Data Emission
2527//===----------------------------------------------------------------------===//
2528
Ted Kremenek42730c52008-01-07 19:49:32 +00002529void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002530 std::string &Result) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002531 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002532
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002533 // Explictly declared @interface's are already synthesized.
2534 if (CDecl->ImplicitInterfaceDecl()) {
2535 // FIXME: Implementation of a class with no @interface (legacy) doese not
2536 // produce correct synthesis as yet.
Ted Kremenek42730c52008-01-07 19:49:32 +00002537 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian7e216522007-11-26 20:59:57 +00002538 }
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002539
Chris Lattnerc7b06752007-12-12 07:56:42 +00002540 // Build _objc_ivar_list metadata for classes ivars if needed
2541 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2542 ? IDecl->getImplDeclNumIvars()
2543 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002544 if (NumIvars > 0) {
2545 static bool objc_ivar = false;
2546 if (!objc_ivar) {
2547 /* struct _objc_ivar {
2548 char *ivar_name;
2549 char *ivar_type;
2550 int ivar_offset;
2551 };
2552 */
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002553 Result += "\nstruct _objc_ivar {\n";
2554 Result += "\tchar *ivar_name;\n";
2555 Result += "\tchar *ivar_type;\n";
2556 Result += "\tint ivar_offset;\n";
2557 Result += "};\n";
2558
2559 /* struct _objc_ivar_list {
2560 int ivar_count;
2561 struct _objc_ivar ivar_list[];
2562 };
2563 */
2564 Result += "\nstruct _objc_ivar_list {\n";
2565 Result += "\tint ivar_count;\n";
2566 Result += "\tstruct _objc_ivar ivar_list[];\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002567 objc_ivar = true;
2568 }
2569
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002570 Result += "\nstatic struct _objc_ivar_list _OBJC_INSTANCE_VARIABLES_";
2571 Result += IDecl->getName();
2572 Result += " __attribute__ ((section (\"__OBJC, __instance_vars\")))= "
2573 "{\n\t";
2574 Result += utostr(NumIvars);
2575 Result += "\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002576
Ted Kremenek42730c52008-01-07 19:49:32 +00002577 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerc7b06752007-12-12 07:56:42 +00002578 if (IDecl->getImplDeclNumIvars() > 0) {
2579 IVI = IDecl->ivar_begin();
2580 IVE = IDecl->ivar_end();
2581 } else {
2582 IVI = CDecl->ivar_begin();
2583 IVE = CDecl->ivar_end();
2584 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002585 Result += "\t,{{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002586 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002587 Result += "\", \"";
2588 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002589 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2590 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002591 Result += StrEncoding;
2592 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002593 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002594 Result += "}\n";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002595 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002596 Result += "\t ,{\"";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002597 Result += (*IVI)->getName();
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002598 Result += "\", \"";
2599 std::string StrEncoding;
Fariborz Jahanian248db262008-01-22 22:44:46 +00002600 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2601 EncodingRecordTypes);
Fariborz Jahaniand5ea4612007-10-29 17:16:25 +00002602 Result += StrEncoding;
2603 Result += "\", ";
Chris Lattnerc7b06752007-12-12 07:56:42 +00002604 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002605 Result += "}\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002606 }
2607
2608 Result += "\t }\n};\n";
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002609 }
2610
2611 // Build _objc_method_list for class's instance methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002612 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002613 true, "", IDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002614
2615 // Build _objc_method_list for class's class methods if needed
Ted Kremenek42730c52008-01-07 19:49:32 +00002616 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002617 false, "", IDecl->getName(), Result);
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002618
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002619 // Protocols referenced in class declaration?
Ted Kremenek42730c52008-01-07 19:49:32 +00002620 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002621 CDecl->getNumIntfRefProtocols(),
Chris Lattnerdea5bec2007-12-12 07:46:12 +00002622 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002623
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002624
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002625 // Declaration of class/meta-class metadata
2626 /* struct _objc_class {
2627 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002628 const char *super_class_name;
2629 char *name;
2630 long version;
2631 long info;
2632 long instance_size;
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002633 struct _objc_ivar_list *ivars;
2634 struct _objc_method_list *methods;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002635 struct objc_cache *cache;
2636 struct objc_protocol_list *protocols;
2637 const char *ivar_layout;
2638 struct _objc_class_ext *ext;
2639 };
2640 */
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002641 static bool objc_class = false;
2642 if (!objc_class) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002643 Result += "\nstruct _objc_class {\n";
2644 Result += "\tstruct _objc_class *isa;\n";
2645 Result += "\tconst char *super_class_name;\n";
2646 Result += "\tchar *name;\n";
2647 Result += "\tlong version;\n";
2648 Result += "\tlong info;\n";
2649 Result += "\tlong instance_size;\n";
2650 Result += "\tstruct _objc_ivar_list *ivars;\n";
2651 Result += "\tstruct _objc_method_list *methods;\n";
2652 Result += "\tstruct objc_cache *cache;\n";
2653 Result += "\tstruct _objc_protocol_list *protocols;\n";
2654 Result += "\tconst char *ivar_layout;\n";
2655 Result += "\tstruct _objc_class_ext *ext;\n";
2656 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002657 objc_class = true;
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002658 }
2659
2660 // Meta-class metadata generation.
Ted Kremenek42730c52008-01-07 19:49:32 +00002661 ObjCInterfaceDecl *RootClass = 0;
2662 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002663 while (SuperClass) {
2664 RootClass = SuperClass;
2665 SuperClass = SuperClass->getSuperClass();
2666 }
2667 SuperClass = CDecl->getSuperClass();
2668
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002669 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2670 Result += CDecl->getName();
2671 Result += " __attribute__ ((section (\"__OBJC, __meta_class\")))= "
2672 "{\n\t(struct _objc_class *)\"";
2673 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2674 Result += "\"";
2675
2676 if (SuperClass) {
2677 Result += ", \"";
2678 Result += SuperClass->getName();
2679 Result += "\", \"";
2680 Result += CDecl->getName();
2681 Result += "\"";
2682 }
2683 else {
2684 Result += ", 0, \"";
2685 Result += CDecl->getName();
2686 Result += "\"";
2687 }
Ted Kremenek42730c52008-01-07 19:49:32 +00002688 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002689 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002690 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffbde81042007-12-05 21:49:40 +00002691 if (IDecl->getNumClassMethods() > 0) {
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002692 Result += "\n\t, &_OBJC_CLASS_METHODS_";
Steve Naroffbde81042007-12-05 21:49:40 +00002693 Result += IDecl->getName();
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002694 Result += "\n";
2695 }
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002696 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002697 Result += ", 0\n";
2698 if (CDecl->getNumIntfRefProtocols() > 0) {
2699 Result += "\t,0, &_OBJC_CLASS_PROTOCOLS_";
2700 Result += CDecl->getName();
2701 Result += ",0,0\n";
2702 }
Fariborz Jahanian0cb4d922007-10-24 20:54:23 +00002703 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002704 Result += "\t,0,0,0,0\n";
2705 Result += "};\n";
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002706
2707 // class metadata generation.
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002708 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2709 Result += CDecl->getName();
2710 Result += " __attribute__ ((section (\"__OBJC, __class\")))= "
2711 "{\n\t&_OBJC_METACLASS_";
2712 Result += CDecl->getName();
2713 if (SuperClass) {
2714 Result += ", \"";
2715 Result += SuperClass->getName();
2716 Result += "\", \"";
2717 Result += CDecl->getName();
2718 Result += "\"";
2719 }
2720 else {
2721 Result += ", 0, \"";
2722 Result += CDecl->getName();
2723 Result += "\"";
2724 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002725 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002726 Result += ", 0,1";
Ted Kremenek42730c52008-01-07 19:49:32 +00002727 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002728 Result += ",0";
2729 else {
2730 // class has size. Must synthesize its size.
Fariborz Jahanian9447e462007-11-05 17:47:33 +00002731 Result += ",sizeof(struct ";
Fariborz Jahanianab3ec252007-10-26 23:09:28 +00002732 Result += CDecl->getName();
2733 Result += ")";
2734 }
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002735 if (NumIvars > 0) {
2736 Result += ", &_OBJC_INSTANCE_VARIABLES_";
2737 Result += CDecl->getName();
2738 Result += "\n\t";
2739 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002740 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002741 Result += ",0";
2742 if (IDecl->getNumInstanceMethods() > 0) {
2743 Result += ", &_OBJC_INSTANCE_METHODS_";
2744 Result += CDecl->getName();
2745 Result += ", 0\n\t";
2746 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002747 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002748 Result += ",0,0";
2749 if (CDecl->getNumIntfRefProtocols() > 0) {
2750 Result += ", &_OBJC_CLASS_PROTOCOLS_";
2751 Result += CDecl->getName();
2752 Result += ", 0,0\n";
2753 }
Fariborz Jahanianf8fa1e72007-10-23 18:53:48 +00002754 else
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002755 Result += ",0,0,0\n";
2756 Result += "};\n";
Fariborz Jahanian0f013d12007-10-23 00:02:02 +00002757}
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002758
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002759/// RewriteImplementations - This routine rewrites all method implementations
2760/// and emits meta-data.
2761
2762void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002763 int ClsDefCount = ClassImplementation.size();
2764 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002765
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002766 if (ClsDefCount == 0 && CatDefCount == 0)
2767 return;
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002768 // Rewrite implemented methods
2769 for (int i = 0; i < ClsDefCount; i++)
2770 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002771
Fariborz Jahanian0136e372007-11-13 20:04:28 +00002772 for (int i = 0; i < CatDefCount; i++)
2773 RewriteImplementationDecl(CategoryImplementation[i]);
2774
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002775 // This is needed for use of offsetof
2776 Result += "#include <stddef.h>\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002777
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002778 // For each implemented class, write out all its meta data.
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002779 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002780 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian9b4e4ff2007-10-24 19:23:36 +00002781
2782 // For each implemented category, write out all its meta data.
2783 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek42730c52008-01-07 19:49:32 +00002784 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanian45d52f72007-10-18 22:09:03 +00002785
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002786 // Write objc_symtab metadata
2787 /*
2788 struct _objc_symtab
2789 {
2790 long sel_ref_cnt;
2791 SEL *refs;
2792 short cls_def_cnt;
2793 short cat_def_cnt;
2794 void *defs[cls_def_cnt + cat_def_cnt];
2795 };
2796 */
2797
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002798 Result += "\nstruct _objc_symtab {\n";
2799 Result += "\tlong sel_ref_cnt;\n";
2800 Result += "\tSEL *refs;\n";
2801 Result += "\tshort cls_def_cnt;\n";
2802 Result += "\tshort cat_def_cnt;\n";
2803 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2804 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002805
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002806 Result += "static struct _objc_symtab "
2807 "_OBJC_SYMBOLS __attribute__((section (\"__OBJC, __symbols\")))= {\n";
2808 Result += "\t0, 0, " + utostr(ClsDefCount)
2809 + ", " + utostr(CatDefCount) + "\n";
2810 for (int i = 0; i < ClsDefCount; i++) {
2811 Result += "\t,&_OBJC_CLASS_";
2812 Result += ClassImplementation[i]->getName();
2813 Result += "\n";
2814 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002815
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002816 for (int i = 0; i < CatDefCount; i++) {
2817 Result += "\t,&_OBJC_CATEGORY_";
2818 Result += CategoryImplementation[i]->getClassInterface()->getName();
2819 Result += "_";
2820 Result += CategoryImplementation[i]->getName();
2821 Result += "\n";
2822 }
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002823
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002824 Result += "};\n\n";
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002825
2826 // Write objc_module metadata
2827
2828 /*
2829 struct _objc_module {
2830 long version;
2831 long size;
2832 const char *name;
2833 struct _objc_symtab *symtab;
2834 }
2835 */
2836
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002837 Result += "\nstruct _objc_module {\n";
2838 Result += "\tlong version;\n";
2839 Result += "\tlong size;\n";
2840 Result += "\tconst char *name;\n";
2841 Result += "\tstruct _objc_symtab *symtab;\n";
2842 Result += "};\n\n";
2843 Result += "static struct _objc_module "
2844 "_OBJC_MODULES __attribute__ ((section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanianf185aef2007-10-26 19:46:17 +00002845 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2846 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahaniancf89c7e2007-10-25 20:55:25 +00002847 Result += "};\n\n";
Fariborz Jahanian8c664912007-11-13 19:21:13 +00002848
Fariborz Jahanian640a01f2007-10-18 19:23:00 +00002849}
Chris Lattner6fe8b272007-10-16 22:36:42 +00002850