blob: b500cf537a4a6114efccb571ac0ed16ea26af9dd [file] [log] [blame]
Chris Lattner77cd2a02007-10-11 00:43:27 +00001//===--- RewriteTest.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000018#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000019#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000021#include "clang/Lex/Lexer.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000022#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000023#include "llvm/ADT/SmallPtrSet.h"
Chris Lattner26de4652007-12-02 01:13:47 +000024#include "llvm/Support/MemoryBuffer.h"
Steve Naroff0113c9d2008-01-28 21:34:52 +000025#include "llvm/Support/CommandLine.h"
Steve Naroff874e2322007-11-15 10:28:18 +000026#include <sstream>
Chris Lattner77cd2a02007-10-11 00:43:27 +000027using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000028using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000029
Steve Naroff0113c9d2008-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 Lattner77cd2a02007-10-11 00:43:27 +000034namespace {
Chris Lattner8a12c272007-10-11 18:38:32 +000035 class RewriteTest : public ASTConsumer {
Chris Lattner2c64b7b2007-10-16 21:07:07 +000036 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000037 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000038 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000039 unsigned RewriteFailedDiag;
40
Chris Lattner01c57482007-10-17 22:35:30 +000041 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000042 SourceManager *SM;
Chris Lattner8a12c272007-10-11 18:38:32 +000043 unsigned MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000044 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000045 SourceLocation LastIncLoc;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
49 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
50 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000051 llvm::SmallVector<Stmt *, 32> Stmts;
52 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +000053 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
Steve Naroffebf2b562007-10-23 23:50:29 +000054
55 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000056 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000057 FunctionDecl *MsgSendStretFunctionDecl;
58 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000059 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000060 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000061 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000062 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000063 FunctionDecl *CFStringFunctionDecl;
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +000064 FunctionDecl *GetProtocolFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000065 FunctionDecl *SuperContructorFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000066
Steve Naroffbeaf2992007-11-03 11:27:19 +000067 // ObjC string constant support.
68 FileVarDecl *ConstantStringClassReference;
69 RecordDecl *NSStringRecord;
Steve Naroffab972d32007-11-04 22:37:50 +000070
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000071 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000072 int BcLabelCount;
73
Steve Naroff874e2322007-11-15 10:28:18 +000074 // Needed for super.
Ted Kremeneka526c5c2008-01-07 19:49:32 +000075 ObjCMethodDecl *CurMethodDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000076 RecordDecl *SuperStructDecl;
77
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +000078 // Needed for header files being rewritten
79 bool IsHeader;
80
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +000081 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +000082 public:
Chris Lattner9e13c2e2008-01-31 19:38:44 +000083 void Initialize(ASTContext &context);
84
Chris Lattner8a12c272007-10-11 18:38:32 +000085
Chris Lattnerf04da132007-10-24 17:06:59 +000086 // Top Level Driver code.
87 virtual void HandleTopLevelDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +000088 void HandleDeclInMainFile(Decl *D);
Steve Naroff4f943c22008-03-10 20:43:59 +000089 RewriteTest(bool isHeader, Diagnostic &D, const LangOptions &LOpts) :
90 Diags(D), LangOpts(LOpts) {
Steve Narofff69cc5d2008-01-30 19:17:43 +000091 IsHeader = isHeader;
Steve Naroff0113c9d2008-01-28 21:34:52 +000092 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
93 "rewriting sub-expression within a macro (may not be correct)");
Steve Narofff69cc5d2008-01-30 19:17:43 +000094 }
Chris Lattnerf04da132007-10-24 17:06:59 +000095 ~RewriteTest();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +000096
97 void ReplaceStmt(Stmt *Old, Stmt *New) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +000098 // If replacement succeeded or warning disabled return with no warning.
99 if (!Rewrite.ReplaceStmt(Old, New) || SilenceRewriteMacroWarning)
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000100 return;
101
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000102 SourceRange Range = Old->getSourceRange();
103 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag,
104 0, 0, &Range, 1);
105 }
106
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000107 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000108 // If insertion succeeded or warning disabled return with no warning.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000109 if (!Rewrite.InsertText(Loc, StrData, StrLen) ||
110 SilenceRewriteMacroWarning)
111 return;
112
113 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
114 }
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000115
Chris Lattneraadaf782008-01-31 19:51:04 +0000116 void RemoveText(SourceLocation Loc, unsigned StrLen) {
117 // If removal succeeded or warning disabled return with no warning.
118 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
119 return;
120
121 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
122 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000123
Chris Lattneraadaf782008-01-31 19:51:04 +0000124 void ReplaceText(SourceLocation Start, unsigned OrigLength,
125 const char *NewStr, unsigned NewLength) {
126 // If removal succeeded or warning disabled return with no warning.
127 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength) ||
128 SilenceRewriteMacroWarning)
129 return;
130
131 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
132 }
133
Chris Lattnerf04da132007-10-24 17:06:59 +0000134 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000135 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000136 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000137 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000138 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
139 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000140 void RewriteImplementationDecl(NamedDecl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000141 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
142 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
143 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
144 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
145 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
146 void RewriteProperties(int nProperties, ObjCPropertyDecl **Properties);
Steve Naroff09b266e2007-10-30 23:14:51 +0000147 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000148 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroffd5255f52007-11-01 13:24:47 +0000149 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000150 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000151 QualType getSuperStructType();
Chris Lattner311ff022007-10-16 22:36:42 +0000152
Chris Lattnerf04da132007-10-24 17:06:59 +0000153 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000154 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000155 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000156 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Steve Naroffb42f8412007-11-05 14:50:49 +0000157 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000158 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000159 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000160 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000161 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000162 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000163 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
164 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
165 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000166 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
167 SourceLocation OrigEnd);
Steve Naroff934f2762007-10-24 22:48:43 +0000168 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
169 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000170 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000171 Stmt *RewriteBreakStmt(BreakStmt *S);
172 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000173 void SynthCountByEnumWithState(std::string &buf);
174
Steve Naroff09b266e2007-10-30 23:14:51 +0000175 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000176 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000177 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000178 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000179 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000180 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000181 void SynthGetMetaClassFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000182 void SynthCFStringFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000183 void SynthSelGetUidFunctionDecl();
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000184 void SynthGetProtocolFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000185 void SynthSuperContructorFunctionDecl();
Steve Naroff96984642007-11-08 14:30:50 +0000186
Chris Lattnerf04da132007-10-24 17:06:59 +0000187 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000188 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000189 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000190
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000191 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000192 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000193
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000194 typedef ObjCCategoryImplDecl::instmeth_iterator instmeth_iterator;
195 void RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000196 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000197 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000198 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000199 const char *ClassName,
200 std::string &Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000201
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000202 void RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000203 int NumProtocols,
204 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000205 const char *ClassName,
206 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000207 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000208 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000209 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
210 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000211 std::string &Result);
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000212 void RewriteImplementations(std::string &Result);
Chris Lattner77cd2a02007-10-11 00:43:27 +0000213 };
214}
215
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000216static bool IsHeaderFile(const std::string &Filename) {
217 std::string::size_type DotPos = Filename.rfind('.');
218
219 if (DotPos == std::string::npos) {
220 // no file extension
221 return false;
222 }
223
224 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
225 // C header: .h
226 // C++ header: .hh or .H;
227 return Ext == "h" || Ext == "hh" || Ext == "H";
228}
229
230ASTConsumer *clang::CreateCodeRewriterTest(const std::string& InFile,
Steve Naroff4f943c22008-03-10 20:43:59 +0000231 Diagnostic &Diags,
232 const LangOptions &LOpts) {
233 return new RewriteTest(IsHeaderFile(InFile), Diags, LOpts);
Chris Lattnere365c502007-11-30 22:25:36 +0000234}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000235
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000236void RewriteTest::Initialize(ASTContext &context) {
237 Context = &context;
238 SM = &Context->getSourceManager();
239 MsgSendFunctionDecl = 0;
240 MsgSendSuperFunctionDecl = 0;
241 MsgSendStretFunctionDecl = 0;
242 MsgSendSuperStretFunctionDecl = 0;
243 MsgSendFpretFunctionDecl = 0;
244 GetClassFunctionDecl = 0;
245 GetMetaClassFunctionDecl = 0;
246 SelGetUidFunctionDecl = 0;
247 CFStringFunctionDecl = 0;
248 GetProtocolFunctionDecl = 0;
249 ConstantStringClassReference = 0;
250 NSStringRecord = 0;
251 CurMethodDecl = 0;
252 SuperStructDecl = 0;
253 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000254 SuperContructorFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000255
256 // Get the ID and start/end of the main file.
257 MainFileID = SM->getMainFileID();
258 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
259 MainFileStart = MainBuf->getBufferStart();
260 MainFileEnd = MainBuf->getBufferEnd();
261
262
263 Rewrite.setSourceMgr(Context->getSourceManager());
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000264
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000265 // declaring objc_selector outside the parameter list removes a silly
266 // scope related warning...
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000267 std::string S = "#pragma once\n";
268 S += "struct objc_selector; struct objc_class;\n";
269 S += "#ifndef OBJC_SUPER\n";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000270 S += "struct objc_super { struct objc_object *object; ";
271 S += "struct objc_object *superClass; ";
272 if (LangOpts.Microsoft) {
273 // Add a constructor for creating temporary objects.
274 S += "objc_super(struct objc_object *o, struct objc_object *s) : ";
275 S += "object(o), superClass(s) {} ";
276 }
277 S += "};\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000278 S += "#define OBJC_SUPER\n";
279 S += "#endif\n";
280 S += "#ifndef _REWRITER_typedef_Protocol\n";
281 S += "typedef struct objc_object Protocol;\n";
282 S += "#define _REWRITER_typedef_Protocol\n";
283 S += "#endif\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000284 if (LangOpts.Microsoft)
285 S += "extern \"C\" {\n";
286 S += "struct objc_object *objc_msgSend";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000287 S += "(struct objc_object *, struct objc_selector *, ...);\n";
288 S += "extern struct objc_object *objc_msgSendSuper";
289 S += "(struct objc_super *, struct objc_selector *, ...);\n";
290 S += "extern struct objc_object *objc_msgSend_stret";
291 S += "(struct objc_object *, struct objc_selector *, ...);\n";
292 S += "extern struct objc_object *objc_msgSendSuper_stret";
293 S += "(struct objc_super *, struct objc_selector *, ...);\n";
294 S += "extern struct objc_object *objc_msgSend_fpret";
295 S += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000296 S += "struct objc_object *objc_getClass";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000297 S += "(const char *);\n";
298 S += "extern struct objc_object *objc_getMetaClass";
299 S += "(const char *);\n";
300 S += "extern void objc_exception_throw(struct objc_object *);\n";
301 S += "extern void objc_exception_try_enter(void *);\n";
302 S += "extern void objc_exception_try_exit(void *);\n";
303 S += "extern struct objc_object *objc_exception_extract(void *);\n";
304 S += "extern int objc_exception_match";
305 S += "(struct objc_class *, struct objc_object *, ...);\n";
306 S += "extern Protocol *objc_getProtocol(const char *);\n";
Steve Naroff3c64d9e2008-03-12 13:19:12 +0000307 if (LangOpts.Microsoft)
308 S += "} // end extern \"C\"\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000309 S += "#include <objc/objc.h>\n";
310 S += "#ifndef __FASTENUMERATIONSTATE\n";
311 S += "struct __objcFastEnumerationState {\n\t";
312 S += "unsigned long state;\n\t";
313 S += "id *itemsPtr;\n\t";
314 S += "unsigned long *mutationsPtr;\n\t";
315 S += "unsigned long extra[5];\n};\n";
316 S += "#define __FASTENUMERATIONSTATE\n";
317 S += "#endif\n";
318#if 0
319 if (LangOpts.Microsoft)
Steve Naroff4f943c22008-03-10 20:43:59 +0000320 S += "#define __attribute__(X)\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000321#endif
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000322 if (IsHeader) {
323 // insert the whole string when rewriting a header file
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000324 InsertText(SourceLocation::getFileLoc(MainFileID, 0), S.c_str(), S.size());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000325 }
326 else {
327 // Not rewriting header, exclude the #pragma once pragma
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000328 const char *p = S.c_str() + strlen("#pragma once\n");
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000329 InsertText(SourceLocation::getFileLoc(MainFileID, 0), p, strlen(p));
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000330 }
331}
332
333
Chris Lattnerf04da132007-10-24 17:06:59 +0000334//===----------------------------------------------------------------------===//
335// Top Level Driver Code
336//===----------------------------------------------------------------------===//
337
Chris Lattner8a12c272007-10-11 18:38:32 +0000338void RewriteTest::HandleTopLevelDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000339 // Two cases: either the decl could be in the main file, or it could be in a
340 // #included file. If the former, rewrite it now. If the later, check to see
341 // if we rewrote the #include/#import.
342 SourceLocation Loc = D->getLocation();
343 Loc = SM->getLogicalLoc(Loc);
344
345 // If this is for a builtin, ignore it.
346 if (Loc.isInvalid()) return;
347
Steve Naroffebf2b562007-10-23 23:50:29 +0000348 // Look for built-in declarations that we need to refer during the rewrite.
349 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000350 RewriteFunctionDecl(FD);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000351 } else if (FileVarDecl *FVD = dyn_cast<FileVarDecl>(D)) {
352 // declared in <Foundation/NSString.h>
353 if (strcmp(FVD->getName(), "_NSConstantStringClassReference") == 0) {
354 ConstantStringClassReference = FVD;
355 return;
356 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000357 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000358 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000359 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000360 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000361 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000362 RewriteProtocolDecl(PD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000363 } else if (ObjCForwardProtocolDecl *FP =
364 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000365 RewriteForwardProtocolDecl(FP);
Steve Naroffebf2b562007-10-23 23:50:29 +0000366 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000367 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000368 if (SM->getDecomposedFileLoc(Loc).first == MainFileID)
369 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000370}
371
Chris Lattnerf04da132007-10-24 17:06:59 +0000372/// HandleDeclInMainFile - This is called for each top-level decl defined in the
373/// main file of the input.
374void RewriteTest::HandleDeclInMainFile(Decl *D) {
375 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
376 if (Stmt *Body = FD->getBody())
Steve Narofff3473a72007-11-09 15:20:18 +0000377 FD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Narofff69cc5d2008-01-30 19:17:43 +0000378
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000379 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Steve Naroff874e2322007-11-15 10:28:18 +0000380 if (Stmt *Body = MD->getBody()) {
381 //Body->dump();
382 CurMethodDecl = MD;
Steve Naroff71c0a952007-11-13 23:01:27 +0000383 MD->setBody(RewriteFunctionBodyOrGlobalInitializer(Body));
Steve Naroff874e2322007-11-15 10:28:18 +0000384 CurMethodDecl = 0;
385 }
Steve Naroff71c0a952007-11-13 23:01:27 +0000386 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000387 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000388 ClassImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000389 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000390 CategoryImplementation.push_back(CI);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000391 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
Chris Lattnerf04da132007-10-24 17:06:59 +0000392 RewriteForwardClassDecl(CD);
Steve Narofff3473a72007-11-09 15:20:18 +0000393 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000394 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Narofff3473a72007-11-09 15:20:18 +0000395 if (VD->getInit())
396 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
397 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000398 // Nothing yet.
399}
400
401RewriteTest::~RewriteTest() {
402 // Get the top-level buffer that this corresponds to.
Chris Lattner74a0c772007-11-08 04:27:23 +0000403
404 // Rewrite tabs if we care.
405 //RewriteTabs();
Chris Lattnerf04da132007-10-24 17:06:59 +0000406
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000407 RewriteInclude();
408
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000409 // Rewrite Objective-c meta data*
410 std::string ResultStr;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +0000411 RewriteImplementations(ResultStr);
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000412
Chris Lattnerf04da132007-10-24 17:06:59 +0000413 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
414 // we are done.
415 if (const RewriteBuffer *RewriteBuf =
416 Rewrite.getRewriteBufferFor(MainFileID)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000417 //printf("Changed:\n");
Chris Lattnerf04da132007-10-24 17:06:59 +0000418 std::string S(RewriteBuf->begin(), RewriteBuf->end());
419 printf("%s\n", S.c_str());
420 } else {
421 printf("No changes\n");
422 }
Fariborz Jahanian4402d812007-11-07 18:40:28 +0000423 // Emit metadata.
424 printf("%s", ResultStr.c_str());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000425}
426
Chris Lattnerf04da132007-10-24 17:06:59 +0000427//===----------------------------------------------------------------------===//
428// Syntactic (non-AST) Rewriting Code
429//===----------------------------------------------------------------------===//
430
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000431void RewriteTest::RewriteInclude() {
432 SourceLocation LocStart = SourceLocation::getFileLoc(MainFileID, 0);
433 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
434 const char *MainBufStart = MainBuf.first;
435 const char *MainBufEnd = MainBuf.second;
436 size_t ImportLen = strlen("import");
437 size_t IncludeLen = strlen("include");
438
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000439 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000440 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
441 if (*BufPtr == '#') {
442 if (++BufPtr == MainBufEnd)
443 return;
444 while (*BufPtr == ' ' || *BufPtr == '\t')
445 if (++BufPtr == MainBufEnd)
446 return;
447 if (!strncmp(BufPtr, "import", ImportLen)) {
448 // replace import with include
449 SourceLocation ImportLoc =
450 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000451 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000452 BufPtr += ImportLen;
453 }
454 }
455 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000456}
457
Chris Lattnerf04da132007-10-24 17:06:59 +0000458void RewriteTest::RewriteTabs() {
459 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
460 const char *MainBufStart = MainBuf.first;
461 const char *MainBufEnd = MainBuf.second;
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000462
Chris Lattnerf04da132007-10-24 17:06:59 +0000463 // Loop over the whole file, looking for tabs.
464 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
465 if (*BufPtr != '\t')
466 continue;
467
468 // Okay, we found a tab. This tab will turn into at least one character,
469 // but it depends on which 'virtual column' it is in. Compute that now.
470 unsigned VCol = 0;
471 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
472 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
473 ++VCol;
474
475 // Okay, now that we know the virtual column, we know how many spaces to
476 // insert. We assume 8-character tab-stops.
477 unsigned Spaces = 8-(VCol & 7);
478
479 // Get the location of the tab.
480 SourceLocation TabLoc =
481 SourceLocation::getFileLoc(MainFileID, BufPtr-MainBufStart);
482
483 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000484 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000485 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000486}
487
488
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000489void RewriteTest::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000490 int numDecls = ClassDecl->getNumForwardDecls();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000491 ObjCInterfaceDecl **ForwardDecls = ClassDecl->getForwardDecls();
Chris Lattnerf04da132007-10-24 17:06:59 +0000492
493 // Get the start location and compute the semi location.
494 SourceLocation startLoc = ClassDecl->getLocation();
495 const char *startBuf = SM->getCharacterData(startLoc);
496 const char *semiPtr = strchr(startBuf, ';');
497
498 // Translate to typedef's that forward reference structs with the same name
499 // as the class. As a convenience, we include the original declaration
500 // as a comment.
501 std::string typedefString;
502 typedefString += "// ";
Steve Naroff934f2762007-10-24 22:48:43 +0000503 typedefString.append(startBuf, semiPtr-startBuf+1);
504 typedefString += "\n";
505 for (int i = 0; i < numDecls; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000506 ObjCInterfaceDecl *ForwardDecl = ForwardDecls[i];
Steve Naroff32174822007-11-09 12:50:28 +0000507 typedefString += "#ifndef _REWRITER_typedef_";
508 typedefString += ForwardDecl->getName();
509 typedefString += "\n";
510 typedefString += "#define _REWRITER_typedef_";
511 typedefString += ForwardDecl->getName();
512 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000513 typedefString += "typedef struct objc_object ";
Steve Naroff934f2762007-10-24 22:48:43 +0000514 typedefString += ForwardDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000515 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000516 }
517
518 // Replace the @class with typedefs corresponding to the classes.
Chris Lattneraadaf782008-01-31 19:51:04 +0000519 ReplaceText(startLoc, semiPtr-startBuf+1,
520 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000521}
522
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000523void RewriteTest::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000524 SourceLocation LocStart = Method->getLocStart();
525 SourceLocation LocEnd = Method->getLocEnd();
Steve Naroff423cb562007-10-30 13:30:57 +0000526
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000527 if (SM->getLineNumber(LocEnd) > SM->getLineNumber(LocStart)) {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000528 InsertText(LocStart, "/* ", 3);
Chris Lattneraadaf782008-01-31 19:51:04 +0000529 ReplaceText(LocEnd, 1, ";*/ ", 4);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000530 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000531 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000532 }
533}
534
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000535void RewriteTest::RewriteProperties(int nProperties, ObjCPropertyDecl **Properties)
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000536{
537 for (int i = 0; i < nProperties; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000538 ObjCPropertyDecl *Property = Properties[i];
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000539 SourceLocation Loc = Property->getLocation();
540
Chris Lattneraadaf782008-01-31 19:51:04 +0000541 ReplaceText(Loc, 0, "// ", 3);
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000542
543 // FIXME: handle properties that are declared across multiple lines.
544 }
545}
546
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000547void RewriteTest::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000548 SourceLocation LocStart = CatDecl->getLocStart();
549
550 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000551 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000552
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000553 for (ObjCCategoryDecl::instmeth_iterator I = CatDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000554 E = CatDecl->instmeth_end(); I != E; ++I)
555 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000556 for (ObjCCategoryDecl::classmeth_iterator I = CatDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000557 E = CatDecl->classmeth_end(); I != E; ++I)
558 RewriteMethodDeclaration(*I);
559
Steve Naroff423cb562007-10-30 13:30:57 +0000560 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000561 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000562}
563
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000564void RewriteTest::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000565 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000566
Steve Naroff752d6ef2007-10-30 16:42:30 +0000567 SourceLocation LocStart = PDecl->getLocStart();
568
569 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000570 ReplaceText(LocStart, 0, "// ", 3);
Steve Naroff752d6ef2007-10-30 16:42:30 +0000571
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000572 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000573 E = PDecl->instmeth_end(); I != E; ++I)
574 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000575 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000576 E = PDecl->classmeth_end(); I != E; ++I)
577 RewriteMethodDeclaration(*I);
578
Steve Naroff752d6ef2007-10-30 16:42:30 +0000579 // Lastly, comment out the @end.
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000580 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattneraadaf782008-01-31 19:51:04 +0000581 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000582
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000583 // Must comment out @optional/@required
584 const char *startBuf = SM->getCharacterData(LocStart);
585 const char *endBuf = SM->getCharacterData(LocEnd);
586 for (const char *p = startBuf; p < endBuf; p++) {
587 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
588 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000589 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000590 ReplaceText(OptionalLoc, strlen("@optional"),
591 CommentedOptional.c_str(), CommentedOptional.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000592
593 }
594 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
595 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000596 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000597 ReplaceText(OptionalLoc, strlen("@required"),
598 CommentedRequired.c_str(), CommentedRequired.size());
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000599
600 }
601 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000602}
603
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000604void RewriteTest::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000605 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000606 if (LocStart.isInvalid())
607 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000608 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000609 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000610}
611
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000612void RewriteTest::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000613 std::string &ResultStr) {
614 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000615 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000616 ResultStr += "id";
617 else
618 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000619 ResultStr += " ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000620
621 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000622 std::string NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000623
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000624 if (OMD->isInstance())
625 NameStr += "_I_";
626 else
627 NameStr += "_C_";
628
629 NameStr += OMD->getClassInterface()->getName();
630 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000631
632 NamedDecl *MethodContext = OMD->getMethodContext();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000633 if (ObjCCategoryImplDecl *CID =
634 dyn_cast<ObjCCategoryImplDecl>(MethodContext)) {
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000635 NameStr += CID->getName();
636 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000637 }
638 // Append selector names, replacing ':' with '_'
639 const char *selName = OMD->getSelector().getName().c_str();
640 if (!strchr(selName, ':'))
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000641 NameStr += OMD->getSelector().getName();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000642 else {
643 std::string selString = OMD->getSelector().getName();
644 int len = selString.size();
645 for (int i = 0; i < len; i++)
646 if (selString[i] == ':')
647 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000648 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000649 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000650 // Remember this name for metadata emission
651 MethodInternalNames[OMD] = NameStr;
652 ResultStr += NameStr;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000653
654 // Rewrite arguments
655 ResultStr += "(";
656
657 // invisible arguments
658 if (OMD->isInstance()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000659 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000660 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000661 if (!LangOpts.Microsoft) {
662 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
663 ResultStr += "struct ";
664 }
665 // When rewriting for Microsoft, explicitly omit the structure name.
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000666 ResultStr += OMD->getClassInterface()->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000667 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000668 }
669 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000670 ResultStr += Context->getObjCIdType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000671
672 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000673 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000674 ResultStr += " _cmd";
675
676 // Method arguments.
677 for (int i = 0; i < OMD->getNumParams(); i++) {
678 ParmVarDecl *PDecl = OMD->getParamDecl(i);
679 ResultStr += ", ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000680 if (PDecl->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000681 ResultStr += "id";
682 else
683 ResultStr += PDecl->getType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000684 ResultStr += " ";
685 ResultStr += PDecl->getName();
686 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +0000687 if (OMD->isVariadic())
688 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000689 ResultStr += ") ";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000690
691}
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000692void RewriteTest::RewriteImplementationDecl(NamedDecl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000693 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
694 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000695
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000696 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000697 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000698 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000699 InsertText(CID->getLocStart(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000700
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000701 for (ObjCCategoryImplDecl::instmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000702 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
703 E = IMD ? IMD->instmeth_end() : CID->instmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000704 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000705 ObjCMethodDecl *OMD = *I;
706 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000707 SourceLocation LocStart = OMD->getLocStart();
708 SourceLocation LocEnd = OMD->getBody()->getLocStart();
709
710 const char *startBuf = SM->getCharacterData(LocStart);
711 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000712 ReplaceText(LocStart, endBuf-startBuf,
713 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000714 }
715
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 for (ObjCCategoryImplDecl::classmeth_iterator
Chris Lattnerab4c4d52007-12-12 07:46:12 +0000717 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
718 E = IMD ? IMD->classmeth_end() : CID->classmeth_end(); I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000719 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000720 ObjCMethodDecl *OMD = *I;
721 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000722 SourceLocation LocStart = OMD->getLocStart();
723 SourceLocation LocEnd = OMD->getBody()->getLocStart();
724
725 const char *startBuf = SM->getCharacterData(LocStart);
726 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +0000727 ReplaceText(LocStart, endBuf-startBuf,
728 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000729 }
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000730 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000731 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +0000732 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000733 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000734}
735
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000736void RewriteTest::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +0000737 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000738 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000739 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +0000740 ResultStr = "#ifndef _REWRITER_typedef_";
Steve Naroff32174822007-11-09 12:50:28 +0000741 ResultStr += ClassDecl->getName();
742 ResultStr += "\n";
743 ResultStr += "#define _REWRITER_typedef_";
744 ResultStr += ClassDecl->getName();
745 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000746 ResultStr += "typedef struct objc_object ";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000747 ResultStr += ClassDecl->getName();
Steve Naroff32174822007-11-09 12:50:28 +0000748 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000749 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000750 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +0000751 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000752 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Steve Narofff908a872007-10-30 02:23:23 +0000753
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000754 RewriteProperties(ClassDecl->getNumPropertyDecl(),
755 ClassDecl->getPropertyDecl());
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000756 for (ObjCInterfaceDecl::instmeth_iterator I = ClassDecl->instmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000757 E = ClassDecl->instmeth_end(); I != E; ++I)
758 RewriteMethodDeclaration(*I);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000759 for (ObjCInterfaceDecl::classmeth_iterator I = ClassDecl->classmeth_begin(),
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000760 E = ClassDecl->classmeth_end(); I != E; ++I)
761 RewriteMethodDeclaration(*I);
762
Steve Naroff2feac5e2007-10-30 03:43:13 +0000763 // Lastly, comment out the @end.
Chris Lattneraadaf782008-01-31 19:51:04 +0000764 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +0000765}
766
Steve Naroff05b8c782008-03-12 00:25:36 +0000767/// FIXME: Investigate the following comment...
768/// This code is not right. It seems unnecessary. It breaks use of
769/// ivar reference used as 'receiver' of an expression; as in:
770/// [newInv->_container addObject:0];
Steve Naroff7e3411b2007-11-15 02:58:25 +0000771Stmt *RewriteTest::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000772 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff05b8c782008-03-12 00:25:36 +0000773 if (CurMethodDecl) {
774 if (const PointerType *pType = IV->getBase()->getType()->getAsPointerType()) {
775 ObjCInterfaceType *intT = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
776 if (CurMethodDecl->getClassInterface() == intT->getDecl()) {
Steve Naroff39bbd9f2008-03-12 21:09:20 +0000777 // lookup which class implements the instance variable.
778 ObjCInterfaceDecl *clsDeclared = 0;
779 intT->getDecl()->lookupInstanceVariable(D->getIdentifier(), clsDeclared);
780 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
781 std::string RecName = clsDeclared->getIdentifier()->getName();
Steve Naroff05b8c782008-03-12 00:25:36 +0000782 RecName += "_IMPL";
783 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
784 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(), II, 0);
785 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
786 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
787 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
788 // Don't forget the parens to enforce the proper binding.
789 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
790 if (IV->isFreeIvar()) {
791 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
792 ReplaceStmt(IV, ME);
793 delete IV;
794 return ME;
795 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000796 ReplaceStmt(IV->getBase(), PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +0000797 delete IV->getBase();
798 return PE;
799 }
800 }
801 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000802 }
Steve Naroff05b8c782008-03-12 00:25:36 +0000803 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
804 IV->getLocation(), D->getType());
805 ReplaceStmt(IV, Replacement);
806 delete IV;
807 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000808}
809
Chris Lattnerf04da132007-10-24 17:06:59 +0000810//===----------------------------------------------------------------------===//
811// Function Body / Expression rewriting
812//===----------------------------------------------------------------------===//
813
Steve Narofff3473a72007-11-09 15:20:18 +0000814Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000815 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
816 isa<DoStmt>(S) || isa<ForStmt>(S))
817 Stmts.push_back(S);
818 else if (isa<ObjCForCollectionStmt>(S)) {
819 Stmts.push_back(S);
820 ObjCBcLabelNo.push_back(++BcLabelCount);
821 }
822
Chris Lattner338d1e22008-01-31 05:10:40 +0000823 SourceLocation OrigStmtEnd = S->getLocEnd();
824
825 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000826 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
827 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000828 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000829 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000830 if (newStmt)
831 *CI = newStmt;
832 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000833
834 // Handle specific things.
835 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
836 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000837
838 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
839 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000840
841 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
842 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000843
Steve Naroffbeaf2992007-11-03 11:27:19 +0000844 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
845 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000846
Steve Naroff934f2762007-10-24 22:48:43 +0000847 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
848 // Before we rewrite it, put the original message expression in a comment.
849 SourceLocation startLoc = MessExpr->getLocStart();
850 SourceLocation endLoc = MessExpr->getLocEnd();
851
852 const char *startBuf = SM->getCharacterData(startLoc);
853 const char *endBuf = SM->getCharacterData(endLoc);
854
855 std::string messString;
856 messString += "// ";
857 messString.append(startBuf, endBuf-startBuf+1);
858 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000859
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000860 // FIXME: Missing definition of
861 // InsertText(clang::SourceLocation, char const*, unsigned int).
862 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000863 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000864 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000865 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000866 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000867
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000868 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
869 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000870
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000871 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
872 return RewriteObjCSynchronizedStmt(StmtTry);
873
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000874 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
875 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000876
877 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
878 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000879
880 if (ObjCForCollectionStmt *StmtForCollection =
881 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000882 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000883 if (BreakStmt *StmtBreakStmt =
884 dyn_cast<BreakStmt>(S))
885 return RewriteBreakStmt(StmtBreakStmt);
886 if (ContinueStmt *StmtContinueStmt =
887 dyn_cast<ContinueStmt>(S))
888 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000889
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000890 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
891 isa<DoStmt>(S) || isa<ForStmt>(S)) {
892 assert(!Stmts.empty() && "Statement stack is empty");
893 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
894 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
895 && "Statement stack mismatch");
896 Stmts.pop_back();
897 }
Steve Naroff874e2322007-11-15 10:28:18 +0000898#if 0
899 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
900 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
901 // Get the new text.
902 std::ostringstream Buf;
903 Replacement->printPretty(Buf);
904 const std::string &Str = Buf.str();
905
906 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000907 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000908 delete S;
909 return Replacement;
910 }
911#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000912 // Return this stmt unmodified.
913 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000914}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000915
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000916/// SynthCountByEnumWithState - To print:
917/// ((unsigned int (*)
918/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
919/// (void *)objc_msgSend)((id)l_collection,
920/// sel_registerName(
921/// "countByEnumeratingWithState:objects:count:"),
922/// &enumState,
923/// (id *)items, (unsigned int)16)
924///
925void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
926 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
927 "id *, unsigned int))(void *)objc_msgSend)";
928 buf += "\n\t\t";
929 buf += "((id)l_collection,\n\t\t";
930 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
931 buf += "\n\t\t";
932 buf += "&enumState, "
933 "(id *)items, (unsigned int)16)";
934}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000935
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000936/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
937/// statement to exit to its outer synthesized loop.
938///
939Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
940 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
941 return S;
942 // replace break with goto __break_label
943 std::string buf;
944
945 SourceLocation startLoc = S->getLocStart();
946 buf = "goto __break_label_";
947 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000948 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000949
950 return 0;
951}
952
953/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
954/// statement to continue with its inner synthesized loop.
955///
956Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
957 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
958 return S;
959 // replace continue with goto __continue_label
960 std::string buf;
961
962 SourceLocation startLoc = S->getLocStart();
963 buf = "goto __continue_label_";
964 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000965 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000966
967 return 0;
968}
969
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000970/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000971/// It rewrites:
972/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000973
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000974/// Into:
975/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000976/// type elem;
977/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000978/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000979/// id l_collection = (id)collection;
980/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
981/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000982/// if (limit) {
983/// unsigned long startMutations = *enumState.mutationsPtr;
984/// do {
985/// unsigned long counter = 0;
986/// do {
987/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000988/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000989/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000990/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000991/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000992/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000993/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
994/// objects:items count:16]);
995/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000996/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000997/// }
998/// else
999/// elem = nil;
1000/// }
1001///
Chris Lattner338d1e22008-01-31 05:10:40 +00001002Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1003 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001004 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1005 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1006 "ObjCForCollectionStmt Statement stack mismatch");
1007 assert(!ObjCBcLabelNo.empty() &&
1008 "ObjCForCollectionStmt - Label No stack empty");
1009
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001010 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001011 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001012 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001013 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001014 std::string buf;
1015 buf = "\n{\n\t";
1016 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1017 // type elem;
1018 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001019 elementTypeAsString = ElementType.getAsString();
1020 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001021 buf += " ";
1022 elementName = DS->getDecl()->getName();
1023 buf += elementName;
1024 buf += ";\n\t";
1025 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001026 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001027 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001028 elementTypeAsString = DR->getDecl()->getType().getAsString();
1029 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001030 else
1031 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1032
1033 // struct __objcFastEnumerationState enumState = { 0 };
1034 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1035 // id items[16];
1036 buf += "id items[16];\n\t";
1037 // id l_collection = (id)
1038 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001039 // Find start location of 'collection' the hard way!
1040 const char *startCollectionBuf = startBuf;
1041 startCollectionBuf += 3; // skip 'for'
1042 startCollectionBuf = strchr(startCollectionBuf, '(');
1043 startCollectionBuf++; // skip '('
1044 // find 'in' and skip it.
1045 while (*startCollectionBuf != ' ' ||
1046 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1047 (*(startCollectionBuf+3) != ' ' &&
1048 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1049 startCollectionBuf++;
1050 startCollectionBuf += 3;
1051
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001052 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001053 ReplaceText(startLoc, startCollectionBuf - startBuf,
1054 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001055 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001056 SourceLocation rightParenLoc = S->getRParenLoc();
1057 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1058 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001059 buf = ";\n\t";
1060
1061 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1062 // objects:items count:16];
1063 // which is synthesized into:
1064 // unsigned int limit =
1065 // ((unsigned int (*)
1066 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1067 // (void *)objc_msgSend)((id)l_collection,
1068 // sel_registerName(
1069 // "countByEnumeratingWithState:objects:count:"),
1070 // (struct __objcFastEnumerationState *)&state,
1071 // (id *)items, (unsigned int)16);
1072 buf += "unsigned long limit =\n\t\t";
1073 SynthCountByEnumWithState(buf);
1074 buf += ";\n\t";
1075 /// if (limit) {
1076 /// unsigned long startMutations = *enumState.mutationsPtr;
1077 /// do {
1078 /// unsigned long counter = 0;
1079 /// do {
1080 /// if (startMutations != *enumState.mutationsPtr)
1081 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001082 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001083 buf += "if (limit) {\n\t";
1084 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1085 buf += "do {\n\t\t";
1086 buf += "unsigned long counter = 0;\n\t\t";
1087 buf += "do {\n\t\t\t";
1088 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1089 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1090 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001091 buf += " = (";
1092 buf += elementTypeAsString;
1093 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001094 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001095 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001096
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001097 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001098 /// } while (counter < limit);
1099 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1100 /// objects:items count:16]);
1101 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001102 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001103 /// }
1104 /// else
1105 /// elem = nil;
1106 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001107 ///
1108 buf = ";\n\t";
1109 buf += "__continue_label_";
1110 buf += utostr(ObjCBcLabelNo.back());
1111 buf += ": ;";
1112 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001113 buf += "} while (counter < limit);\n\t";
1114 buf += "} while (limit = ";
1115 SynthCountByEnumWithState(buf);
1116 buf += ");\n\t";
1117 buf += elementName;
1118 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001119 buf += "__break_label_";
1120 buf += utostr(ObjCBcLabelNo.back());
1121 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001122 buf += "}\n\t";
1123 buf += "else\n\t\t";
1124 buf += elementName;
1125 buf += " = nil;\n";
1126 buf += "}\n";
1127 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001128 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001129 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001130 Stmts.pop_back();
1131 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001132 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001133}
1134
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001135/// RewriteObjCSynchronizedStmt -
1136/// This routine rewrites @synchronized(expr) stmt;
1137/// into:
1138/// objc_sync_enter(expr);
1139/// @try stmt @finally { objc_sync_exit(expr); }
1140///
1141Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1142 // Get the start location and compute the semi location.
1143 SourceLocation startLoc = S->getLocStart();
1144 const char *startBuf = SM->getCharacterData(startLoc);
1145
1146 assert((*startBuf == '@') && "bogus @synchronized location");
1147
1148 std::string buf;
1149 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001150 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001151 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1152 const char *endBuf = SM->getCharacterData(endLoc);
1153 endBuf++;
1154 const char *rparenBuf = strchr(endBuf, ')');
1155 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1156 buf = ");\n";
1157 // declare a new scope with two variables, _stack and _rethrow.
1158 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1159 buf += "int buf[18/*32-bit i386*/];\n";
1160 buf += "char *pointers[4];} _stack;\n";
1161 buf += "id volatile _rethrow = 0;\n";
1162 buf += "objc_exception_try_enter(&_stack);\n";
1163 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001164 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001165 startLoc = S->getSynchBody()->getLocEnd();
1166 startBuf = SM->getCharacterData(startLoc);
1167
1168 assert((*startBuf == '}') && "bogus @try block");
1169 SourceLocation lastCurlyLoc = startLoc;
1170 buf = "}\nelse {\n";
1171 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1172 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1173 // FIXME: This must be objc_sync_exit(syncExpr);
1174 buf += " objc_sync_exit();\n";
1175 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1176 buf += "}\n";
1177 buf += "}";
1178
Chris Lattneraadaf782008-01-31 19:51:04 +00001179 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001180 return 0;
1181}
1182
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001183Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001184 // Get the start location and compute the semi location.
1185 SourceLocation startLoc = S->getLocStart();
1186 const char *startBuf = SM->getCharacterData(startLoc);
1187
1188 assert((*startBuf == '@') && "bogus @try location");
1189
1190 std::string buf;
1191 // declare a new scope with two variables, _stack and _rethrow.
1192 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1193 buf += "int buf[18/*32-bit i386*/];\n";
1194 buf += "char *pointers[4];} _stack;\n";
1195 buf += "id volatile _rethrow = 0;\n";
1196 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001197 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001198
Chris Lattneraadaf782008-01-31 19:51:04 +00001199 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001200
1201 startLoc = S->getTryBody()->getLocEnd();
1202 startBuf = SM->getCharacterData(startLoc);
1203
1204 assert((*startBuf == '}') && "bogus @try block");
1205
1206 SourceLocation lastCurlyLoc = startLoc;
1207
1208 startLoc = startLoc.getFileLocWithOffset(1);
1209 buf = " /* @catch begin */ else {\n";
1210 buf += " id _caught = objc_exception_extract(&_stack);\n";
1211 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001212 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001213 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1214 buf += " else { /* @catch continue */";
1215
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001216 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001217
1218 bool sawIdTypedCatch = false;
1219 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001220 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001221 while (catchList) {
1222 Stmt *catchStmt = catchList->getCatchParamStmt();
1223
1224 if (catchList == S->getCatchStmts())
1225 buf = "if ("; // we are generating code for the first catch clause
1226 else
1227 buf = "else if (";
1228 startLoc = catchList->getLocStart();
1229 startBuf = SM->getCharacterData(startLoc);
1230
1231 assert((*startBuf == '@') && "bogus @catch location");
1232
1233 const char *lParenLoc = strchr(startBuf, '(');
1234
Steve Naroffbe4b3332008-02-01 22:08:12 +00001235 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001236 // Now rewrite the body...
1237 lastCatchBody = catchList->getCatchBody();
1238 SourceLocation rParenLoc = catchList->getRParenLoc();
1239 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1240 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1241 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1242 assert((*rParenBuf == ')') && "bogus @catch paren location");
1243 assert((*bodyBuf == '{') && "bogus @catch body location");
1244
1245 buf += "1) { id _tmp = _caught;";
1246 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1247 buf.c_str(), buf.size());
1248 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001249 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001250 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001251 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001252 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001253 sawIdTypedCatch = true;
1254 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001255 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001256
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001257 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001258 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001259 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001260 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001261 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001262 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001263 }
1264 }
1265 // Now rewrite the body...
1266 lastCatchBody = catchList->getCatchBody();
1267 SourceLocation rParenLoc = catchList->getRParenLoc();
1268 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1269 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1270 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1271 assert((*rParenBuf == ')') && "bogus @catch paren location");
1272 assert((*bodyBuf == '{') && "bogus @catch body location");
1273
1274 buf = " = _caught;";
1275 // Here we replace ") {" with "= _caught;" (which initializes and
1276 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001277 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001278 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001279 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001280 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001281 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001282 catchList = catchList->getNextCatchStmt();
1283 }
1284 // Complete the catch list...
1285 if (lastCatchBody) {
1286 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1287 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1288 assert((*bodyBuf == '}') && "bogus @catch body location");
1289 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1290 buf = " } } /* @catch end */\n";
1291
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001292 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001293
1294 // Set lastCurlyLoc
1295 lastCurlyLoc = lastCatchBody->getLocEnd();
1296 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001297 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001298 startLoc = finalStmt->getLocStart();
1299 startBuf = SM->getCharacterData(startLoc);
1300 assert((*startBuf == '@') && "bogus @finally start");
1301
1302 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001303 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001304
1305 Stmt *body = finalStmt->getFinallyBody();
1306 SourceLocation startLoc = body->getLocStart();
1307 SourceLocation endLoc = body->getLocEnd();
1308 const char *startBuf = SM->getCharacterData(startLoc);
1309 const char *endBuf = SM->getCharacterData(endLoc);
1310 assert((*startBuf == '{') && "bogus @finally body location");
1311 assert((*endBuf == '}') && "bogus @finally body location");
1312
1313 startLoc = startLoc.getFileLocWithOffset(1);
1314 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001315 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001316 endLoc = endLoc.getFileLocWithOffset(-1);
1317 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001318 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001319
1320 // Set lastCurlyLoc
1321 lastCurlyLoc = body->getLocEnd();
1322 }
1323 // Now emit the final closing curly brace...
1324 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1325 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001326 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001327 return 0;
1328}
1329
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001330Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001331 return 0;
1332}
1333
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001334Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001335 return 0;
1336}
1337
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001338// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001339// the throw expression is typically a message expression that's already
1340// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001341Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001342 // Get the start location and compute the semi location.
1343 SourceLocation startLoc = S->getLocStart();
1344 const char *startBuf = SM->getCharacterData(startLoc);
1345
1346 assert((*startBuf == '@') && "bogus @throw location");
1347
1348 std::string buf;
1349 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001350 if (S->getThrowExpr())
1351 buf = "objc_exception_throw(";
1352 else // add an implicit argument
1353 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001354 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001355 const char *semiBuf = strchr(startBuf, ';');
1356 assert((*semiBuf == ';') && "@throw: can't find ';'");
1357 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1358 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001359 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001360 return 0;
1361}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001362
Chris Lattnere64b7772007-10-24 16:57:36 +00001363Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001364 // Create a new string expression.
1365 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001366 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001367 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1368 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001369 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1370 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001371 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001372 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001373
Chris Lattner07506182007-11-30 22:53:43 +00001374 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001375 delete Exp;
1376 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001377}
1378
Steve Naroffb42f8412007-11-05 14:50:49 +00001379Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1380 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1381 // Create a call to sel_registerName("selName").
1382 llvm::SmallVector<Expr*, 8> SelExprs;
1383 QualType argType = Context->getPointerType(Context->CharTy);
1384 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1385 Exp->getSelector().getName().size(),
1386 false, argType, SourceLocation(),
1387 SourceLocation()));
1388 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1389 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001390 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001391 delete Exp;
1392 return SelExp;
1393}
1394
Steve Naroff934f2762007-10-24 22:48:43 +00001395CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1396 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001397 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001398 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001399
1400 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001401 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001402
1403 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001404 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001405 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1406
1407 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001408
Steve Naroff934f2762007-10-24 22:48:43 +00001409 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1410}
1411
Steve Naroffd5255f52007-11-01 13:24:47 +00001412static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1413 const char *&startRef, const char *&endRef) {
1414 while (startBuf < endBuf) {
1415 if (*startBuf == '<')
1416 startRef = startBuf; // mark the start.
1417 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001418 if (startRef && *startRef == '<') {
1419 endRef = startBuf; // mark the end.
1420 return true;
1421 }
1422 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001423 }
1424 startBuf++;
1425 }
1426 return false;
1427}
1428
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001429static void scanToNextArgument(const char *&argRef) {
1430 int angle = 0;
1431 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1432 if (*argRef == '<')
1433 angle++;
1434 else if (*argRef == '>')
1435 angle--;
1436 argRef++;
1437 }
1438 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1439}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001440
Steve Naroffd5255f52007-11-01 13:24:47 +00001441bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001442
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001443 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001444 return true;
1445
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001446 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001447 return true;
1448
Steve Naroffd5255f52007-11-01 13:24:47 +00001449 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001450 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001451 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001452 return true; // we have "Class <Protocol> *".
1453 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001454 return false;
1455}
1456
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001457void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001458 SourceLocation Loc;
1459 QualType Type;
1460 const FunctionTypeProto *proto = 0;
1461 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1462 Loc = VD->getLocation();
1463 Type = VD->getType();
1464 }
1465 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1466 Loc = FD->getLocation();
1467 // Check for ObjC 'id' and class types that have been adorned with protocol
1468 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1469 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1470 assert(funcType && "missing function type");
1471 proto = dyn_cast<FunctionTypeProto>(funcType);
1472 if (!proto)
1473 return;
1474 Type = proto->getResultType();
1475 }
1476 else
1477 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001478
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001479 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001480 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001481
1482 const char *endBuf = SM->getCharacterData(Loc);
1483 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001484 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001485 startBuf--; // scan backward (from the decl location) for return type.
1486 const char *startRef = 0, *endRef = 0;
1487 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1488 // Get the locations of the startRef, endRef.
1489 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1490 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1491 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001492 InsertText(LessLoc, "/*", 2);
1493 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001494 }
1495 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001496 if (!proto)
1497 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001498 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001499 const char *startBuf = SM->getCharacterData(Loc);
1500 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001501 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1502 if (needToScanForQualifiers(proto->getArgType(i))) {
1503 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001504
Steve Naroffd5255f52007-11-01 13:24:47 +00001505 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001506 // scan forward (from the decl location) for argument types.
1507 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001508 const char *startRef = 0, *endRef = 0;
1509 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1510 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001511 SourceLocation LessLoc =
1512 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1513 SourceLocation GreaterLoc =
1514 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001515 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001516 InsertText(LessLoc, "/*", 2);
1517 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001518 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001519 startBuf = ++endBuf;
1520 }
1521 else {
1522 while (*startBuf != ')' && *startBuf != ',')
1523 startBuf++; // scan forward (from the decl location) for argument types.
1524 startBuf++;
1525 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001526 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001527}
1528
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001529// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1530void RewriteTest::SynthSelGetUidFunctionDecl() {
1531 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1532 llvm::SmallVector<QualType, 16> ArgTys;
1533 ArgTys.push_back(Context->getPointerType(
1534 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001535 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001536 &ArgTys[0], ArgTys.size(),
1537 false /*isVariadic*/);
1538 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1539 SelGetUidIdent, getFuncType,
1540 FunctionDecl::Extern, false, 0);
1541}
1542
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001543// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1544void RewriteTest::SynthGetProtocolFunctionDecl() {
1545 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1546 llvm::SmallVector<QualType, 16> ArgTys;
1547 ArgTys.push_back(Context->getPointerType(
1548 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001549 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001550 &ArgTys[0], ArgTys.size(),
1551 false /*isVariadic*/);
1552 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1553 SelGetProtoIdent, getFuncType,
1554 FunctionDecl::Extern, false, 0);
1555}
1556
Steve Naroff09b266e2007-10-30 23:14:51 +00001557void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1558 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001559 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001560 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001561 return;
1562 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001563 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001564}
1565
Steve Naroffc0a123c2008-03-11 17:37:02 +00001566// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1567void RewriteTest::SynthSuperContructorFunctionDecl() {
1568 if (SuperContructorFunctionDecl)
1569 return;
1570 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1571 llvm::SmallVector<QualType, 16> ArgTys;
1572 QualType argT = Context->getObjCIdType();
1573 assert(!argT.isNull() && "Can't find 'id' type");
1574 ArgTys.push_back(argT);
1575 ArgTys.push_back(argT);
1576 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1577 &ArgTys[0], ArgTys.size(),
1578 false);
1579 SuperContructorFunctionDecl = new FunctionDecl(SourceLocation(),
1580 msgSendIdent, msgSendType,
1581 FunctionDecl::Extern, false, 0);
1582}
1583
Steve Naroff09b266e2007-10-30 23:14:51 +00001584// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1585void RewriteTest::SynthMsgSendFunctionDecl() {
1586 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1587 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001588 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001589 assert(!argT.isNull() && "Can't find 'id' type");
1590 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001591 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001592 assert(!argT.isNull() && "Can't find 'SEL' type");
1593 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001594 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001595 &ArgTys[0], ArgTys.size(),
1596 true /*isVariadic*/);
1597 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1598 msgSendIdent, msgSendType,
1599 FunctionDecl::Extern, false, 0);
1600}
1601
Steve Naroff874e2322007-11-15 10:28:18 +00001602// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1603void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1604 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1605 llvm::SmallVector<QualType, 16> ArgTys;
1606 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1607 &Context->Idents.get("objc_super"), 0);
1608 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1609 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1610 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001611 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001612 assert(!argT.isNull() && "Can't find 'SEL' type");
1613 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001614 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001615 &ArgTys[0], ArgTys.size(),
1616 true /*isVariadic*/);
1617 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1618 msgSendIdent, msgSendType,
1619 FunctionDecl::Extern, false, 0);
1620}
1621
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001622// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1623void RewriteTest::SynthMsgSendStretFunctionDecl() {
1624 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1625 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001626 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001627 assert(!argT.isNull() && "Can't find 'id' type");
1628 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001629 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001630 assert(!argT.isNull() && "Can't find 'SEL' type");
1631 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001632 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001633 &ArgTys[0], ArgTys.size(),
1634 true /*isVariadic*/);
1635 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1636 msgSendIdent, msgSendType,
1637 FunctionDecl::Extern, false, 0);
1638}
1639
1640// SynthMsgSendSuperStretFunctionDecl -
1641// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1642void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1643 IdentifierInfo *msgSendIdent =
1644 &Context->Idents.get("objc_msgSendSuper_stret");
1645 llvm::SmallVector<QualType, 16> ArgTys;
1646 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1647 &Context->Idents.get("objc_super"), 0);
1648 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1649 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1650 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001651 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001652 assert(!argT.isNull() && "Can't find 'SEL' type");
1653 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001654 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001655 &ArgTys[0], ArgTys.size(),
1656 true /*isVariadic*/);
1657 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1658 msgSendIdent, msgSendType,
1659 FunctionDecl::Extern, false, 0);
1660}
1661
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001662// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1663void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1664 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1665 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001666 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001667 assert(!argT.isNull() && "Can't find 'id' type");
1668 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001669 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001670 assert(!argT.isNull() && "Can't find 'SEL' type");
1671 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001672 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001673 &ArgTys[0], ArgTys.size(),
1674 true /*isVariadic*/);
1675 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1676 msgSendIdent, msgSendType,
1677 FunctionDecl::Extern, false, 0);
1678}
1679
Steve Naroff09b266e2007-10-30 23:14:51 +00001680// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1681void RewriteTest::SynthGetClassFunctionDecl() {
1682 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1683 llvm::SmallVector<QualType, 16> ArgTys;
1684 ArgTys.push_back(Context->getPointerType(
1685 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001686 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001687 &ArgTys[0], ArgTys.size(),
1688 false /*isVariadic*/);
1689 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1690 getClassIdent, getClassType,
1691 FunctionDecl::Extern, false, 0);
1692}
1693
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001694// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1695void RewriteTest::SynthGetMetaClassFunctionDecl() {
1696 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1697 llvm::SmallVector<QualType, 16> ArgTys;
1698 ArgTys.push_back(Context->getPointerType(
1699 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001700 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001701 &ArgTys[0], ArgTys.size(),
1702 false /*isVariadic*/);
1703 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1704 getClassIdent, getClassType,
1705 FunctionDecl::Extern, false, 0);
1706}
1707
Steve Naroff96984642007-11-08 14:30:50 +00001708// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1709void RewriteTest::SynthCFStringFunctionDecl() {
1710 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1711 llvm::SmallVector<QualType, 16> ArgTys;
1712 ArgTys.push_back(Context->getPointerType(
1713 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001714 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001715 &ArgTys[0], ArgTys.size(),
1716 false /*isVariadic*/);
1717 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1718 getClassIdent, getClassType,
1719 FunctionDecl::Extern, false, 0);
1720}
1721
Steve Naroffbeaf2992007-11-03 11:27:19 +00001722Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001723#if 1
1724 // This rewrite is specific to GCC, which has builtin support for CFString.
1725 if (!CFStringFunctionDecl)
1726 SynthCFStringFunctionDecl();
1727 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1728 llvm::SmallVector<Expr*, 8> StrExpr;
1729 StrExpr.push_back(Exp->getString());
1730 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1731 &StrExpr[0], StrExpr.size());
1732 // cast to NSConstantString *
1733 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001734 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001735 delete Exp;
1736 return cast;
1737#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001738 assert(ConstantStringClassReference && "Can't find constant string reference");
1739 llvm::SmallVector<Expr*, 4> InitExprs;
1740
1741 // Synthesize "(Class)&_NSConstantStringClassReference"
1742 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1743 ConstantStringClassReference->getType(),
1744 SourceLocation());
1745 QualType expType = Context->getPointerType(ClsRef->getType());
1746 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1747 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001748 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001749 SourceLocation());
1750 InitExprs.push_back(cast); // set the 'isa'.
1751 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1752 unsigned IntSize = static_cast<unsigned>(
1753 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1754 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1755 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1756 Exp->getLocStart());
1757 InitExprs.push_back(len); // set "int numBytes".
1758
1759 // struct NSConstantString
1760 QualType CFConstantStrType = Context->getCFConstantStringType();
1761 // (struct NSConstantString) { <exprs from above> }
1762 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1763 &InitExprs[0], InitExprs.size(),
1764 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001765 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001766 // struct NSConstantString *
1767 expType = Context->getPointerType(StrRep->getType());
1768 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1769 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001770 // cast to NSConstantString *
1771 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001772 ReplaceStmt(Exp, cast);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001773 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001774 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001775#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001776}
1777
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001778ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001779 // check if we are sending a message to 'super'
1780 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001781 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1782 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1783 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1784 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001785 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001786 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001787 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001788 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001789 if (ObjCInterfaceType *IT =
1790 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001791 if (IT->getDecl() ==
1792 CurMethodDecl->getClassInterface()->getSuperClass())
1793 return IT->getDecl();
1794 }
1795 }
1796 }
1797 }
1798 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001799 }
Steve Naroff874e2322007-11-15 10:28:18 +00001800 }
1801 return 0;
1802}
1803
1804// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1805QualType RewriteTest::getSuperStructType() {
1806 if (!SuperStructDecl) {
1807 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1808 &Context->Idents.get("objc_super"), 0);
1809 QualType FieldTypes[2];
1810
1811 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001812 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001813 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001814 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001815 // Create fields
1816 FieldDecl *FieldDecls[2];
1817
1818 for (unsigned i = 0; i < 2; ++i)
1819 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1820
1821 SuperStructDecl->defineBody(FieldDecls, 4);
1822 }
1823 return Context->getTagDeclType(SuperStructDecl);
1824}
1825
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001826Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001827 if (!SelGetUidFunctionDecl)
1828 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001829 if (!MsgSendFunctionDecl)
1830 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001831 if (!MsgSendSuperFunctionDecl)
1832 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001833 if (!MsgSendStretFunctionDecl)
1834 SynthMsgSendStretFunctionDecl();
1835 if (!MsgSendSuperStretFunctionDecl)
1836 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001837 if (!MsgSendFpretFunctionDecl)
1838 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001839 if (!GetClassFunctionDecl)
1840 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001841 if (!GetMetaClassFunctionDecl)
1842 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001843
Steve Naroff874e2322007-11-15 10:28:18 +00001844 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001845 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1846 // May need to use objc_msgSend_stret() as well.
1847 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001848 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001849 QualType resultType = mDecl->getResultType();
1850 if (resultType.getCanonicalType()->isStructureType()
1851 || resultType.getCanonicalType()->isUnionType())
1852 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001853 else if (resultType.getCanonicalType()->isRealFloatingType())
1854 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001855 }
Steve Naroff874e2322007-11-15 10:28:18 +00001856
Steve Naroff934f2762007-10-24 22:48:43 +00001857 // Synthesize a call to objc_msgSend().
1858 llvm::SmallVector<Expr*, 8> MsgExprs;
1859 IdentifierInfo *clsName = Exp->getClassName();
1860
1861 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1862 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001863 if (!strcmp(clsName->getName(), "super")) {
1864 MsgSendFlavor = MsgSendSuperFunctionDecl;
1865 if (MsgSendStretFlavor)
1866 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1867 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1868
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001869 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001870 CurMethodDecl->getClassInterface()->getSuperClass();
1871
1872 llvm::SmallVector<Expr*, 4> InitExprs;
1873
1874 // set the receiver to self, the first argument to all methods.
1875 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001876 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001877 SourceLocation()));
1878 llvm::SmallVector<Expr*, 8> ClsExprs;
1879 QualType argType = Context->getPointerType(Context->CharTy);
1880 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1881 SuperDecl->getIdentifier()->getLength(),
1882 false, argType, SourceLocation(),
1883 SourceLocation()));
1884 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1885 &ClsExprs[0],
1886 ClsExprs.size());
1887 // To turn off a warning, type-cast to 'id'
1888 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001889 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001890 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1891 // struct objc_super
1892 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001893 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001894
Steve Naroff23f41272008-03-11 18:14:26 +00001895 if (LangOpts.Microsoft) {
1896 SynthSuperContructorFunctionDecl();
1897 // Simulate a contructor call...
1898 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1899 superType, SourceLocation());
1900 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1901 superType, SourceLocation());
1902 } else {
1903 // (struct objc_super) { <exprs from above> }
1904 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1905 &InitExprs[0], InitExprs.size(),
1906 SourceLocation());
1907 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1908 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001909 // struct objc_super *
1910 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1911 Context->getPointerType(SuperRep->getType()),
1912 SourceLocation());
1913 MsgExprs.push_back(Unop);
1914 } else {
1915 llvm::SmallVector<Expr*, 8> ClsExprs;
1916 QualType argType = Context->getPointerType(Context->CharTy);
1917 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1918 clsName->getLength(),
1919 false, argType, SourceLocation(),
1920 SourceLocation()));
1921 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1922 &ClsExprs[0],
1923 ClsExprs.size());
1924 MsgExprs.push_back(Cls);
1925 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001926 } else { // instance message.
1927 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001928
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001929 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001930 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001931 if (MsgSendStretFlavor)
1932 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001933 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1934
1935 llvm::SmallVector<Expr*, 4> InitExprs;
1936
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001937 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001938 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001939 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001940
1941 llvm::SmallVector<Expr*, 8> ClsExprs;
1942 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001943 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1944 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001945 false, argType, SourceLocation(),
1946 SourceLocation()));
1947 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001948 &ClsExprs[0],
1949 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001950 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001951 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001952 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001953 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001954 // struct objc_super
1955 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00001956 Expr *SuperRep;
1957
1958 if (LangOpts.Microsoft) {
1959 SynthSuperContructorFunctionDecl();
1960 // Simulate a contructor call...
1961 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1962 superType, SourceLocation());
1963 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1964 superType, SourceLocation());
1965 } else {
1966 // (struct objc_super) { <exprs from above> }
1967 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1968 &InitExprs[0], InitExprs.size(),
1969 SourceLocation());
1970 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1971 }
Steve Naroff874e2322007-11-15 10:28:18 +00001972 // struct objc_super *
1973 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1974 Context->getPointerType(SuperRep->getType()),
1975 SourceLocation());
1976 MsgExprs.push_back(Unop);
1977 } else {
Steve Naroff3c64d9e2008-03-12 13:19:12 +00001978 //recExpr->dump();
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001979 // Remove all type-casts because it may contain objc-style types; e.g.
1980 // Foo<Proto> *.
1981 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1982 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001983 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001984 MsgExprs.push_back(recExpr);
1985 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001986 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001987 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001988 llvm::SmallVector<Expr*, 8> SelExprs;
1989 QualType argType = Context->getPointerType(Context->CharTy);
1990 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1991 Exp->getSelector().getName().size(),
1992 false, argType, SourceLocation(),
1993 SourceLocation()));
1994 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1995 &SelExprs[0], SelExprs.size());
1996 MsgExprs.push_back(SelExp);
1997
1998 // Now push any user supplied arguments.
1999 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002000 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002001 // Make all implicit casts explicit...ICE comes in handy:-)
2002 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2003 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002004 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2005 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002006 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002007 }
2008 // Make id<P...> cast into an 'id' cast.
2009 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002010 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002011 while ((CE = dyn_cast<CastExpr>(userExpr)))
2012 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002013 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002014 userExpr, SourceLocation());
2015 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002016 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002017 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002018 // We've transferred the ownership to MsgExprs. Null out the argument in
2019 // the original expression, since we will delete it below.
2020 Exp->setArg(i, 0);
2021 }
Steve Naroffab972d32007-11-04 22:37:50 +00002022 // Generate the funky cast.
2023 CastExpr *cast;
2024 llvm::SmallVector<QualType, 8> ArgTypes;
2025 QualType returnType;
2026
2027 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002028 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2029 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2030 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002031 ArgTypes.push_back(Context->getObjCIdType());
2032 ArgTypes.push_back(Context->getObjCSelType());
2033 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002034 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00002035 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002036 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2037 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002038 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002039 ArgTypes.push_back(t);
2040 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2042 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002043 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002044 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002045 }
2046 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002047 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002048
2049 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002050 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2051 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002052
2053 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2054 // If we don't do this cast, we get the following bizarre warning/note:
2055 // xx.m:13: warning: function called through a non-compatible type
2056 // xx.m:13: note: if this code is reached, the program will abort
2057 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2058 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002059
Steve Naroffab972d32007-11-04 22:37:50 +00002060 // Now do the "normal" pointer to function cast.
2061 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002062 &ArgTypes[0], ArgTypes.size(),
2063 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00002064 castType = Context->getPointerType(castType);
2065 cast = new CastExpr(castType, cast, SourceLocation());
2066
2067 // Don't forget the parens to enforce the proper binding.
2068 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2069
2070 const FunctionType *FT = msgSendType->getAsFunctionType();
2071 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2072 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002073 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002074 if (MsgSendStretFlavor) {
2075 // We have the method which returns a struct/union. Must also generate
2076 // call to objc_msgSend_stret and hang both varieties on a conditional
2077 // expression which dictate which one to envoke depending on size of
2078 // method's return type.
2079
2080 // Create a reference to the objc_msgSend_stret() declaration.
2081 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2082 SourceLocation());
2083 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2084 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2085 SourceLocation());
2086 // Now do the "normal" pointer to function cast.
2087 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002088 &ArgTypes[0], ArgTypes.size(),
2089 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002090 castType = Context->getPointerType(castType);
2091 cast = new CastExpr(castType, cast, SourceLocation());
2092
2093 // Don't forget the parens to enforce the proper binding.
2094 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2095
2096 FT = msgSendType->getAsFunctionType();
2097 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2098 FT->getResultType(), SourceLocation());
2099
2100 // Build sizeof(returnType)
2101 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2102 returnType, Context->getSizeType(),
2103 SourceLocation(), SourceLocation());
2104 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2105 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2106 // For X86 it is more complicated and some kind of target specific routine
2107 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002108 unsigned IntSize =
2109 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002110 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2111 Context->IntTy,
2112 SourceLocation());
2113 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2114 BinaryOperator::LE,
2115 Context->IntTy,
2116 SourceLocation());
2117 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2118 ConditionalOperator *CondExpr =
2119 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002120 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002121 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002122 return ReplacingStmt;
2123}
2124
2125Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2126 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002127 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002128 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002129
Chris Lattnere64b7772007-10-24 16:57:36 +00002130 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002131 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002132}
2133
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002134/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2135/// call to objc_getProtocol("proto-name").
2136Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2137 if (!GetProtocolFunctionDecl)
2138 SynthGetProtocolFunctionDecl();
2139 // Create a call to objc_getProtocol("ProtocolName").
2140 llvm::SmallVector<Expr*, 8> ProtoExprs;
2141 QualType argType = Context->getPointerType(Context->CharTy);
2142 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2143 strlen(Exp->getProtocol()->getName()),
2144 false, argType, SourceLocation(),
2145 SourceLocation()));
2146 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2147 &ProtoExprs[0],
2148 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002149 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002150 delete Exp;
2151 return ProtoExp;
2152
2153}
2154
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002155/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002156/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002157void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002158 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002159 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2160 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002161 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002162 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002163 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002164 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002165 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002166 SourceLocation LocStart = CDecl->getLocStart();
2167 SourceLocation LocEnd = CDecl->getLocEnd();
2168
2169 const char *startBuf = SM->getCharacterData(LocStart);
2170 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002171 // If no ivars and no root or if its root, directly or indirectly,
2172 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002173 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002174 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002175 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002176 return;
2177 }
2178
2179 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002180 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002181 Result += "\nstruct ";
2182 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002183 if (LangOpts.Microsoft)
2184 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002185
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002186 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002187 const char *cursor = strchr(startBuf, '{');
2188 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002189 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002190
2191 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002192 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002193 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002194 Result = "\n struct ";
2195 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002196 Result += "_IMPL ";
2197 Result += RCDecl->getName();
2198 Result += "_IVARS";
Steve Narofffea763e82007-11-14 19:25:57 +00002199 Result += ";\n";
2200
2201 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002202 SourceLocation OnePastCurly =
2203 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2204 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002205 }
2206 cursor++; // past '{'
2207
2208 // Now comment out any visibility specifiers.
2209 while (cursor < endBuf) {
2210 if (*cursor == '@') {
2211 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002212 // Skip whitespace.
2213 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2214 /*scan*/;
2215
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002216 // FIXME: presence of @public, etc. inside comment results in
2217 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002218 if (!strncmp(cursor, "public", strlen("public")) ||
2219 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002220 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002221 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002222 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002223 // FIXME: If there are cases where '<' is used in ivar declaration part
2224 // of user code, then scan the ivar list and use needToScanForQualifiers
2225 // for type checking.
2226 else if (*cursor == '<') {
2227 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002228 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002229 cursor = strchr(cursor, '>');
2230 cursor++;
2231 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002232 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002233 }
Steve Narofffea763e82007-11-14 19:25:57 +00002234 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002235 }
Steve Narofffea763e82007-11-14 19:25:57 +00002236 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002237 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002238 } else { // we don't have any instance variables - insert super struct.
2239 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2240 Result += " {\n struct ";
2241 Result += RCDecl->getName();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002242 Result += "_IMPL ";
2243 Result += RCDecl->getName();
2244 Result += "_IVARS";
Steve Narofffea763e82007-11-14 19:25:57 +00002245 Result += ";\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002246 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002247 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002248 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002249 if (!ObjCSynthesizedStructs.insert(CDecl))
2250 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002251}
2252
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002253// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002254/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002255void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002256 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002257 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002258 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002259 const char *ClassName,
2260 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002261 if (MethodBegin == MethodEnd) return;
2262
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002263 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002264 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002265 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002266 SEL _cmd;
2267 char *method_types;
2268 void *_imp;
2269 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002270 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002271 Result += "\nstruct _objc_method {\n";
2272 Result += "\tSEL _cmd;\n";
2273 Result += "\tchar *method_types;\n";
2274 Result += "\tvoid *_imp;\n";
2275 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002276
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002277 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002278 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002279
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002280 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002281
2282 /* struct {
2283 struct _objc_method_list *next_method;
2284 int method_count;
2285 struct _objc_method method_list[];
2286 }
2287 */
2288 Result += "\nstatic struct {\n";
2289 Result += "\tstruct _objc_method_list *next_method;\n";
2290 Result += "\tint method_count;\n";
2291 Result += "\tstruct _objc_method method_list[";
2292 Result += utostr(MethodEnd-MethodBegin);
2293 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002294 Result += prefix;
2295 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2296 Result += "_METHODS_";
2297 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002298 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002299 Result += IsInstanceMethod ? "inst" : "cls";
2300 Result += "_meth\")))= ";
2301 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002302
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002303 Result += "\t,{{(SEL)\"";
2304 Result += (*MethodBegin)->getSelector().getName().c_str();
2305 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002306 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002307 Result += "\", \"";
2308 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002309 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002310 Result += MethodInternalNames[*MethodBegin];
2311 Result += "}\n";
2312 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2313 Result += "\t ,{(SEL)\"";
2314 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002315 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002316 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002317 Result += "\", \"";
2318 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002319 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002320 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002321 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002322 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002323 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002324}
2325
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002326/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2327void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002328 int NumProtocols,
2329 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002330 const char *ClassName,
2331 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002332 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002333 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002334 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002335 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002336 // Output struct protocol_methods holder of method selector and type.
2337 if (!objc_protocol_methods &&
2338 (PDecl->getNumInstanceMethods() > 0
2339 || PDecl->getNumClassMethods() > 0)) {
2340 /* struct protocol_methods {
2341 SEL _cmd;
2342 char *method_types;
2343 }
2344 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002345 Result += "\nstruct protocol_methods {\n";
2346 Result += "\tSEL _cmd;\n";
2347 Result += "\tchar *method_types;\n";
2348 Result += "};\n";
2349
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002350 objc_protocol_methods = true;
2351 }
2352 int NumMethods = PDecl->getNumInstanceMethods();
2353 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002354 /* struct _objc_protocol_method_list {
2355 int protocol_method_count;
2356 struct protocol_methods protocols[];
2357 }
2358 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002359 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002360 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002361 Result += "\tstruct protocol_methods protocols[";
2362 Result += utostr(NumMethods);
2363 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002364 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002365 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002366 "{\n\t" + utostr(NumMethods) + "\n";
2367
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002368 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002370 E = PDecl->instmeth_end(); I != E; ++I) {
2371 if (I == PDecl->instmeth_begin())
2372 Result += "\t ,{{(SEL)\"";
2373 else
2374 Result += "\t ,{(SEL)\"";
2375 Result += (*I)->getSelector().getName().c_str();
2376 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002377 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002378 Result += "\", \"";
2379 Result += MethodTypeString;
2380 Result += "\"}\n";
2381 }
2382 Result += "\t }\n};\n";
2383 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002384
2385 // Output class methods declared in this protocol.
2386 NumMethods = PDecl->getNumClassMethods();
2387 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002388 /* struct _objc_protocol_method_list {
2389 int protocol_method_count;
2390 struct protocol_methods protocols[];
2391 }
2392 */
2393 Result += "\nstatic struct {\n";
2394 Result += "\tint protocol_method_count;\n";
2395 Result += "\tstruct protocol_methods protocols[";
2396 Result += utostr(NumMethods);
2397 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002398 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002399 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002400 "{\n\t";
2401 Result += utostr(NumMethods);
2402 Result += "\n";
2403
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002404 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002405 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002406 E = PDecl->classmeth_end(); I != E; ++I) {
2407 if (I == PDecl->classmeth_begin())
2408 Result += "\t ,{{(SEL)\"";
2409 else
2410 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002411 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002412 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002413 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002414 Result += "\", \"";
2415 Result += MethodTypeString;
2416 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002417 }
2418 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002419 }
2420 // Output:
2421 /* struct _objc_protocol {
2422 // Objective-C 1.0 extensions
2423 struct _objc_protocol_extension *isa;
2424 char *protocol_name;
2425 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002426 struct _objc_protocol_method_list *instance_methods;
2427 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002428 };
2429 */
2430 static bool objc_protocol = false;
2431 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002432 Result += "\nstruct _objc_protocol {\n";
2433 Result += "\tstruct _objc_protocol_extension *isa;\n";
2434 Result += "\tchar *protocol_name;\n";
2435 Result += "\tstruct _objc_protocol **protocol_list;\n";
2436 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2437 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2438 Result += "};\n";
2439
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002440 objc_protocol = true;
2441 }
2442
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002443 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2444 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002445 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002446 "{\n\t0, \"";
2447 Result += PDecl->getName();
2448 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002449 if (PDecl->getNumInstanceMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002450 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002451 Result += PDecl->getName();
2452 Result += ", ";
2453 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002454 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002455 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002456 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002457 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002458 Result += PDecl->getName();
2459 Result += "\n";
2460 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002461 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002462 Result += "0\n";
2463 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002464 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002465 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002466 /* struct _objc_protocol_list {
2467 struct _objc_protocol_list *next;
2468 int protocol_count;
2469 struct _objc_protocol *class_protocols[];
2470 }
2471 */
2472 Result += "\nstatic struct {\n";
2473 Result += "\tstruct _objc_protocol_list *next;\n";
2474 Result += "\tint protocol_count;\n";
2475 Result += "\tstruct _objc_protocol *class_protocols[";
2476 Result += utostr(NumProtocols);
2477 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002478 Result += prefix;
2479 Result += "_PROTOCOLS_";
2480 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002481 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002482 "{\n\t0, ";
2483 Result += utostr(NumProtocols);
2484 Result += "\n";
2485
2486 Result += "\t,{&_OBJC_PROTOCOL_";
2487 Result += Protocols[0]->getName();
2488 Result += " \n";
2489
2490 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002491 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002492 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002493 Result += PDecl->getName();
2494 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002495 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002496 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002497 }
2498}
2499
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002500/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002501/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002502void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002503 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002504 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002505 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002506 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002507 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2508 CDecl = CDecl->getNextClassCategory())
2509 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2510 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002511
Chris Lattnereb44eee2007-12-23 01:40:15 +00002512 std::string FullCategoryName = ClassDecl->getName();
2513 FullCategoryName += '_';
2514 FullCategoryName += IDecl->getName();
2515
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002516 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002517 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002518 true, "CATEGORY_", FullCategoryName.c_str(),
2519 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002520
2521 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002522 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002523 false, "CATEGORY_", FullCategoryName.c_str(),
2524 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002525
2526 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002527 // Null CDecl is case of a category implementation with no category interface
2528 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002529 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002530 CDecl->getNumReferencedProtocols(),
2531 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002532 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002533
2534 /* struct _objc_category {
2535 char *category_name;
2536 char *class_name;
2537 struct _objc_method_list *instance_methods;
2538 struct _objc_method_list *class_methods;
2539 struct _objc_protocol_list *protocols;
2540 // Objective-C 1.0 extensions
2541 uint32_t size; // sizeof (struct _objc_category)
2542 struct _objc_property_list *instance_properties; // category's own
2543 // @property decl.
2544 };
2545 */
2546
2547 static bool objc_category = false;
2548 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002549 Result += "\nstruct _objc_category {\n";
2550 Result += "\tchar *category_name;\n";
2551 Result += "\tchar *class_name;\n";
2552 Result += "\tstruct _objc_method_list *instance_methods;\n";
2553 Result += "\tstruct _objc_method_list *class_methods;\n";
2554 Result += "\tstruct _objc_protocol_list *protocols;\n";
2555 Result += "\tunsigned int size;\n";
2556 Result += "\tstruct _objc_property_list *instance_properties;\n";
2557 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002558 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002559 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002560 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2561 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002562 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002563 Result += IDecl->getName();
2564 Result += "\"\n\t, \"";
2565 Result += ClassDecl->getName();
2566 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002567
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002568 if (IDecl->getNumInstanceMethods() > 0) {
2569 Result += "\t, (struct _objc_method_list *)"
2570 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2571 Result += FullCategoryName;
2572 Result += "\n";
2573 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002574 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002575 Result += "\t, 0\n";
2576 if (IDecl->getNumClassMethods() > 0) {
2577 Result += "\t, (struct _objc_method_list *)"
2578 "&_OBJC_CATEGORY_CLASS_METHODS_";
2579 Result += FullCategoryName;
2580 Result += "\n";
2581 }
2582 else
2583 Result += "\t, 0\n";
2584
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002585 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002586 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2587 Result += FullCategoryName;
2588 Result += "\n";
2589 }
2590 else
2591 Result += "\t, 0\n";
2592 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002593}
2594
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002595/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2596/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002597void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2598 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002599 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002600 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002601 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002602 if (LangOpts.Microsoft)
2603 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002604 Result += ", ";
2605 Result += ivar->getName();
2606 Result += ")";
2607}
2608
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002609//===----------------------------------------------------------------------===//
2610// Meta Data Emission
2611//===----------------------------------------------------------------------===//
2612
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002613void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002614 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002615 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002616
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002617 // Explictly declared @interface's are already synthesized.
2618 if (CDecl->ImplicitInterfaceDecl()) {
2619 // FIXME: Implementation of a class with no @interface (legacy) doese not
2620 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002621 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002622 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002623
Chris Lattnerbe6df082007-12-12 07:56:42 +00002624 // Build _objc_ivar_list metadata for classes ivars if needed
2625 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2626 ? IDecl->getImplDeclNumIvars()
2627 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002628 if (NumIvars > 0) {
2629 static bool objc_ivar = false;
2630 if (!objc_ivar) {
2631 /* struct _objc_ivar {
2632 char *ivar_name;
2633 char *ivar_type;
2634 int ivar_offset;
2635 };
2636 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002637 Result += "\nstruct _objc_ivar {\n";
2638 Result += "\tchar *ivar_name;\n";
2639 Result += "\tchar *ivar_type;\n";
2640 Result += "\tint ivar_offset;\n";
2641 Result += "};\n";
2642
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002643 objc_ivar = true;
2644 }
2645
Steve Naroff946a6932008-03-11 00:12:29 +00002646 /* struct {
2647 int ivar_count;
2648 struct _objc_ivar ivar_list[nIvars];
2649 };
2650 */
2651 Result += "\nstatic struct {\n";
2652 Result += "\tint ivar_count;\n";
2653 Result += "\tstruct _objc_ivar ivar_list[";
2654 Result += utostr(NumIvars);
2655 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002656 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002657 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002658 "{\n\t";
2659 Result += utostr(NumIvars);
2660 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002661
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002662 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002663 if (IDecl->getImplDeclNumIvars() > 0) {
2664 IVI = IDecl->ivar_begin();
2665 IVE = IDecl->ivar_end();
2666 } else {
2667 IVI = CDecl->ivar_begin();
2668 IVE = CDecl->ivar_end();
2669 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002670 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002671 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002672 Result += "\", \"";
2673 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002674 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2675 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002676 Result += StrEncoding;
2677 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002678 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002679 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002680 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002681 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002682 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002683 Result += "\", \"";
2684 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002685 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2686 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002687 Result += StrEncoding;
2688 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002689 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002690 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002691 }
2692
2693 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002694 }
2695
2696 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002697 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002698 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002699
2700 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002701 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002702 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002703
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002704 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002705 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002706 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002707 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002708
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002709
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002710 // Declaration of class/meta-class metadata
2711 /* struct _objc_class {
2712 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002713 const char *super_class_name;
2714 char *name;
2715 long version;
2716 long info;
2717 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002718 struct _objc_ivar_list *ivars;
2719 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002720 struct objc_cache *cache;
2721 struct objc_protocol_list *protocols;
2722 const char *ivar_layout;
2723 struct _objc_class_ext *ext;
2724 };
2725 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002726 static bool objc_class = false;
2727 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002728 Result += "\nstruct _objc_class {\n";
2729 Result += "\tstruct _objc_class *isa;\n";
2730 Result += "\tconst char *super_class_name;\n";
2731 Result += "\tchar *name;\n";
2732 Result += "\tlong version;\n";
2733 Result += "\tlong info;\n";
2734 Result += "\tlong instance_size;\n";
2735 Result += "\tstruct _objc_ivar_list *ivars;\n";
2736 Result += "\tstruct _objc_method_list *methods;\n";
2737 Result += "\tstruct objc_cache *cache;\n";
2738 Result += "\tstruct _objc_protocol_list *protocols;\n";
2739 Result += "\tconst char *ivar_layout;\n";
2740 Result += "\tstruct _objc_class_ext *ext;\n";
2741 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002742 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002743 }
2744
2745 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002746 ObjCInterfaceDecl *RootClass = 0;
2747 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002748 while (SuperClass) {
2749 RootClass = SuperClass;
2750 SuperClass = SuperClass->getSuperClass();
2751 }
2752 SuperClass = CDecl->getSuperClass();
2753
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002754 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2755 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002756 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002757 "{\n\t(struct _objc_class *)\"";
2758 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2759 Result += "\"";
2760
2761 if (SuperClass) {
2762 Result += ", \"";
2763 Result += SuperClass->getName();
2764 Result += "\", \"";
2765 Result += CDecl->getName();
2766 Result += "\"";
2767 }
2768 else {
2769 Result += ", 0, \"";
2770 Result += CDecl->getName();
2771 Result += "\"";
2772 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002773 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002774 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002775 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002776 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002777 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002778 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002779 Result += "\n";
2780 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002781 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002782 Result += ", 0\n";
2783 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002784 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002785 Result += CDecl->getName();
2786 Result += ",0,0\n";
2787 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002788 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002789 Result += "\t,0,0,0,0\n";
2790 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002791
2792 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002793 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2794 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002795 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002796 "{\n\t&_OBJC_METACLASS_";
2797 Result += CDecl->getName();
2798 if (SuperClass) {
2799 Result += ", \"";
2800 Result += SuperClass->getName();
2801 Result += "\", \"";
2802 Result += CDecl->getName();
2803 Result += "\"";
2804 }
2805 else {
2806 Result += ", 0, \"";
2807 Result += CDecl->getName();
2808 Result += "\"";
2809 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002810 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002811 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002812 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002813 Result += ",0";
2814 else {
2815 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002816 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002817 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002818 if (LangOpts.Microsoft)
2819 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002820 Result += ")";
2821 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002822 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002823 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002824 Result += CDecl->getName();
2825 Result += "\n\t";
2826 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002827 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002828 Result += ",0";
2829 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002830 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002831 Result += CDecl->getName();
2832 Result += ", 0\n\t";
2833 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002834 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002835 Result += ",0,0";
2836 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002837 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002838 Result += CDecl->getName();
2839 Result += ", 0,0\n";
2840 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002841 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002842 Result += ",0,0,0\n";
2843 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002844}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002845
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002846/// RewriteImplementations - This routine rewrites all method implementations
2847/// and emits meta-data.
2848
2849void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002850 int ClsDefCount = ClassImplementation.size();
2851 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002852
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002853 if (ClsDefCount == 0 && CatDefCount == 0)
2854 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002855 // Rewrite implemented methods
2856 for (int i = 0; i < ClsDefCount; i++)
2857 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002858
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002859 for (int i = 0; i < CatDefCount; i++)
2860 RewriteImplementationDecl(CategoryImplementation[i]);
2861
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002862 // This is needed for use of offsetof
2863 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002864
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002865 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002866 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002867 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002868
2869 // For each implemented category, write out all its meta data.
2870 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002871 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002872
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002873 // Write objc_symtab metadata
2874 /*
2875 struct _objc_symtab
2876 {
2877 long sel_ref_cnt;
2878 SEL *refs;
2879 short cls_def_cnt;
2880 short cat_def_cnt;
2881 void *defs[cls_def_cnt + cat_def_cnt];
2882 };
2883 */
2884
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002885 Result += "\nstruct _objc_symtab {\n";
2886 Result += "\tlong sel_ref_cnt;\n";
2887 Result += "\tSEL *refs;\n";
2888 Result += "\tshort cls_def_cnt;\n";
2889 Result += "\tshort cat_def_cnt;\n";
2890 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2891 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002892
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002893 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002894 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002895 Result += "\t0, 0, " + utostr(ClsDefCount)
2896 + ", " + utostr(CatDefCount) + "\n";
2897 for (int i = 0; i < ClsDefCount; i++) {
2898 Result += "\t,&_OBJC_CLASS_";
2899 Result += ClassImplementation[i]->getName();
2900 Result += "\n";
2901 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002902
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002903 for (int i = 0; i < CatDefCount; i++) {
2904 Result += "\t,&_OBJC_CATEGORY_";
2905 Result += CategoryImplementation[i]->getClassInterface()->getName();
2906 Result += "_";
2907 Result += CategoryImplementation[i]->getName();
2908 Result += "\n";
2909 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002910
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002911 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002912
2913 // Write objc_module metadata
2914
2915 /*
2916 struct _objc_module {
2917 long version;
2918 long size;
2919 const char *name;
2920 struct _objc_symtab *symtab;
2921 }
2922 */
2923
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002924 Result += "\nstruct _objc_module {\n";
2925 Result += "\tlong version;\n";
2926 Result += "\tlong size;\n";
2927 Result += "\tconst char *name;\n";
2928 Result += "\tstruct _objc_symtab *symtab;\n";
2929 Result += "};\n\n";
2930 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002931 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002932 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2933 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002934 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002935
2936 if (LangOpts.Microsoft) {
2937 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2938 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2939 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2940 Result += "&_OBJC_MODULES;\n";
2941 Result += "#pragma data_seg(pop)\n\n";
2942 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002943}
Chris Lattner311ff022007-10-16 22:36:42 +00002944