blob: 4ac943328a32aa9d312559c4683ff18dac041e31 [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()) {
777 std::string RecName = intT->getDecl()->getIdentifier()->getName();
778 RecName += "_IMPL";
779 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
780 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(), II, 0);
781 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
782 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
783 CastExpr *castExpr = new CastExpr(castT, IV->getBase(), SourceLocation());
784 // Don't forget the parens to enforce the proper binding.
785 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), castExpr);
786 if (IV->isFreeIvar()) {
787 MemberExpr *ME = new MemberExpr(PE, true, D, IV->getLocation(), D->getType());
788 ReplaceStmt(IV, ME);
789 delete IV;
790 return ME;
791 } else {
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000792 ReplaceStmt(IV->getBase(), PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +0000793 delete IV->getBase();
794 return PE;
795 }
796 }
797 }
Steve Naroffc2a689b2007-11-15 11:33:00 +0000798 }
Steve Naroff05b8c782008-03-12 00:25:36 +0000799 Expr *Replacement = new MemberExpr(IV->getBase(), true, D,
800 IV->getLocation(), D->getType());
801 ReplaceStmt(IV, Replacement);
802 delete IV;
803 return Replacement;
Steve Naroff7e3411b2007-11-15 02:58:25 +0000804}
805
Chris Lattnerf04da132007-10-24 17:06:59 +0000806//===----------------------------------------------------------------------===//
807// Function Body / Expression rewriting
808//===----------------------------------------------------------------------===//
809
Steve Narofff3473a72007-11-09 15:20:18 +0000810Stmt *RewriteTest::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000811 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
812 isa<DoStmt>(S) || isa<ForStmt>(S))
813 Stmts.push_back(S);
814 else if (isa<ObjCForCollectionStmt>(S)) {
815 Stmts.push_back(S);
816 ObjCBcLabelNo.push_back(++BcLabelCount);
817 }
818
Chris Lattner338d1e22008-01-31 05:10:40 +0000819 SourceLocation OrigStmtEnd = S->getLocEnd();
820
821 // Start by rewriting all children.
Chris Lattner311ff022007-10-16 22:36:42 +0000822 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
823 CI != E; ++CI)
Steve Naroff75730982007-11-07 04:08:17 +0000824 if (*CI) {
Steve Narofff3473a72007-11-09 15:20:18 +0000825 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Steve Naroff75730982007-11-07 04:08:17 +0000826 if (newStmt)
827 *CI = newStmt;
828 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000829
830 // Handle specific things.
831 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
832 return RewriteAtEncode(AtEncode);
Steve Naroff7e3411b2007-11-15 02:58:25 +0000833
834 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
835 return RewriteObjCIvarRefExpr(IvarRefExpr);
Steve Naroffb42f8412007-11-05 14:50:49 +0000836
837 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
838 return RewriteAtSelector(AtSelector);
Steve Narofff69cc5d2008-01-30 19:17:43 +0000839
Steve Naroffbeaf2992007-11-03 11:27:19 +0000840 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
841 return RewriteObjCStringLiteral(AtString);
Steve Naroffebf2b562007-10-23 23:50:29 +0000842
Steve Naroff934f2762007-10-24 22:48:43 +0000843 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
844 // Before we rewrite it, put the original message expression in a comment.
845 SourceLocation startLoc = MessExpr->getLocStart();
846 SourceLocation endLoc = MessExpr->getLocEnd();
847
848 const char *startBuf = SM->getCharacterData(startLoc);
849 const char *endBuf = SM->getCharacterData(endLoc);
850
851 std::string messString;
852 messString += "// ";
853 messString.append(startBuf, endBuf-startBuf+1);
854 messString += "\n";
Steve Naroffbef11852007-10-26 20:53:56 +0000855
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000856 // FIXME: Missing definition of
857 // InsertText(clang::SourceLocation, char const*, unsigned int).
858 // InsertText(startLoc, messString.c_str(), messString.size());
Steve Naroff934f2762007-10-24 22:48:43 +0000859 // Tried this, but it didn't work either...
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000860 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffebf2b562007-10-23 23:50:29 +0000861 return RewriteMessageExpr(MessExpr);
Steve Naroff934f2762007-10-24 22:48:43 +0000862 }
Fariborz Jahanian909f02a2007-11-05 17:47:33 +0000863
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000864 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
865 return RewriteObjCTryStmt(StmtTry);
Steve Naroff2bd03922007-11-07 15:32:26 +0000866
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000867 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
868 return RewriteObjCSynchronizedStmt(StmtTry);
869
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000870 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
871 return RewriteObjCThrowStmt(StmtThrow);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000872
873 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
874 return RewriteObjCProtocolExpr(ProtocolExp);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000875
876 if (ObjCForCollectionStmt *StmtForCollection =
877 dyn_cast<ObjCForCollectionStmt>(S))
Chris Lattner338d1e22008-01-31 05:10:40 +0000878 return RewriteObjCForCollectionStmt(StmtForCollection, OrigStmtEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000879 if (BreakStmt *StmtBreakStmt =
880 dyn_cast<BreakStmt>(S))
881 return RewriteBreakStmt(StmtBreakStmt);
882 if (ContinueStmt *StmtContinueStmt =
883 dyn_cast<ContinueStmt>(S))
884 return RewriteContinueStmt(StmtContinueStmt);
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000885
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000886 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
887 isa<DoStmt>(S) || isa<ForStmt>(S)) {
888 assert(!Stmts.empty() && "Statement stack is empty");
889 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
890 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
891 && "Statement stack mismatch");
892 Stmts.pop_back();
893 }
Steve Naroff874e2322007-11-15 10:28:18 +0000894#if 0
895 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
896 CastExpr *Replacement = new CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
897 // Get the new text.
898 std::ostringstream Buf;
899 Replacement->printPretty(Buf);
900 const std::string &Str = Buf.str();
901
902 printf("CAST = %s\n", &Str[0]);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000903 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
Steve Naroff874e2322007-11-15 10:28:18 +0000904 delete S;
905 return Replacement;
906 }
907#endif
Chris Lattnere64b7772007-10-24 16:57:36 +0000908 // Return this stmt unmodified.
909 return S;
Chris Lattner311ff022007-10-16 22:36:42 +0000910}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000911
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000912/// SynthCountByEnumWithState - To print:
913/// ((unsigned int (*)
914/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
915/// (void *)objc_msgSend)((id)l_collection,
916/// sel_registerName(
917/// "countByEnumeratingWithState:objects:count:"),
918/// &enumState,
919/// (id *)items, (unsigned int)16)
920///
921void RewriteTest::SynthCountByEnumWithState(std::string &buf) {
922 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
923 "id *, unsigned int))(void *)objc_msgSend)";
924 buf += "\n\t\t";
925 buf += "((id)l_collection,\n\t\t";
926 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
927 buf += "\n\t\t";
928 buf += "&enumState, "
929 "(id *)items, (unsigned int)16)";
930}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000931
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000932/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
933/// statement to exit to its outer synthesized loop.
934///
935Stmt *RewriteTest::RewriteBreakStmt(BreakStmt *S) {
936 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
937 return S;
938 // replace break with goto __break_label
939 std::string buf;
940
941 SourceLocation startLoc = S->getLocStart();
942 buf = "goto __break_label_";
943 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000944 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000945
946 return 0;
947}
948
949/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
950/// statement to continue with its inner synthesized loop.
951///
952Stmt *RewriteTest::RewriteContinueStmt(ContinueStmt *S) {
953 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
954 return S;
955 // replace continue with goto __continue_label
956 std::string buf;
957
958 SourceLocation startLoc = S->getLocStart();
959 buf = "goto __continue_label_";
960 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +0000961 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000962
963 return 0;
964}
965
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000966/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000967/// It rewrites:
968/// for ( type elem in collection) { stmts; }
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +0000969
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000970/// Into:
971/// {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000972/// type elem;
973/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000974/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000975/// id l_collection = (id)collection;
976/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
977/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000978/// if (limit) {
979/// unsigned long startMutations = *enumState.mutationsPtr;
980/// do {
981/// unsigned long counter = 0;
982/// do {
983/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000984/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +0000985/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000986/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000987/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000988/// } while (counter < limit);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000989/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
990/// objects:items count:16]);
991/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000992/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +0000993/// }
994/// else
995/// elem = nil;
996/// }
997///
Chris Lattner338d1e22008-01-31 05:10:40 +0000998Stmt *RewriteTest::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
999 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001000 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1001 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1002 "ObjCForCollectionStmt Statement stack mismatch");
1003 assert(!ObjCBcLabelNo.empty() &&
1004 "ObjCForCollectionStmt - Label No stack empty");
1005
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001006 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001007 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001008 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001009 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001010 std::string buf;
1011 buf = "\n{\n\t";
1012 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1013 // type elem;
1014 QualType ElementType = cast<ValueDecl>(DS->getDecl())->getType();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001015 elementTypeAsString = ElementType.getAsString();
1016 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001017 buf += " ";
1018 elementName = DS->getDecl()->getName();
1019 buf += elementName;
1020 buf += ";\n\t";
1021 }
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001022 else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S->getElement())) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001023 elementName = DR->getDecl()->getName();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001024 elementTypeAsString = DR->getDecl()->getType().getAsString();
1025 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001026 else
1027 assert(false && "RewriteObjCForCollectionStmt - bad element kind");
1028
1029 // struct __objcFastEnumerationState enumState = { 0 };
1030 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1031 // id items[16];
1032 buf += "id items[16];\n\t";
1033 // id l_collection = (id)
1034 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001035 // Find start location of 'collection' the hard way!
1036 const char *startCollectionBuf = startBuf;
1037 startCollectionBuf += 3; // skip 'for'
1038 startCollectionBuf = strchr(startCollectionBuf, '(');
1039 startCollectionBuf++; // skip '('
1040 // find 'in' and skip it.
1041 while (*startCollectionBuf != ' ' ||
1042 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1043 (*(startCollectionBuf+3) != ' ' &&
1044 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1045 startCollectionBuf++;
1046 startCollectionBuf += 3;
1047
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001048 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001049 ReplaceText(startLoc, startCollectionBuf - startBuf,
1050 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001051 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001052 SourceLocation rightParenLoc = S->getRParenLoc();
1053 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1054 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001055 buf = ";\n\t";
1056
1057 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1058 // objects:items count:16];
1059 // which is synthesized into:
1060 // unsigned int limit =
1061 // ((unsigned int (*)
1062 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1063 // (void *)objc_msgSend)((id)l_collection,
1064 // sel_registerName(
1065 // "countByEnumeratingWithState:objects:count:"),
1066 // (struct __objcFastEnumerationState *)&state,
1067 // (id *)items, (unsigned int)16);
1068 buf += "unsigned long limit =\n\t\t";
1069 SynthCountByEnumWithState(buf);
1070 buf += ";\n\t";
1071 /// if (limit) {
1072 /// unsigned long startMutations = *enumState.mutationsPtr;
1073 /// do {
1074 /// unsigned long counter = 0;
1075 /// do {
1076 /// if (startMutations != *enumState.mutationsPtr)
1077 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001078 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001079 buf += "if (limit) {\n\t";
1080 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1081 buf += "do {\n\t\t";
1082 buf += "unsigned long counter = 0;\n\t\t";
1083 buf += "do {\n\t\t\t";
1084 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1085 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1086 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001087 buf += " = (";
1088 buf += elementTypeAsString;
1089 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001090 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001091 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001092
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001093 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001094 /// } while (counter < limit);
1095 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1096 /// objects:items count:16]);
1097 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001098 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001099 /// }
1100 /// else
1101 /// elem = nil;
1102 /// }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001103 ///
1104 buf = ";\n\t";
1105 buf += "__continue_label_";
1106 buf += utostr(ObjCBcLabelNo.back());
1107 buf += ": ;";
1108 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001109 buf += "} while (counter < limit);\n\t";
1110 buf += "} while (limit = ";
1111 SynthCountByEnumWithState(buf);
1112 buf += ");\n\t";
1113 buf += elementName;
1114 buf += " = nil;\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001115 buf += "__break_label_";
1116 buf += utostr(ObjCBcLabelNo.back());
1117 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001118 buf += "}\n\t";
1119 buf += "else\n\t\t";
1120 buf += elementName;
1121 buf += " = nil;\n";
1122 buf += "}\n";
1123 // Insert all these *after* the statement body.
Chris Lattner338d1e22008-01-31 05:10:40 +00001124 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001125 InsertText(endBodyLoc, buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001126 Stmts.pop_back();
1127 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001128 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001129}
1130
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001131/// RewriteObjCSynchronizedStmt -
1132/// This routine rewrites @synchronized(expr) stmt;
1133/// into:
1134/// objc_sync_enter(expr);
1135/// @try stmt @finally { objc_sync_exit(expr); }
1136///
1137Stmt *RewriteTest::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1138 // Get the start location and compute the semi location.
1139 SourceLocation startLoc = S->getLocStart();
1140 const char *startBuf = SM->getCharacterData(startLoc);
1141
1142 assert((*startBuf == '@') && "bogus @synchronized location");
1143
1144 std::string buf;
1145 buf = "objc_sync_enter";
Chris Lattneraadaf782008-01-31 19:51:04 +00001146 ReplaceText(startLoc, 13, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001147 SourceLocation endLoc = S->getSynchExpr()->getLocEnd();
1148 const char *endBuf = SM->getCharacterData(endLoc);
1149 endBuf++;
1150 const char *rparenBuf = strchr(endBuf, ')');
1151 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
1152 buf = ");\n";
1153 // declare a new scope with two variables, _stack and _rethrow.
1154 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1155 buf += "int buf[18/*32-bit i386*/];\n";
1156 buf += "char *pointers[4];} _stack;\n";
1157 buf += "id volatile _rethrow = 0;\n";
1158 buf += "objc_exception_try_enter(&_stack);\n";
1159 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001160 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001161 startLoc = S->getSynchBody()->getLocEnd();
1162 startBuf = SM->getCharacterData(startLoc);
1163
1164 assert((*startBuf == '}') && "bogus @try block");
1165 SourceLocation lastCurlyLoc = startLoc;
1166 buf = "}\nelse {\n";
1167 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1168 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1169 // FIXME: This must be objc_sync_exit(syncExpr);
1170 buf += " objc_sync_exit();\n";
1171 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1172 buf += "}\n";
1173 buf += "}";
1174
Chris Lattneraadaf782008-01-31 19:51:04 +00001175 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001176 return 0;
1177}
1178
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001179Stmt *RewriteTest::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001180 // Get the start location and compute the semi location.
1181 SourceLocation startLoc = S->getLocStart();
1182 const char *startBuf = SM->getCharacterData(startLoc);
1183
1184 assert((*startBuf == '@') && "bogus @try location");
1185
1186 std::string buf;
1187 // declare a new scope with two variables, _stack and _rethrow.
1188 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1189 buf += "int buf[18/*32-bit i386*/];\n";
1190 buf += "char *pointers[4];} _stack;\n";
1191 buf += "id volatile _rethrow = 0;\n";
1192 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001193 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001194
Chris Lattneraadaf782008-01-31 19:51:04 +00001195 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001196
1197 startLoc = S->getTryBody()->getLocEnd();
1198 startBuf = SM->getCharacterData(startLoc);
1199
1200 assert((*startBuf == '}') && "bogus @try block");
1201
1202 SourceLocation lastCurlyLoc = startLoc;
1203
1204 startLoc = startLoc.getFileLocWithOffset(1);
1205 buf = " /* @catch begin */ else {\n";
1206 buf += " id _caught = objc_exception_extract(&_stack);\n";
1207 buf += " objc_exception_try_enter (&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001208 buf += " if (_setjmp(_stack.buf))\n";
Steve Naroff75730982007-11-07 04:08:17 +00001209 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1210 buf += " else { /* @catch continue */";
1211
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001212 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001213
1214 bool sawIdTypedCatch = false;
1215 Stmt *lastCatchBody = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001216 ObjCAtCatchStmt *catchList = S->getCatchStmts();
Steve Naroff75730982007-11-07 04:08:17 +00001217 while (catchList) {
1218 Stmt *catchStmt = catchList->getCatchParamStmt();
1219
1220 if (catchList == S->getCatchStmts())
1221 buf = "if ("; // we are generating code for the first catch clause
1222 else
1223 buf = "else if (";
1224 startLoc = catchList->getLocStart();
1225 startBuf = SM->getCharacterData(startLoc);
1226
1227 assert((*startBuf == '@') && "bogus @catch location");
1228
1229 const char *lParenLoc = strchr(startBuf, '(');
1230
Steve Naroffbe4b3332008-02-01 22:08:12 +00001231 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001232 // Now rewrite the body...
1233 lastCatchBody = catchList->getCatchBody();
1234 SourceLocation rParenLoc = catchList->getRParenLoc();
1235 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1236 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1237 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1238 assert((*rParenBuf == ')') && "bogus @catch paren location");
1239 assert((*bodyBuf == '{') && "bogus @catch body location");
1240
1241 buf += "1) { id _tmp = _caught;";
1242 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1,
1243 buf.c_str(), buf.size());
1244 } else if (DeclStmt *declStmt = dyn_cast<DeclStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001245 QualType t = dyn_cast<ValueDecl>(declStmt->getDecl())->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001246 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001247 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001248 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001249 sawIdTypedCatch = true;
1250 } else if (const PointerType *pType = t->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001251 ObjCInterfaceType *cls; // Should be a pointer to a class.
Steve Naroff75730982007-11-07 04:08:17 +00001252
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001253 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroff75730982007-11-07 04:08:17 +00001254 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001255 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Steve Naroff75730982007-11-07 04:08:17 +00001256 buf += cls->getDecl()->getName();
Steve Naroff21867b12007-11-07 18:43:40 +00001257 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001258 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001259 }
1260 }
1261 // Now rewrite the body...
1262 lastCatchBody = catchList->getCatchBody();
1263 SourceLocation rParenLoc = catchList->getRParenLoc();
1264 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1265 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1266 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1267 assert((*rParenBuf == ')') && "bogus @catch paren location");
1268 assert((*bodyBuf == '{') && "bogus @catch body location");
1269
1270 buf = " = _caught;";
1271 // Here we replace ") {" with "= _caught;" (which initializes and
1272 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001273 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001274 } else if (!isa<NullStmt>(catchStmt)) {
Steve Naroff75730982007-11-07 04:08:17 +00001275 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001276 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001277 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001278 catchList = catchList->getNextCatchStmt();
1279 }
1280 // Complete the catch list...
1281 if (lastCatchBody) {
1282 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1283 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1284 assert((*bodyBuf == '}') && "bogus @catch body location");
1285 bodyLoc = bodyLoc.getFileLocWithOffset(1);
1286 buf = " } } /* @catch end */\n";
1287
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001288 InsertText(bodyLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001289
1290 // Set lastCurlyLoc
1291 lastCurlyLoc = lastCatchBody->getLocEnd();
1292 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001293 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001294 startLoc = finalStmt->getLocStart();
1295 startBuf = SM->getCharacterData(startLoc);
1296 assert((*startBuf == '@') && "bogus @finally start");
1297
1298 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001299 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001300
1301 Stmt *body = finalStmt->getFinallyBody();
1302 SourceLocation startLoc = body->getLocStart();
1303 SourceLocation endLoc = body->getLocEnd();
1304 const char *startBuf = SM->getCharacterData(startLoc);
1305 const char *endBuf = SM->getCharacterData(endLoc);
1306 assert((*startBuf == '{') && "bogus @finally body location");
1307 assert((*endBuf == '}') && "bogus @finally body location");
1308
1309 startLoc = startLoc.getFileLocWithOffset(1);
1310 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001311 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001312 endLoc = endLoc.getFileLocWithOffset(-1);
1313 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001314 InsertText(endLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001315
1316 // Set lastCurlyLoc
1317 lastCurlyLoc = body->getLocEnd();
1318 }
1319 // Now emit the final closing curly brace...
1320 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1321 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001322 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001323 return 0;
1324}
1325
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001326Stmt *RewriteTest::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001327 return 0;
1328}
1329
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001330Stmt *RewriteTest::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001331 return 0;
1332}
1333
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001334// This can't be done with ReplaceStmt(S, ThrowExpr), since
Steve Naroff2bd03922007-11-07 15:32:26 +00001335// the throw expression is typically a message expression that's already
1336// been rewritten! (which implies the SourceLocation's are invalid).
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001337Stmt *RewriteTest::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001338 // Get the start location and compute the semi location.
1339 SourceLocation startLoc = S->getLocStart();
1340 const char *startBuf = SM->getCharacterData(startLoc);
1341
1342 assert((*startBuf == '@') && "bogus @throw location");
1343
1344 std::string buf;
1345 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001346 if (S->getThrowExpr())
1347 buf = "objc_exception_throw(";
1348 else // add an implicit argument
1349 buf = "objc_exception_throw(_caught";
Chris Lattneraadaf782008-01-31 19:51:04 +00001350 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001351 const char *semiBuf = strchr(startBuf, ';');
1352 assert((*semiBuf == ';') && "@throw: can't find ';'");
1353 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1354 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001355 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001356 return 0;
1357}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001358
Chris Lattnere64b7772007-10-24 16:57:36 +00001359Stmt *RewriteTest::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001360 // Create a new string expression.
1361 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001362 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00001363 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding,
1364 EncodingRecordTypes);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001365 Expr *Replacement = new StringLiteral(StrEncoding.c_str(),
1366 StrEncoding.length(), false, StrType,
Chris Lattner01c57482007-10-17 22:35:30 +00001367 SourceLocation(), SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001368 ReplaceStmt(Exp, Replacement);
Chris Lattnere365c502007-11-30 22:25:36 +00001369
Chris Lattner07506182007-11-30 22:53:43 +00001370 // Replace this subexpr in the parent.
Chris Lattnere64b7772007-10-24 16:57:36 +00001371 delete Exp;
1372 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001373}
1374
Steve Naroffb42f8412007-11-05 14:50:49 +00001375Stmt *RewriteTest::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1376 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1377 // Create a call to sel_registerName("selName").
1378 llvm::SmallVector<Expr*, 8> SelExprs;
1379 QualType argType = Context->getPointerType(Context->CharTy);
1380 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1381 Exp->getSelector().getName().size(),
1382 false, argType, SourceLocation(),
1383 SourceLocation()));
1384 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1385 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001386 ReplaceStmt(Exp, SelExp);
Steve Naroffb42f8412007-11-05 14:50:49 +00001387 delete Exp;
1388 return SelExp;
1389}
1390
Steve Naroff934f2762007-10-24 22:48:43 +00001391CallExpr *RewriteTest::SynthesizeCallToFunctionDecl(
1392 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001393 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001394 QualType msgSendType = FD->getType();
Steve Naroffebf2b562007-10-23 23:50:29 +00001395
1396 // Create a reference to the objc_msgSend() declaration.
Steve Naroff934f2762007-10-24 22:48:43 +00001397 DeclRefExpr *DRE = new DeclRefExpr(FD, msgSendType, SourceLocation());
Steve Naroffebf2b562007-10-23 23:50:29 +00001398
1399 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001400 QualType pToFunc = Context->getPointerType(msgSendType);
Steve Naroffebf2b562007-10-23 23:50:29 +00001401 ImplicitCastExpr *ICE = new ImplicitCastExpr(pToFunc, DRE);
1402
1403 const FunctionType *FT = msgSendType->getAsFunctionType();
Chris Lattnere64b7772007-10-24 16:57:36 +00001404
Steve Naroff934f2762007-10-24 22:48:43 +00001405 return new CallExpr(ICE, args, nargs, FT->getResultType(), SourceLocation());
1406}
1407
Steve Naroffd5255f52007-11-01 13:24:47 +00001408static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1409 const char *&startRef, const char *&endRef) {
1410 while (startBuf < endBuf) {
1411 if (*startBuf == '<')
1412 startRef = startBuf; // mark the start.
1413 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001414 if (startRef && *startRef == '<') {
1415 endRef = startBuf; // mark the end.
1416 return true;
1417 }
1418 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001419 }
1420 startBuf++;
1421 }
1422 return false;
1423}
1424
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001425static void scanToNextArgument(const char *&argRef) {
1426 int angle = 0;
1427 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1428 if (*argRef == '<')
1429 angle++;
1430 else if (*argRef == '>')
1431 angle--;
1432 argRef++;
1433 }
1434 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1435}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001436
Steve Naroffd5255f52007-11-01 13:24:47 +00001437bool RewriteTest::needToScanForQualifiers(QualType T) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001438
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001439 if (T == Context->getObjCIdType())
Steve Naroffd5255f52007-11-01 13:24:47 +00001440 return true;
1441
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001442 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001443 return true;
1444
Steve Naroffd5255f52007-11-01 13:24:47 +00001445 if (const PointerType *pType = T->getAsPointerType()) {
Steve Naroff9165ad32007-10-31 04:38:33 +00001446 Type *pointeeType = pType->getPointeeType().getTypePtr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001447 if (isa<ObjCQualifiedInterfaceType>(pointeeType))
Steve Naroff9165ad32007-10-31 04:38:33 +00001448 return true; // we have "Class <Protocol> *".
1449 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001450 return false;
1451}
1452
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001453void RewriteTest::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001454 SourceLocation Loc;
1455 QualType Type;
1456 const FunctionTypeProto *proto = 0;
1457 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1458 Loc = VD->getLocation();
1459 Type = VD->getType();
1460 }
1461 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1462 Loc = FD->getLocation();
1463 // Check for ObjC 'id' and class types that have been adorned with protocol
1464 // information (id<p>, C<p>*). The protocol references need to be rewritten!
1465 const FunctionType *funcType = FD->getType()->getAsFunctionType();
1466 assert(funcType && "missing function type");
1467 proto = dyn_cast<FunctionTypeProto>(funcType);
1468 if (!proto)
1469 return;
1470 Type = proto->getResultType();
1471 }
1472 else
1473 return;
Steve Naroffd5255f52007-11-01 13:24:47 +00001474
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001475 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00001476 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001477
1478 const char *endBuf = SM->getCharacterData(Loc);
1479 const char *startBuf = endBuf;
Chris Lattner26de4652007-12-02 01:13:47 +00001480 while (*startBuf != ';' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00001481 startBuf--; // scan backward (from the decl location) for return type.
1482 const char *startRef = 0, *endRef = 0;
1483 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1484 // Get the locations of the startRef, endRef.
1485 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
1486 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
1487 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001488 InsertText(LessLoc, "/*", 2);
1489 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00001490 }
1491 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001492 if (!proto)
1493 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00001494 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001495 const char *startBuf = SM->getCharacterData(Loc);
1496 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00001497 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
1498 if (needToScanForQualifiers(proto->getArgType(i))) {
1499 // Since types are unique, we need to scan the buffer.
Steve Naroffd5255f52007-11-01 13:24:47 +00001500
Steve Naroffd5255f52007-11-01 13:24:47 +00001501 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001502 // scan forward (from the decl location) for argument types.
1503 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00001504 const char *startRef = 0, *endRef = 0;
1505 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1506 // Get the locations of the startRef, endRef.
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001507 SourceLocation LessLoc =
1508 Loc.getFileLocWithOffset(startRef-startFuncBuf);
1509 SourceLocation GreaterLoc =
1510 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00001511 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001512 InsertText(LessLoc, "/*", 2);
1513 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00001514 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001515 startBuf = ++endBuf;
1516 }
1517 else {
1518 while (*startBuf != ')' && *startBuf != ',')
1519 startBuf++; // scan forward (from the decl location) for argument types.
1520 startBuf++;
1521 }
Steve Naroffd5255f52007-11-01 13:24:47 +00001522 }
Steve Naroff9165ad32007-10-31 04:38:33 +00001523}
1524
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001525// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
1526void RewriteTest::SynthSelGetUidFunctionDecl() {
1527 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
1528 llvm::SmallVector<QualType, 16> ArgTys;
1529 ArgTys.push_back(Context->getPointerType(
1530 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001531 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001532 &ArgTys[0], ArgTys.size(),
1533 false /*isVariadic*/);
1534 SelGetUidFunctionDecl = new FunctionDecl(SourceLocation(),
1535 SelGetUidIdent, getFuncType,
1536 FunctionDecl::Extern, false, 0);
1537}
1538
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001539// SynthGetProtocolFunctionDecl - Protocol objc_getProtocol(const char *proto);
1540void RewriteTest::SynthGetProtocolFunctionDecl() {
1541 IdentifierInfo *SelGetProtoIdent = &Context->Idents.get("objc_getProtocol");
1542 llvm::SmallVector<QualType, 16> ArgTys;
1543 ArgTys.push_back(Context->getPointerType(
1544 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001545 QualType getFuncType = Context->getFunctionType(Context->getObjCProtoType(),
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00001546 &ArgTys[0], ArgTys.size(),
1547 false /*isVariadic*/);
1548 GetProtocolFunctionDecl = new FunctionDecl(SourceLocation(),
1549 SelGetProtoIdent, getFuncType,
1550 FunctionDecl::Extern, false, 0);
1551}
1552
Steve Naroff09b266e2007-10-30 23:14:51 +00001553void RewriteTest::RewriteFunctionDecl(FunctionDecl *FD) {
1554 // declared in <objc/objc.h>
Steve Naroffbeaf2992007-11-03 11:27:19 +00001555 if (strcmp(FD->getName(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00001556 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00001557 return;
1558 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001559 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00001560}
1561
Steve Naroffc0a123c2008-03-11 17:37:02 +00001562// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
1563void RewriteTest::SynthSuperContructorFunctionDecl() {
1564 if (SuperContructorFunctionDecl)
1565 return;
1566 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_super");
1567 llvm::SmallVector<QualType, 16> ArgTys;
1568 QualType argT = Context->getObjCIdType();
1569 assert(!argT.isNull() && "Can't find 'id' type");
1570 ArgTys.push_back(argT);
1571 ArgTys.push_back(argT);
1572 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
1573 &ArgTys[0], ArgTys.size(),
1574 false);
1575 SuperContructorFunctionDecl = new FunctionDecl(SourceLocation(),
1576 msgSendIdent, msgSendType,
1577 FunctionDecl::Extern, false, 0);
1578}
1579
Steve Naroff09b266e2007-10-30 23:14:51 +00001580// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
1581void RewriteTest::SynthMsgSendFunctionDecl() {
1582 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
1583 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001584 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001585 assert(!argT.isNull() && "Can't find 'id' type");
1586 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001587 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00001588 assert(!argT.isNull() && "Can't find 'SEL' type");
1589 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001590 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001591 &ArgTys[0], ArgTys.size(),
1592 true /*isVariadic*/);
1593 MsgSendFunctionDecl = new FunctionDecl(SourceLocation(),
1594 msgSendIdent, msgSendType,
1595 FunctionDecl::Extern, false, 0);
1596}
1597
Steve Naroff874e2322007-11-15 10:28:18 +00001598// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
1599void RewriteTest::SynthMsgSendSuperFunctionDecl() {
1600 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
1601 llvm::SmallVector<QualType, 16> ArgTys;
1602 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1603 &Context->Idents.get("objc_super"), 0);
1604 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1605 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1606 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001607 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00001608 assert(!argT.isNull() && "Can't find 'SEL' type");
1609 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001610 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00001611 &ArgTys[0], ArgTys.size(),
1612 true /*isVariadic*/);
1613 MsgSendSuperFunctionDecl = new FunctionDecl(SourceLocation(),
1614 msgSendIdent, msgSendType,
1615 FunctionDecl::Extern, false, 0);
1616}
1617
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001618// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
1619void RewriteTest::SynthMsgSendStretFunctionDecl() {
1620 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
1621 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001622 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001623 assert(!argT.isNull() && "Can't find 'id' type");
1624 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001625 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001626 assert(!argT.isNull() && "Can't find 'SEL' type");
1627 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001628 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001629 &ArgTys[0], ArgTys.size(),
1630 true /*isVariadic*/);
1631 MsgSendStretFunctionDecl = new FunctionDecl(SourceLocation(),
1632 msgSendIdent, msgSendType,
1633 FunctionDecl::Extern, false, 0);
1634}
1635
1636// SynthMsgSendSuperStretFunctionDecl -
1637// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
1638void RewriteTest::SynthMsgSendSuperStretFunctionDecl() {
1639 IdentifierInfo *msgSendIdent =
1640 &Context->Idents.get("objc_msgSendSuper_stret");
1641 llvm::SmallVector<QualType, 16> ArgTys;
1642 RecordDecl *RD = new RecordDecl(Decl::Struct, SourceLocation(),
1643 &Context->Idents.get("objc_super"), 0);
1644 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
1645 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
1646 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001647 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001648 assert(!argT.isNull() && "Can't find 'SEL' type");
1649 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001650 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001651 &ArgTys[0], ArgTys.size(),
1652 true /*isVariadic*/);
1653 MsgSendSuperStretFunctionDecl = new FunctionDecl(SourceLocation(),
1654 msgSendIdent, msgSendType,
1655 FunctionDecl::Extern, false, 0);
1656}
1657
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001658// SynthMsgSendFpretFunctionDecl - id objc_msgSend_fpret(id self, SEL op, ...);
1659void RewriteTest::SynthMsgSendFpretFunctionDecl() {
1660 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
1661 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001662 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001663 assert(!argT.isNull() && "Can't find 'id' type");
1664 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001665 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001666 assert(!argT.isNull() && "Can't find 'SEL' type");
1667 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001668 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001669 &ArgTys[0], ArgTys.size(),
1670 true /*isVariadic*/);
1671 MsgSendFpretFunctionDecl = new FunctionDecl(SourceLocation(),
1672 msgSendIdent, msgSendType,
1673 FunctionDecl::Extern, false, 0);
1674}
1675
Steve Naroff09b266e2007-10-30 23:14:51 +00001676// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
1677void RewriteTest::SynthGetClassFunctionDecl() {
1678 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
1679 llvm::SmallVector<QualType, 16> ArgTys;
1680 ArgTys.push_back(Context->getPointerType(
1681 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001682 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00001683 &ArgTys[0], ArgTys.size(),
1684 false /*isVariadic*/);
1685 GetClassFunctionDecl = new FunctionDecl(SourceLocation(),
1686 getClassIdent, getClassType,
1687 FunctionDecl::Extern, false, 0);
1688}
1689
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001690// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
1691void RewriteTest::SynthGetMetaClassFunctionDecl() {
1692 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
1693 llvm::SmallVector<QualType, 16> ArgTys;
1694 ArgTys.push_back(Context->getPointerType(
1695 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001696 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001697 &ArgTys[0], ArgTys.size(),
1698 false /*isVariadic*/);
1699 GetMetaClassFunctionDecl = new FunctionDecl(SourceLocation(),
1700 getClassIdent, getClassType,
1701 FunctionDecl::Extern, false, 0);
1702}
1703
Steve Naroff96984642007-11-08 14:30:50 +00001704// SynthCFStringFunctionDecl - id __builtin___CFStringMakeConstantString(const char *name);
1705void RewriteTest::SynthCFStringFunctionDecl() {
1706 IdentifierInfo *getClassIdent = &Context->Idents.get("__builtin___CFStringMakeConstantString");
1707 llvm::SmallVector<QualType, 16> ArgTys;
1708 ArgTys.push_back(Context->getPointerType(
1709 Context->CharTy.getQualifiedType(QualType::Const)));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001710 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff96984642007-11-08 14:30:50 +00001711 &ArgTys[0], ArgTys.size(),
1712 false /*isVariadic*/);
1713 CFStringFunctionDecl = new FunctionDecl(SourceLocation(),
1714 getClassIdent, getClassType,
1715 FunctionDecl::Extern, false, 0);
1716}
1717
Steve Naroffbeaf2992007-11-03 11:27:19 +00001718Stmt *RewriteTest::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroff96984642007-11-08 14:30:50 +00001719#if 1
1720 // This rewrite is specific to GCC, which has builtin support for CFString.
1721 if (!CFStringFunctionDecl)
1722 SynthCFStringFunctionDecl();
1723 // Create a call to __builtin___CFStringMakeConstantString("cstr").
1724 llvm::SmallVector<Expr*, 8> StrExpr;
1725 StrExpr.push_back(Exp->getString());
1726 CallExpr *call = SynthesizeCallToFunctionDecl(CFStringFunctionDecl,
1727 &StrExpr[0], StrExpr.size());
1728 // cast to NSConstantString *
1729 CastExpr *cast = new CastExpr(Exp->getType(), call, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001730 ReplaceStmt(Exp, cast);
Steve Naroff96984642007-11-08 14:30:50 +00001731 delete Exp;
1732 return cast;
1733#else
Steve Naroffbeaf2992007-11-03 11:27:19 +00001734 assert(ConstantStringClassReference && "Can't find constant string reference");
1735 llvm::SmallVector<Expr*, 4> InitExprs;
1736
1737 // Synthesize "(Class)&_NSConstantStringClassReference"
1738 DeclRefExpr *ClsRef = new DeclRefExpr(ConstantStringClassReference,
1739 ConstantStringClassReference->getType(),
1740 SourceLocation());
1741 QualType expType = Context->getPointerType(ClsRef->getType());
1742 UnaryOperator *Unop = new UnaryOperator(ClsRef, UnaryOperator::AddrOf,
1743 expType, SourceLocation());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001744 CastExpr *cast = new CastExpr(Context->getObjCClassType(), Unop,
Steve Naroffbeaf2992007-11-03 11:27:19 +00001745 SourceLocation());
1746 InitExprs.push_back(cast); // set the 'isa'.
1747 InitExprs.push_back(Exp->getString()); // set "char *bytes".
1748 unsigned IntSize = static_cast<unsigned>(
1749 Context->getTypeSize(Context->IntTy, Exp->getLocStart()));
1750 llvm::APInt IntVal(IntSize, Exp->getString()->getByteLength());
1751 IntegerLiteral *len = new IntegerLiteral(IntVal, Context->IntTy,
1752 Exp->getLocStart());
1753 InitExprs.push_back(len); // set "int numBytes".
1754
1755 // struct NSConstantString
1756 QualType CFConstantStrType = Context->getCFConstantStringType();
1757 // (struct NSConstantString) { <exprs from above> }
1758 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1759 &InitExprs[0], InitExprs.size(),
1760 SourceLocation());
Steve Naroffe9b12192008-01-14 18:19:28 +00001761 CompoundLiteralExpr *StrRep = new CompoundLiteralExpr(CFConstantStrType, ILE, false);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001762 // struct NSConstantString *
1763 expType = Context->getPointerType(StrRep->getType());
1764 Unop = new UnaryOperator(StrRep, UnaryOperator::AddrOf, expType,
1765 SourceLocation());
Steve Naroff352336b2007-11-05 14:36:37 +00001766 // cast to NSConstantString *
1767 cast = new CastExpr(Exp->getType(), Unop, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001768 ReplaceStmt(Exp, cast);
Steve Naroffbeaf2992007-11-03 11:27:19 +00001769 delete Exp;
Steve Naroff352336b2007-11-05 14:36:37 +00001770 return cast;
Steve Naroff96984642007-11-08 14:30:50 +00001771#endif
Steve Naroffbeaf2992007-11-03 11:27:19 +00001772}
1773
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001774ObjCInterfaceDecl *RewriteTest::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001775 // check if we are sending a message to 'super'
1776 if (CurMethodDecl && CurMethodDecl->isInstance()) {
Steve Naroff874e2322007-11-15 10:28:18 +00001777 if (CastExpr *CE = dyn_cast<CastExpr>(recExpr)) {
1778 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
1779 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
1780 if (!strcmp(PVD->getName(), "self")) {
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001781 // is this id<P1..> type?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001782 if (CE->getType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001783 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00001784 if (const PointerType *PT = CE->getType()->getAsPointerType()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001785 if (ObjCInterfaceType *IT =
1786 dyn_cast<ObjCInterfaceType>(PT->getPointeeType())) {
Steve Naroff874e2322007-11-15 10:28:18 +00001787 if (IT->getDecl() ==
1788 CurMethodDecl->getClassInterface()->getSuperClass())
1789 return IT->getDecl();
1790 }
1791 }
1792 }
1793 }
1794 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001795 }
Steve Naroff874e2322007-11-15 10:28:18 +00001796 }
1797 return 0;
1798}
1799
1800// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
1801QualType RewriteTest::getSuperStructType() {
1802 if (!SuperStructDecl) {
1803 SuperStructDecl = new RecordDecl(Decl::Struct, SourceLocation(),
1804 &Context->Idents.get("objc_super"), 0);
1805 QualType FieldTypes[2];
1806
1807 // struct objc_object *receiver;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001808 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00001809 // struct objc_class *super;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001810 FieldTypes[1] = Context->getObjCClassType();
Steve Naroff874e2322007-11-15 10:28:18 +00001811 // Create fields
1812 FieldDecl *FieldDecls[2];
1813
1814 for (unsigned i = 0; i < 2; ++i)
1815 FieldDecls[i] = new FieldDecl(SourceLocation(), 0, FieldTypes[i]);
1816
1817 SuperStructDecl->defineBody(FieldDecls, 4);
1818 }
1819 return Context->getTagDeclType(SuperStructDecl);
1820}
1821
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001822Stmt *RewriteTest::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00001823 if (!SelGetUidFunctionDecl)
1824 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001825 if (!MsgSendFunctionDecl)
1826 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00001827 if (!MsgSendSuperFunctionDecl)
1828 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001829 if (!MsgSendStretFunctionDecl)
1830 SynthMsgSendStretFunctionDecl();
1831 if (!MsgSendSuperStretFunctionDecl)
1832 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001833 if (!MsgSendFpretFunctionDecl)
1834 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00001835 if (!GetClassFunctionDecl)
1836 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001837 if (!GetMetaClassFunctionDecl)
1838 SynthGetMetaClassFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001839
Steve Naroff874e2322007-11-15 10:28:18 +00001840 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001841 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
1842 // May need to use objc_msgSend_stret() as well.
1843 FunctionDecl *MsgSendStretFlavor = 0;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001844 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001845 QualType resultType = mDecl->getResultType();
1846 if (resultType.getCanonicalType()->isStructureType()
1847 || resultType.getCanonicalType()->isUnionType())
1848 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +00001849 else if (resultType.getCanonicalType()->isRealFloatingType())
1850 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001851 }
Steve Naroff874e2322007-11-15 10:28:18 +00001852
Steve Naroff934f2762007-10-24 22:48:43 +00001853 // Synthesize a call to objc_msgSend().
1854 llvm::SmallVector<Expr*, 8> MsgExprs;
1855 IdentifierInfo *clsName = Exp->getClassName();
1856
1857 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
1858 if (clsName) { // class message.
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001859 if (!strcmp(clsName->getName(), "super")) {
1860 MsgSendFlavor = MsgSendSuperFunctionDecl;
1861 if (MsgSendStretFlavor)
1862 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
1863 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1864
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001865 ObjCInterfaceDecl *SuperDecl =
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001866 CurMethodDecl->getClassInterface()->getSuperClass();
1867
1868 llvm::SmallVector<Expr*, 4> InitExprs;
1869
1870 // set the receiver to self, the first argument to all methods.
1871 InitExprs.push_back(new DeclRefExpr(CurMethodDecl->getSelfDecl(),
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001872 Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001873 SourceLocation()));
1874 llvm::SmallVector<Expr*, 8> ClsExprs;
1875 QualType argType = Context->getPointerType(Context->CharTy);
1876 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1877 SuperDecl->getIdentifier()->getLength(),
1878 false, argType, SourceLocation(),
1879 SourceLocation()));
1880 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
1881 &ClsExprs[0],
1882 ClsExprs.size());
1883 // To turn off a warning, type-cast to 'id'
1884 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001885 new CastExpr(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001886 Cls, SourceLocation())); // set 'super class', using objc_getClass().
1887 // struct objc_super
1888 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00001889 Expr *SuperRep;
Steve Naroffc0a123c2008-03-11 17:37:02 +00001890
Steve Naroff23f41272008-03-11 18:14:26 +00001891 if (LangOpts.Microsoft) {
1892 SynthSuperContructorFunctionDecl();
1893 // Simulate a contructor call...
1894 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1895 superType, SourceLocation());
1896 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1897 superType, SourceLocation());
1898 } else {
1899 // (struct objc_super) { <exprs from above> }
1900 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1901 &InitExprs[0], InitExprs.size(),
1902 SourceLocation());
1903 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1904 }
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001905 // struct objc_super *
1906 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1907 Context->getPointerType(SuperRep->getType()),
1908 SourceLocation());
1909 MsgExprs.push_back(Unop);
1910 } else {
1911 llvm::SmallVector<Expr*, 8> ClsExprs;
1912 QualType argType = Context->getPointerType(Context->CharTy);
1913 ClsExprs.push_back(new StringLiteral(clsName->getName(),
1914 clsName->getLength(),
1915 false, argType, SourceLocation(),
1916 SourceLocation()));
1917 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
1918 &ClsExprs[0],
1919 ClsExprs.size());
1920 MsgExprs.push_back(Cls);
1921 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001922 } else { // instance message.
1923 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00001924
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001925 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00001926 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00001927 if (MsgSendStretFlavor)
1928 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00001929 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
1930
1931 llvm::SmallVector<Expr*, 4> InitExprs;
1932
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001933 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001934 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001935 recExpr, SourceLocation())); // set the 'receiver'.
Steve Naroff874e2322007-11-15 10:28:18 +00001936
1937 llvm::SmallVector<Expr*, 8> ClsExprs;
1938 QualType argType = Context->getPointerType(Context->CharTy);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00001939 ClsExprs.push_back(new StringLiteral(SuperDecl->getIdentifier()->getName(),
1940 SuperDecl->getIdentifier()->getLength(),
Steve Naroff874e2322007-11-15 10:28:18 +00001941 false, argType, SourceLocation(),
1942 SourceLocation()));
1943 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001944 &ClsExprs[0],
1945 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00001946 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001947 InitExprs.push_back(
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001948 new CastExpr(Context->getObjCIdType(),
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00001949 Cls, SourceLocation())); // set 'super class', using objc_getClass().
Steve Naroff874e2322007-11-15 10:28:18 +00001950 // struct objc_super
1951 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00001952 Expr *SuperRep;
1953
1954 if (LangOpts.Microsoft) {
1955 SynthSuperContructorFunctionDecl();
1956 // Simulate a contructor call...
1957 DeclRefExpr *DRE = new DeclRefExpr(SuperContructorFunctionDecl,
1958 superType, SourceLocation());
1959 SuperRep = new CallExpr(DRE, &InitExprs[0], InitExprs.size(),
1960 superType, SourceLocation());
1961 } else {
1962 // (struct objc_super) { <exprs from above> }
1963 InitListExpr *ILE = new InitListExpr(SourceLocation(),
1964 &InitExprs[0], InitExprs.size(),
1965 SourceLocation());
1966 SuperRep = new CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
1967 }
Steve Naroff874e2322007-11-15 10:28:18 +00001968 // struct objc_super *
1969 Expr *Unop = new UnaryOperator(SuperRep, UnaryOperator::AddrOf,
1970 Context->getPointerType(SuperRep->getType()),
1971 SourceLocation());
1972 MsgExprs.push_back(Unop);
1973 } else {
Steve Naroff3c64d9e2008-03-12 13:19:12 +00001974 //recExpr->dump();
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00001975 // Remove all type-casts because it may contain objc-style types; e.g.
1976 // Foo<Proto> *.
1977 while (CastExpr *CE = dyn_cast<CastExpr>(recExpr))
1978 recExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 recExpr = new CastExpr(Context->getObjCIdType(), recExpr, SourceLocation());
Steve Naroff874e2322007-11-15 10:28:18 +00001980 MsgExprs.push_back(recExpr);
1981 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00001982 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00001983 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00001984 llvm::SmallVector<Expr*, 8> SelExprs;
1985 QualType argType = Context->getPointerType(Context->CharTy);
1986 SelExprs.push_back(new StringLiteral(Exp->getSelector().getName().c_str(),
1987 Exp->getSelector().getName().size(),
1988 false, argType, SourceLocation(),
1989 SourceLocation()));
1990 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1991 &SelExprs[0], SelExprs.size());
1992 MsgExprs.push_back(SelExp);
1993
1994 // Now push any user supplied arguments.
1995 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00001996 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00001997 // Make all implicit casts explicit...ICE comes in handy:-)
1998 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
1999 // Reuse the ICE type, it is exactly what the doctor ordered.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002000 userExpr = new CastExpr(ICE->getType()->isObjCQualifiedIdType()
2001 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002002 : ICE->getType(), userExpr, SourceLocation());
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002003 }
2004 // Make id<P...> cast into an 'id' cast.
2005 else if (CastExpr *CE = dyn_cast<CastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002006 if (CE->getType()->isObjCQualifiedIdType()) {
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002007 while ((CE = dyn_cast<CastExpr>(userExpr)))
2008 userExpr = CE->getSubExpr();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002009 userExpr = new CastExpr(Context->getObjCIdType(),
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002010 userExpr, SourceLocation());
2011 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00002012 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002013 MsgExprs.push_back(userExpr);
Steve Naroff934f2762007-10-24 22:48:43 +00002014 // We've transferred the ownership to MsgExprs. Null out the argument in
2015 // the original expression, since we will delete it below.
2016 Exp->setArg(i, 0);
2017 }
Steve Naroffab972d32007-11-04 22:37:50 +00002018 // Generate the funky cast.
2019 CastExpr *cast;
2020 llvm::SmallVector<QualType, 8> ArgTypes;
2021 QualType returnType;
2022
2023 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002024 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2025 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2026 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002027 ArgTypes.push_back(Context->getObjCIdType());
2028 ArgTypes.push_back(Context->getObjCSelType());
2029 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002030 // Push any user argument types.
Steve Naroff352336b2007-11-05 14:36:37 +00002031 for (int i = 0; i < mDecl->getNumParams(); i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002032 QualType t = mDecl->getParamDecl(i)->getType()->isObjCQualifiedIdType()
2033 ? Context->getObjCIdType()
Fariborz Jahanianc5692492007-12-17 21:03:50 +00002034 : mDecl->getParamDecl(i)->getType();
Steve Naroff352336b2007-11-05 14:36:37 +00002035 ArgTypes.push_back(t);
2036 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002037 returnType = mDecl->getResultType()->isObjCQualifiedIdType()
2038 ? Context->getObjCIdType() : mDecl->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002039 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002040 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002041 }
2042 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002043 QualType msgSendType = MsgSendFlavor->getType();
Steve Naroffab972d32007-11-04 22:37:50 +00002044
2045 // Create a reference to the objc_msgSend() declaration.
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002046 DeclRefExpr *DRE = new DeclRefExpr(MsgSendFlavor, msgSendType,
2047 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002048
2049 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2050 // If we don't do this cast, we get the following bizarre warning/note:
2051 // xx.m:13: warning: function called through a non-compatible type
2052 // xx.m:13: note: if this code is reached, the program will abort
2053 cast = new CastExpr(Context->getPointerType(Context->VoidTy), DRE,
2054 SourceLocation());
Steve Naroff335eafa2007-11-15 12:35:21 +00002055
Steve Naroffab972d32007-11-04 22:37:50 +00002056 // Now do the "normal" pointer to function cast.
2057 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002058 &ArgTypes[0], ArgTypes.size(),
2059 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Steve Naroffab972d32007-11-04 22:37:50 +00002060 castType = Context->getPointerType(castType);
2061 cast = new CastExpr(castType, cast, SourceLocation());
2062
2063 // Don't forget the parens to enforce the proper binding.
2064 ParenExpr *PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2065
2066 const FunctionType *FT = msgSendType->getAsFunctionType();
2067 CallExpr *CE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2068 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002069 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002070 if (MsgSendStretFlavor) {
2071 // We have the method which returns a struct/union. Must also generate
2072 // call to objc_msgSend_stret and hang both varieties on a conditional
2073 // expression which dictate which one to envoke depending on size of
2074 // method's return type.
2075
2076 // Create a reference to the objc_msgSend_stret() declaration.
2077 DeclRefExpr *STDRE = new DeclRefExpr(MsgSendStretFlavor, msgSendType,
2078 SourceLocation());
2079 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2080 cast = new CastExpr(Context->getPointerType(Context->VoidTy), STDRE,
2081 SourceLocation());
2082 // Now do the "normal" pointer to function cast.
2083 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002084 &ArgTypes[0], ArgTypes.size(),
2085 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002086 castType = Context->getPointerType(castType);
2087 cast = new CastExpr(castType, cast, SourceLocation());
2088
2089 // Don't forget the parens to enforce the proper binding.
2090 PE = new ParenExpr(SourceLocation(), SourceLocation(), cast);
2091
2092 FT = msgSendType->getAsFunctionType();
2093 CallExpr *STCE = new CallExpr(PE, &MsgExprs[0], MsgExprs.size(),
2094 FT->getResultType(), SourceLocation());
2095
2096 // Build sizeof(returnType)
2097 SizeOfAlignOfTypeExpr *sizeofExpr = new SizeOfAlignOfTypeExpr(true,
2098 returnType, Context->getSizeType(),
2099 SourceLocation(), SourceLocation());
2100 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2101 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2102 // For X86 it is more complicated and some kind of target specific routine
2103 // is needed to decide what to do.
Chris Lattner98be4942008-03-05 18:54:05 +00002104 unsigned IntSize =
2105 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002106 IntegerLiteral *limit = new IntegerLiteral(llvm::APInt(IntSize, 8),
2107 Context->IntTy,
2108 SourceLocation());
2109 BinaryOperator *lessThanExpr = new BinaryOperator(sizeofExpr, limit,
2110 BinaryOperator::LE,
2111 Context->IntTy,
2112 SourceLocation());
2113 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2114 ConditionalOperator *CondExpr =
2115 new ConditionalOperator(lessThanExpr, CE, STCE, returnType);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002116 ReplacingStmt = new ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002117 }
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002118 return ReplacingStmt;
2119}
2120
2121Stmt *RewriteTest::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2122 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Steve Naroff934f2762007-10-24 22:48:43 +00002123 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002124 ReplaceStmt(Exp, ReplacingStmt);
Steve Naroff934f2762007-10-24 22:48:43 +00002125
Chris Lattnere64b7772007-10-24 16:57:36 +00002126 delete Exp;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002127 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002128}
2129
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002130/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2131/// call to objc_getProtocol("proto-name").
2132Stmt *RewriteTest::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
2133 if (!GetProtocolFunctionDecl)
2134 SynthGetProtocolFunctionDecl();
2135 // Create a call to objc_getProtocol("ProtocolName").
2136 llvm::SmallVector<Expr*, 8> ProtoExprs;
2137 QualType argType = Context->getPointerType(Context->CharTy);
2138 ProtoExprs.push_back(new StringLiteral(Exp->getProtocol()->getName(),
2139 strlen(Exp->getProtocol()->getName()),
2140 false, argType, SourceLocation(),
2141 SourceLocation()));
2142 CallExpr *ProtoExp = SynthesizeCallToFunctionDecl(GetProtocolFunctionDecl,
2143 &ProtoExprs[0],
2144 ProtoExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002145 ReplaceStmt(Exp, ProtoExp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002146 delete Exp;
2147 return ProtoExp;
2148
2149}
2150
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002151/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002152/// an objective-c class with ivars.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002153void RewriteTest::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002154 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002155 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
2156 assert(CDecl->getName() && "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002157 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002158 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002159 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002160 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Steve Naroff03300712007-11-12 13:56:41 +00002161 int NumIvars = CDecl->getNumInstanceVariables();
Steve Narofffea763e82007-11-14 19:25:57 +00002162 SourceLocation LocStart = CDecl->getLocStart();
2163 SourceLocation LocEnd = CDecl->getLocEnd();
2164
2165 const char *startBuf = SM->getCharacterData(LocStart);
2166 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002167 // If no ivars and no root or if its root, directly or indirectly,
2168 // have no ivars (thus not synthesized) then no need to synthesize this class.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002169 if (NumIvars <= 0 && (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002170 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
Chris Lattneraadaf782008-01-31 19:51:04 +00002171 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002172 return;
2173 }
2174
2175 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002176 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002177 Result += "\nstruct ";
2178 Result += CDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002179 if (LangOpts.Microsoft)
2180 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002181
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002182 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002183 const char *cursor = strchr(startBuf, '{');
2184 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002185 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Narofffea763e82007-11-14 19:25:57 +00002186
2187 // rewrite the original header *without* disturbing the '{'
Chris Lattneraadaf782008-01-31 19:51:04 +00002188 ReplaceText(LocStart, cursor-startBuf-1, Result.c_str(), Result.size());
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002189 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002190 Result = "\n struct ";
2191 Result += RCDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002192 if (LangOpts.Microsoft)
2193 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002194
Steve Narofff69cc5d2008-01-30 19:17:43 +00002195 // Note: We don't name the field decl. This simplifies the "codegen" for
2196 // accessing a superclasses instance variables (and is similar to what gcc
2197 // does internally). The unnamed struct field feature is enabled with
2198 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2199 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002200 Result += ";\n";
2201
2202 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002203 SourceLocation OnePastCurly =
2204 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2205 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002206 }
2207 cursor++; // past '{'
2208
2209 // Now comment out any visibility specifiers.
2210 while (cursor < endBuf) {
2211 if (*cursor == '@') {
2212 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002213 // Skip whitespace.
2214 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2215 /*scan*/;
2216
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002217 // FIXME: presence of @public, etc. inside comment results in
2218 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002219 if (!strncmp(cursor, "public", strlen("public")) ||
2220 !strncmp(cursor, "private", strlen("private")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002221 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002222 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002223 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002224 // FIXME: If there are cases where '<' is used in ivar declaration part
2225 // of user code, then scan the ivar list and use needToScanForQualifiers
2226 // for type checking.
2227 else if (*cursor == '<') {
2228 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002229 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002230 cursor = strchr(cursor, '>');
2231 cursor++;
2232 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002233 InsertText(atLoc, " */", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002234 }
Steve Narofffea763e82007-11-14 19:25:57 +00002235 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002236 }
Steve Narofffea763e82007-11-14 19:25:57 +00002237 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002238 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002239 } else { // we don't have any instance variables - insert super struct.
2240 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM);
2241 Result += " {\n struct ";
2242 Result += RCDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002243 if (LangOpts.Microsoft)
2244 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002245
Steve Narofff69cc5d2008-01-30 19:17:43 +00002246 // Note: We don't name the field decl. This simplifies the "codegen" for
2247 // accessing a superclasses instance variables (and is similar to what gcc
2248 // does internally). The unnamed struct field feature is enabled with
2249 // -fms-extensions. If the struct definition were "inlined", we wouldn't
2250 // need to use this switch. That said, I don't want to inline the def.
Steve Narofffea763e82007-11-14 19:25:57 +00002251 Result += ";\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002252 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002253 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002254 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002255 if (!ObjCSynthesizedStructs.insert(CDecl))
2256 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002257}
2258
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002259// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002260/// class methods.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002261void RewriteTest::RewriteObjCMethodsMetaData(instmeth_iterator MethodBegin,
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002262 instmeth_iterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002263 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002264 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002265 const char *ClassName,
2266 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002267 if (MethodBegin == MethodEnd) return;
2268
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002269 static bool objc_impl_method = false;
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002270 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002271 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002272 SEL _cmd;
2273 char *method_types;
2274 void *_imp;
2275 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002276 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002277 Result += "\nstruct _objc_method {\n";
2278 Result += "\tSEL _cmd;\n";
2279 Result += "\tchar *method_types;\n";
2280 Result += "\tvoid *_imp;\n";
2281 Result += "};\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002282
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002283 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00002284 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002285
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002286 // Build _objc_method_list for class's methods if needed
Steve Naroff946a6932008-03-11 00:12:29 +00002287
2288 /* struct {
2289 struct _objc_method_list *next_method;
2290 int method_count;
2291 struct _objc_method method_list[];
2292 }
2293 */
2294 Result += "\nstatic struct {\n";
2295 Result += "\tstruct _objc_method_list *next_method;\n";
2296 Result += "\tint method_count;\n";
2297 Result += "\tstruct _objc_method method_list[";
2298 Result += utostr(MethodEnd-MethodBegin);
2299 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002300 Result += prefix;
2301 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2302 Result += "_METHODS_";
2303 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002304 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002305 Result += IsInstanceMethod ? "inst" : "cls";
2306 Result += "_meth\")))= ";
2307 Result += "{\n\t0, " + utostr(MethodEnd-MethodBegin) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002308
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002309 Result += "\t,{{(SEL)\"";
2310 Result += (*MethodBegin)->getSelector().getName().c_str();
2311 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002312 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002313 Result += "\", \"";
2314 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002315 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002316 Result += MethodInternalNames[*MethodBegin];
2317 Result += "}\n";
2318 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2319 Result += "\t ,{(SEL)\"";
2320 Result += (*MethodBegin)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002321 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002322 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002323 Result += "\", \"";
2324 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00002325 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002326 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00002327 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002328 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002329 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002330}
2331
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002332/// RewriteObjCProtocolsMetaData - Rewrite protocols meta-data.
2333void RewriteTest::RewriteObjCProtocolsMetaData(ObjCProtocolDecl **Protocols,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002334 int NumProtocols,
2335 const char *prefix,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002336 const char *ClassName,
2337 std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002338 static bool objc_protocol_methods = false;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002339 if (NumProtocols > 0) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002340 for (int i = 0; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002341 ObjCProtocolDecl *PDecl = Protocols[i];
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002342 // Output struct protocol_methods holder of method selector and type.
2343 if (!objc_protocol_methods &&
2344 (PDecl->getNumInstanceMethods() > 0
2345 || PDecl->getNumClassMethods() > 0)) {
2346 /* struct protocol_methods {
2347 SEL _cmd;
2348 char *method_types;
2349 }
2350 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002351 Result += "\nstruct protocol_methods {\n";
2352 Result += "\tSEL _cmd;\n";
2353 Result += "\tchar *method_types;\n";
2354 Result += "};\n";
2355
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002356 objc_protocol_methods = true;
2357 }
2358 int NumMethods = PDecl->getNumInstanceMethods();
2359 if(NumMethods > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002360 /* struct _objc_protocol_method_list {
2361 int protocol_method_count;
2362 struct protocol_methods protocols[];
2363 }
2364 */
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002365 Result += "\nstatic struct {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002366 Result += "\tint protocol_method_count;\n";
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002367 Result += "\tstruct protocol_methods protocols[";
2368 Result += utostr(NumMethods);
2369 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002370 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002371 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002372 "{\n\t" + utostr(NumMethods) + "\n";
2373
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002374 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002375 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002376 E = PDecl->instmeth_end(); I != E; ++I) {
2377 if (I == PDecl->instmeth_begin())
2378 Result += "\t ,{{(SEL)\"";
2379 else
2380 Result += "\t ,{(SEL)\"";
2381 Result += (*I)->getSelector().getName().c_str();
2382 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002383 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanianfc591ac2007-12-17 17:56:10 +00002384 Result += "\", \"";
2385 Result += MethodTypeString;
2386 Result += "\"}\n";
2387 }
2388 Result += "\t }\n};\n";
2389 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002390
2391 // Output class methods declared in this protocol.
2392 NumMethods = PDecl->getNumClassMethods();
2393 if (NumMethods > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002394 /* struct _objc_protocol_method_list {
2395 int protocol_method_count;
2396 struct protocol_methods protocols[];
2397 }
2398 */
2399 Result += "\nstatic struct {\n";
2400 Result += "\tint protocol_method_count;\n";
2401 Result += "\tstruct protocol_methods protocols[";
2402 Result += utostr(NumMethods);
2403 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002404 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002405 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002406 "{\n\t";
2407 Result += utostr(NumMethods);
2408 Result += "\n";
2409
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002410 // Output instance methods declared in this protocol.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002411 for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
Fariborz Jahanianc6e2c2a2007-12-17 18:07:01 +00002412 E = PDecl->classmeth_end(); I != E; ++I) {
2413 if (I == PDecl->classmeth_begin())
2414 Result += "\t ,{{(SEL)\"";
2415 else
2416 Result += "\t ,{(SEL)\"";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002417 Result += (*I)->getSelector().getName().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002418 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00002420 Result += "\", \"";
2421 Result += MethodTypeString;
2422 Result += "\"}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002423 }
2424 Result += "\t }\n};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002425 }
2426 // Output:
2427 /* struct _objc_protocol {
2428 // Objective-C 1.0 extensions
2429 struct _objc_protocol_extension *isa;
2430 char *protocol_name;
2431 struct _objc_protocol **protocol_list;
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002432 struct _objc_protocol_method_list *instance_methods;
2433 struct _objc_protocol_method_list *class_methods;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002434 };
2435 */
2436 static bool objc_protocol = false;
2437 if (!objc_protocol) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002438 Result += "\nstruct _objc_protocol {\n";
2439 Result += "\tstruct _objc_protocol_extension *isa;\n";
2440 Result += "\tchar *protocol_name;\n";
2441 Result += "\tstruct _objc_protocol **protocol_list;\n";
2442 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
2443 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
2444 Result += "};\n";
2445
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002446 objc_protocol = true;
2447 }
2448
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002449 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
2450 Result += PDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002451 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002452 "{\n\t0, \"";
2453 Result += PDecl->getName();
2454 Result += "\", 0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002455 if (PDecl->getNumInstanceMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002456 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002457 Result += PDecl->getName();
2458 Result += ", ";
2459 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002460 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002461 Result += "0, ";
Steve Naroff58dbdeb2007-12-14 23:37:57 +00002462 if (PDecl->getNumClassMethods() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002463 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002464 Result += PDecl->getName();
2465 Result += "\n";
2466 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002467 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002468 Result += "0\n";
2469 Result += "};\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002470 }
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002471 // Output the top lovel protocol meta-data for the class.
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002472 /* struct _objc_protocol_list {
2473 struct _objc_protocol_list *next;
2474 int protocol_count;
2475 struct _objc_protocol *class_protocols[];
2476 }
2477 */
2478 Result += "\nstatic struct {\n";
2479 Result += "\tstruct _objc_protocol_list *next;\n";
2480 Result += "\tint protocol_count;\n";
2481 Result += "\tstruct _objc_protocol *class_protocols[";
2482 Result += utostr(NumProtocols);
2483 Result += "];\n} _OBJC_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002484 Result += prefix;
2485 Result += "_PROTOCOLS_";
2486 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002487 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002488 "{\n\t0, ";
2489 Result += utostr(NumProtocols);
2490 Result += "\n";
2491
2492 Result += "\t,{&_OBJC_PROTOCOL_";
2493 Result += Protocols[0]->getName();
2494 Result += " \n";
2495
2496 for (int i = 1; i < NumProtocols; i++) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002497 ObjCProtocolDecl *PDecl = Protocols[i];
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002498 Result += "\t ,(struct _objc_protocol_list*)&_OBJC_PROTOCOL_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002499 Result += PDecl->getName();
2500 Result += "\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002501 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002502 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002503 }
2504}
2505
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002506/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002507/// implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002508void RewriteTest::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002509 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002510 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002511 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002512 ObjCCategoryDecl *CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002513 for (CDecl = ClassDecl->getCategoryList(); CDecl;
2514 CDecl = CDecl->getNextClassCategory())
2515 if (CDecl->getIdentifier() == IDecl->getIdentifier())
2516 break;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002517
Chris Lattnereb44eee2007-12-23 01:40:15 +00002518 std::string FullCategoryName = ClassDecl->getName();
2519 FullCategoryName += '_';
2520 FullCategoryName += IDecl->getName();
2521
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002522 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002523 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002524 true, "CATEGORY_", FullCategoryName.c_str(),
2525 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002526
2527 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002528 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00002529 false, "CATEGORY_", FullCategoryName.c_str(),
2530 Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002531
2532 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002533 // Null CDecl is case of a category implementation with no category interface
2534 if (CDecl)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002535 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002536 CDecl->getNumReferencedProtocols(),
2537 "CATEGORY",
Chris Lattnereb44eee2007-12-23 01:40:15 +00002538 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002539
2540 /* struct _objc_category {
2541 char *category_name;
2542 char *class_name;
2543 struct _objc_method_list *instance_methods;
2544 struct _objc_method_list *class_methods;
2545 struct _objc_protocol_list *protocols;
2546 // Objective-C 1.0 extensions
2547 uint32_t size; // sizeof (struct _objc_category)
2548 struct _objc_property_list *instance_properties; // category's own
2549 // @property decl.
2550 };
2551 */
2552
2553 static bool objc_category = false;
2554 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002555 Result += "\nstruct _objc_category {\n";
2556 Result += "\tchar *category_name;\n";
2557 Result += "\tchar *class_name;\n";
2558 Result += "\tstruct _objc_method_list *instance_methods;\n";
2559 Result += "\tstruct _objc_method_list *class_methods;\n";
2560 Result += "\tstruct _objc_protocol_list *protocols;\n";
2561 Result += "\tunsigned int size;\n";
2562 Result += "\tstruct _objc_property_list *instance_properties;\n";
2563 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002564 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002565 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002566 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
2567 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00002568 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002569 Result += IDecl->getName();
2570 Result += "\"\n\t, \"";
2571 Result += ClassDecl->getName();
2572 Result += "\"\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002573
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002574 if (IDecl->getNumInstanceMethods() > 0) {
2575 Result += "\t, (struct _objc_method_list *)"
2576 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
2577 Result += FullCategoryName;
2578 Result += "\n";
2579 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002580 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002581 Result += "\t, 0\n";
2582 if (IDecl->getNumClassMethods() > 0) {
2583 Result += "\t, (struct _objc_method_list *)"
2584 "&_OBJC_CATEGORY_CLASS_METHODS_";
2585 Result += FullCategoryName;
2586 Result += "\n";
2587 }
2588 else
2589 Result += "\t, 0\n";
2590
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00002591 if (CDecl && CDecl->getNumReferencedProtocols() > 0) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002592 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
2593 Result += FullCategoryName;
2594 Result += "\n";
2595 }
2596 else
2597 Result += "\t, 0\n";
2598 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002599}
2600
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002601/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
2602/// ivar offset.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002603void RewriteTest::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
2604 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002605 std::string &Result) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002606 Result += "offsetof(struct ";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002607 Result += IDecl->getName();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002608 if (LangOpts.Microsoft)
2609 Result += "_IMPL";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002610 Result += ", ";
2611 Result += ivar->getName();
2612 Result += ")";
2613}
2614
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002615//===----------------------------------------------------------------------===//
2616// Meta Data Emission
2617//===----------------------------------------------------------------------===//
2618
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002619void RewriteTest::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002620 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002621 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002622
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002623 // Explictly declared @interface's are already synthesized.
2624 if (CDecl->ImplicitInterfaceDecl()) {
2625 // FIXME: Implementation of a class with no @interface (legacy) doese not
2626 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002627 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00002628 }
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002629
Chris Lattnerbe6df082007-12-12 07:56:42 +00002630 // Build _objc_ivar_list metadata for classes ivars if needed
2631 int NumIvars = IDecl->getImplDeclNumIvars() > 0
2632 ? IDecl->getImplDeclNumIvars()
2633 : (CDecl ? CDecl->getNumInstanceVariables() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002634 if (NumIvars > 0) {
2635 static bool objc_ivar = false;
2636 if (!objc_ivar) {
2637 /* struct _objc_ivar {
2638 char *ivar_name;
2639 char *ivar_type;
2640 int ivar_offset;
2641 };
2642 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002643 Result += "\nstruct _objc_ivar {\n";
2644 Result += "\tchar *ivar_name;\n";
2645 Result += "\tchar *ivar_type;\n";
2646 Result += "\tint ivar_offset;\n";
2647 Result += "};\n";
2648
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002649 objc_ivar = true;
2650 }
2651
Steve Naroff946a6932008-03-11 00:12:29 +00002652 /* struct {
2653 int ivar_count;
2654 struct _objc_ivar ivar_list[nIvars];
2655 };
2656 */
2657 Result += "\nstatic struct {\n";
2658 Result += "\tint ivar_count;\n";
2659 Result += "\tstruct _objc_ivar ivar_list[";
2660 Result += utostr(NumIvars);
2661 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002662 Result += IDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002663 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002664 "{\n\t";
2665 Result += utostr(NumIvars);
2666 Result += "\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002667
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002668 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattnerbe6df082007-12-12 07:56:42 +00002669 if (IDecl->getImplDeclNumIvars() > 0) {
2670 IVI = IDecl->ivar_begin();
2671 IVE = IDecl->ivar_end();
2672 } else {
2673 IVI = CDecl->ivar_begin();
2674 IVE = CDecl->ivar_end();
2675 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002676 Result += "\t,{{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002677 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002678 Result += "\", \"";
2679 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002680 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2681 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002682 Result += StrEncoding;
2683 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002684 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002685 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002686 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002687 Result += "\t ,{\"";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002688 Result += (*IVI)->getName();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002689 Result += "\", \"";
2690 std::string StrEncoding;
Fariborz Jahanian7d6b46d2008-01-22 22:44:46 +00002691 Context->getObjCEncodingForType((*IVI)->getType(), StrEncoding,
2692 EncodingRecordTypes);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00002693 Result += StrEncoding;
2694 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00002695 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002696 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002697 }
2698
2699 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002700 }
2701
2702 // Build _objc_method_list for class's instance methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002703 RewriteObjCMethodsMetaData(IDecl->instmeth_begin(), IDecl->instmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002704 true, "", IDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002705
2706 // Build _objc_method_list for class's class methods if needed
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002707 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002708 false, "", IDecl->getName(), Result);
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002709
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002710 // Protocols referenced in class declaration?
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002711 RewriteObjCProtocolsMetaData(CDecl->getReferencedProtocols(),
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002712 CDecl->getNumIntfRefProtocols(),
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002713 "CLASS", CDecl->getName(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002714
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002715
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002716 // Declaration of class/meta-class metadata
2717 /* struct _objc_class {
2718 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002719 const char *super_class_name;
2720 char *name;
2721 long version;
2722 long info;
2723 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002724 struct _objc_ivar_list *ivars;
2725 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002726 struct objc_cache *cache;
2727 struct objc_protocol_list *protocols;
2728 const char *ivar_layout;
2729 struct _objc_class_ext *ext;
2730 };
2731 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002732 static bool objc_class = false;
2733 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002734 Result += "\nstruct _objc_class {\n";
2735 Result += "\tstruct _objc_class *isa;\n";
2736 Result += "\tconst char *super_class_name;\n";
2737 Result += "\tchar *name;\n";
2738 Result += "\tlong version;\n";
2739 Result += "\tlong info;\n";
2740 Result += "\tlong instance_size;\n";
2741 Result += "\tstruct _objc_ivar_list *ivars;\n";
2742 Result += "\tstruct _objc_method_list *methods;\n";
2743 Result += "\tstruct objc_cache *cache;\n";
2744 Result += "\tstruct _objc_protocol_list *protocols;\n";
2745 Result += "\tconst char *ivar_layout;\n";
2746 Result += "\tstruct _objc_class_ext *ext;\n";
2747 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002748 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002749 }
2750
2751 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002752 ObjCInterfaceDecl *RootClass = 0;
2753 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002754 while (SuperClass) {
2755 RootClass = SuperClass;
2756 SuperClass = SuperClass->getSuperClass();
2757 }
2758 SuperClass = CDecl->getSuperClass();
2759
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002760 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
2761 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002762 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002763 "{\n\t(struct _objc_class *)\"";
2764 Result += (RootClass ? RootClass->getName() : CDecl->getName());
2765 Result += "\"";
2766
2767 if (SuperClass) {
2768 Result += ", \"";
2769 Result += SuperClass->getName();
2770 Result += "\", \"";
2771 Result += CDecl->getName();
2772 Result += "\"";
2773 }
2774 else {
2775 Result += ", 0, \"";
2776 Result += CDecl->getName();
2777 Result += "\"";
2778 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002779 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002780 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002781 Result += ", 0,2, sizeof(struct _objc_class), 0";
Steve Naroffb26d7132007-12-05 21:49:40 +00002782 if (IDecl->getNumClassMethods() > 0) {
Steve Naroff23f41272008-03-11 18:14:26 +00002783 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Steve Naroffb26d7132007-12-05 21:49:40 +00002784 Result += IDecl->getName();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002785 Result += "\n";
2786 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002787 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002788 Result += ", 0\n";
2789 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002790 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002791 Result += CDecl->getName();
2792 Result += ",0,0\n";
2793 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00002794 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002795 Result += "\t,0,0,0,0\n";
2796 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002797
2798 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002799 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
2800 Result += CDecl->getName();
Steve Naroffdbb65432008-03-12 17:18:30 +00002801 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002802 "{\n\t&_OBJC_METACLASS_";
2803 Result += CDecl->getName();
2804 if (SuperClass) {
2805 Result += ", \"";
2806 Result += SuperClass->getName();
2807 Result += "\", \"";
2808 Result += CDecl->getName();
2809 Result += "\"";
2810 }
2811 else {
2812 Result += ", 0, \"";
2813 Result += CDecl->getName();
2814 Result += "\"";
2815 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002816 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002817 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002818 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002819 Result += ",0";
2820 else {
2821 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002822 Result += ",sizeof(struct ";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002823 Result += CDecl->getName();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00002824 if (LangOpts.Microsoft)
2825 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00002826 Result += ")";
2827 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002828 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002829 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002830 Result += CDecl->getName();
2831 Result += "\n\t";
2832 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002833 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002834 Result += ",0";
2835 if (IDecl->getNumInstanceMethods() > 0) {
Steve Naroff946a6932008-03-11 00:12:29 +00002836 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002837 Result += CDecl->getName();
2838 Result += ", 0\n\t";
2839 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002840 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002841 Result += ",0,0";
2842 if (CDecl->getNumIntfRefProtocols() > 0) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00002843 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002844 Result += CDecl->getName();
2845 Result += ", 0,0\n";
2846 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00002847 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002848 Result += ",0,0,0\n";
2849 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00002850}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002851
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002852/// RewriteImplementations - This routine rewrites all method implementations
2853/// and emits meta-data.
2854
2855void RewriteTest::RewriteImplementations(std::string &Result) {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002856 int ClsDefCount = ClassImplementation.size();
2857 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002858
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002859 if (ClsDefCount == 0 && CatDefCount == 0)
2860 return;
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002861 // Rewrite implemented methods
2862 for (int i = 0; i < ClsDefCount; i++)
2863 RewriteImplementationDecl(ClassImplementation[i]);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002864
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00002865 for (int i = 0; i < CatDefCount; i++)
2866 RewriteImplementationDecl(CategoryImplementation[i]);
2867
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002868 // This is needed for use of offsetof
2869 Result += "#include <stddef.h>\n";
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00002870
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002871 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002872 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002873 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002874
2875 // For each implemented category, write out all its meta data.
2876 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002877 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00002878
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002879 // Write objc_symtab metadata
2880 /*
2881 struct _objc_symtab
2882 {
2883 long sel_ref_cnt;
2884 SEL *refs;
2885 short cls_def_cnt;
2886 short cat_def_cnt;
2887 void *defs[cls_def_cnt + cat_def_cnt];
2888 };
2889 */
2890
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002891 Result += "\nstruct _objc_symtab {\n";
2892 Result += "\tlong sel_ref_cnt;\n";
2893 Result += "\tSEL *refs;\n";
2894 Result += "\tshort cls_def_cnt;\n";
2895 Result += "\tshort cat_def_cnt;\n";
2896 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
2897 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002898
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002899 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00002900 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002901 Result += "\t0, 0, " + utostr(ClsDefCount)
2902 + ", " + utostr(CatDefCount) + "\n";
2903 for (int i = 0; i < ClsDefCount; i++) {
2904 Result += "\t,&_OBJC_CLASS_";
2905 Result += ClassImplementation[i]->getName();
2906 Result += "\n";
2907 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002908
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002909 for (int i = 0; i < CatDefCount; i++) {
2910 Result += "\t,&_OBJC_CATEGORY_";
2911 Result += CategoryImplementation[i]->getClassInterface()->getName();
2912 Result += "_";
2913 Result += CategoryImplementation[i]->getName();
2914 Result += "\n";
2915 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002916
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002917 Result += "};\n\n";
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002918
2919 // Write objc_module metadata
2920
2921 /*
2922 struct _objc_module {
2923 long version;
2924 long size;
2925 const char *name;
2926 struct _objc_symtab *symtab;
2927 }
2928 */
2929
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002930 Result += "\nstruct _objc_module {\n";
2931 Result += "\tlong version;\n";
2932 Result += "\tlong size;\n";
2933 Result += "\tconst char *name;\n";
2934 Result += "\tstruct _objc_symtab *symtab;\n";
2935 Result += "};\n\n";
2936 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00002937 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002938 Result += "\t" + utostr(OBJC_ABI_VERSION) +
2939 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00002940 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00002941
2942 if (LangOpts.Microsoft) {
2943 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
2944 Result += "#pragma data_seq(push, \".objc_module_info$B\")\n";
2945 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
2946 Result += "&_OBJC_MODULES;\n";
2947 Result += "#pragma data_seg(pop)\n\n";
2948 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00002949}
Chris Lattner311ff022007-10-16 22:36:42 +00002950